
    6bi                    R   S r SSKrSSKrSSKrSSKrSSKrSSKrSSKJ	r	  SSK
Jr  SSK
Jr  SSK
Jr  SSKJr   SSKrSSKJr  SS	KJr   SS
KJr  \" S5       " S S\R,                  5      5       rS rS r " S S5      r\" S5       " S S\\5      5       r\" S5       " S S\5      5       rS r " S S\\5      rS r\" S5       " S S5      5       r \" S5            S2S  j5       r!\" S!5            S2S" j5       r"\" S#5            S2S$ j5       r#\" S%5            S2S& j5       r$\" S'5      S3S( j5       r%\" S)5      S3S* j5       r&\" S+5      S4S, j5       r'\" S-5      S4S. j5       r(S/ r)\" S05                  S5S1 j5       r*g! \ a     GNLf = f! \ a    Sr GNTf = f)6at  Utilies for image preprocessing and augmentation.

Deprecated: `tf.keras.preprocessing.image` APIs do not operate on tensors and
are not recommended for new code. Prefer loading data with
`tf.keras.utils.image_dataset_from_directory`, and then transforming the output
`tf.data.Dataset` with preprocessing layers. For more information, see the
tutorials for [loading images](
https://www.tensorflow.org/tutorials/load_data/images) and [augmenting images](
https://www.tensorflow.org/tutorials/images/data_augmentation), as well as the
[preprocessing layer guide](
https://www.tensorflow.org/guide/tf_keras/preprocessing_layers).
    N)backend)
data_utils)image_utils)io_utils)keras_export)linalg)ndimage)ImageEnhancez"keras.preprocessing.image.Iteratorc                   ^    \ rS rSrSrSrS rS rS rS r	S r
S	 rS
 rS rS rS rS rSrg)Iterator:   a  Base class for image data iterators.

Deprecated: `tf.keras.preprocessing.image.Iterator` is not recommended for
new code. Prefer loading images with
`tf.keras.utils.image_dataset_from_directory` and transforming the output
`tf.data.Dataset` with preprocessing layers. For more information, see the
tutorials for [loading images](
https://www.tensorflow.org/tutorials/load_data/images) and
[augmenting images](
https://www.tensorflow.org/tutorials/images/data_augmentation), as well as
the [preprocessing layer guide](
https://www.tensorflow.org/guide/tf_keras/preprocessing_layers).

Every `Iterator` must implement the `_get_batches_of_transformed_samples`
method.

Args:
    n: Integer, total number of samples in the dataset to loop over.
    batch_size: Integer, size of a batch.
    shuffle: Boolean, whether to shuffle the data between epochs.
    seed: Random seeding for data shuffling.
)pngjpgjpegbmpppmtiftiffc                     Xl         X l        X@l        X0l        SU l        SU l        [        R                  " 5       U l        S U l	        U R                  5       U l        g Nr   )n
batch_sizeseedshufflebatch_indextotal_batches_seen	threadingLocklockindex_array_flow_indexindex_generator)selfr   r   r   r   s        Z/home/james-whalen/.local/lib/python3.13/site-packages/tf_keras/src/preprocessing/image.py__init__Iterator.__init__U   sM    $	"#NN$	#//1    c                     [         R                  " U R                  5      U l        U R                  (       a/  [         R
                  R                  U R                  5      U l        g g N)nparanger   r    r   randompermutationr#   s    r$   _set_index_arrayIterator._set_index_array`   s>    99TVV,<<!yy44TVV<D r'   c                    U[        U 5      :  a"  [        SR                  U[        U 5      S95      eU R                  b6  [        R
                  R                  U R                  U R                  -   5        U =R                  S-  sl        U R                  c  U R                  5         U R                  U R                  U-  U R                  US-   -   nU R                  U5      $ )NzEAsked to retrieve element {idx}, but the Sequence has length {length})idxlength   )len
ValueErrorformatr   r*   r,   r   r    r/   r   #_get_batches_of_transformed_samples)r#   r2   r    s      r$   __getitem__Iterator.__getitem__e   s    #d)&&,fSYf&G 
 99 IINN499t'>'>>?1$#!!#&&OOc!DOOsQw$?
 77DDr'   c                 T    U R                   U R                  -   S-
  U R                  -  $ )Nr4   )r   r   r.   s    r$   __len__Iterator.__len__v   s#    (1,@@r'   c                 $    U R                  5         g r)   )r/   r.   s    r$   on_epoch_endIterator.on_epoch_endy   s    r'   c                     SU l         g r   )r   r.   s    r$   resetIterator.reset|   s
    r'   c              #   @  #    U R                  5          U R                  b6  [        R                  R                  U R                  U R                  -   5        U R
                  S:X  a  U R                  5         U R                  S:X  a  SnO&U R
                  U R                  -  U R                  -  nU R                  XR                  -   :  a  U =R
                  S-  sl        OSU l        U =R                  S-  sl        U R                  XU R                  -    v   GM
  7f)Nr4   r   )
rB   r   r*   r,   r   r   r/   r   r   r    )r#   current_indexs     r$   r!   Iterator._flow_index   s     

yy$		tyy4+B+BBC1$%%'vv{ !!%!1!1DOO!Ctvv Mvv77  A% #$ ##q(#"" ? ! s   DDc                     U $ r)    r.   s    r$   __iter__Iterator.__iter__   s	     r'   c                 &    U R                   " U0 UD6$ r)   )next)r#   argskwargss      r$   __next__Iterator.__next__   s    yy$)&))r'   c                     U R                      [        U R                  5      nSSS5        U R                  W5      $ ! , (       d  f       N= f)z.For python 2.x.

Returns:
    The next batch.
N)r   rL   r"   r8   r#   r    s     r$   rL   Iterator.next   s;     YYt334K  77DD	 Ys	   <
A
c                     [         e)Gets a batch of transformed samples.

Args:
    index_array: Array of sample indices to include in batch.
Returns:
    A batch of transformed samples.
)NotImplementedErrorrR   s     r$   r8   ,Iterator._get_batches_of_transformed_samples   s
     "!r'   )	r   r   r    r"   r   r   r   r   r   N)__name__
__module____qualname____firstlineno____doc__white_list_formatsr%   r/   r9   r<   r?   rB   r!   rI   rO   rL   r8   __static_attributes__rH   r'   r$   r   r   :   sJ    . M	2=
E"A .
*
E"r'   r   c              #   ,  ^#    U4S jnU" U 5       H}  u  pEn[        U5       Hh  nUR                  5       R                  S5      (       a  [        R                  " S5        UR                  5       R                  U5      (       d  Mc  XG4v   Mj     M     g7f)az  Iterates on files with extension.

Args:
    directory: Absolute path to the directory
        containing files to be counted
    white_list_formats: Set of strings containing allowed extensions for
        the files to be counted.
    follow_links: Boolean, follow symbolic links to subdirectories.
Yields:
    Tuple of (root, filename) with extension in `white_list_formats`.
c                 @   > [        [        R                  " U TS9S S9$ )N)followlinksc                     U S   $ r   rH   xs    r$   <lambda><_iter_valid_files.<locals>._recursive_list.<locals>.<lambda>   s    adr'   )key)sortedoswalk)subpathfollow_linkss    r$   _recursive_list*_iter_valid_files.<locals>._recursive_list   s     GGG6N
 	
r'   z.tiffzYUsing ".tiff" files with multiple bands will cause distortion. Please verify your output.N)rh   lowerendswithwarningswarn)	directoryr]   rl   rm   root_filesfnames     `     r$   _iter_valid_filesrx      sy     

 *)4E]E{{}%%g..H {{}%%&899k! # 5s   A?BBc                    [         R                  R                  U 5      nU(       aF  [        [	        XU5      5      n[        U5      n[        US   U-  5      [        US   U-  5      pXhU	 n
O[	        XU5      n
/ n/ nU
 H  u  pUR                  X5   5        [         R                  R                  X5      n[         R                  R                  U[         R                  R                  X5      5      nUR                  U5        M     X4$ )a  Lists paths of files in `subdir` with extensions in `white_list_formats`.

Args:
    directory: absolute path to a directory containing the files to list.
        The directory name is used as class label
        and must be a key of `class_indices`.
    white_list_formats: set of strings containing allowed extensions for
        the files to be counted.
    split: tuple of floats (e.g. `(0.2, 0.6)`) to only take into
        account a certain fraction of files in each directory.
        E.g.: `segment=(0.6, 1.0)` would only account for last 40 percent
        of images in each directory.
    class_indices: dictionary mapping a class name to its index.
    follow_links: boolean, follow symbolic links to subdirectories.

Returns:
     classes: a list of class indices
     filenames: the path of valid files in `directory`, relative from
         `directory`'s parent (e.g., if `directory` is "dataset/class1",
        the filenames will be
        `["class1/file1.jpg", "class1/file2.jpg", ...]`).
r   r4   )
ri   pathbasenamelistrx   r5   intappendjoinrelpath)rs   r]   splitclass_indicesrl   dirname	all_files	num_filesstartstopvalid_filesclasses	filenamesrt   rw   absolute_pathrelative_paths                    r$   "_list_valid_filenames_in_directoryr      s    2 ggy)Gi\J
	 	N	%(Y./U1X	5I1Jtd+'<
 GI"}-.T1RWW__]>
 	' # r'   c                   T    \ rS rSrSrS rS r\S 5       r\S 5       r	\S 5       r
Srg	)
BatchFromFilesMixini  ztAdds methods related to getting batches from filenames.

It includes the logic to transform image files to batches.
c                    Xl         [        U5      U l        Xl        US;  a  [	        SUS5      eX0l        X@l        U R
                  S:X  a:  U R                  S:X  a  U R                  S-   U l        OSU R                  -   U l        OU R
                  S:X  a:  U R                  S:X  a  U R                  S-   U l        ONSU R                  -   U l        O9U R                  S:X  a  U R                  S	-   U l        OS	U R                  -   U l        XPl        X`l	        Xpl
        Xl        Ub<  U R                   R                  nUS:X  a  SU4nOUS:X  a  US4nO[	        SU< S35      eS
nXl        Xl        g
)a&  Sets attributes to use later for processing files into a batch.

Args:
    image_data_generator: Instance of `ImageDataGenerator`
        to use for random transformations and normalization.
    target_size: tuple of integers, dimensions to resize input images
    to.
    color_mode: One of `"rgb"`, `"rgba"`, `"grayscale"`.
        Color mode to read images.
    data_format: String, one of `channels_first`, `channels_last`.
    save_to_dir: Optional directory where to save the pictures
        being yielded, in a viewable format. This is useful
        for visualizing the random transformations being
        applied, for debugging purposes.
    save_prefix: String prefix to use for saving sample
        images (if `save_to_dir` is set).
    save_format: Format to use for saving sample images
        (if `save_to_dir` is set).
    subset: Subset of data (`"training"` or `"validation"`) if
        validation_split is set in ImageDataGenerator.
    interpolation: Interpolation method used to resample the image if
        the target size is different from that of the loaded image.
        Supported methods are "nearest", "bilinear", and "bicubic". If
        PIL version 1.1.3 or newer is installed, "lanczos" is also
        supported. If PIL version 3.4.0 or newer is installed, "box" and
        "hamming" are also supported. By default, "nearest" is used.
    keep_aspect_ratio: Boolean, whether to resize images to a target
        size without aspect ratio distortion. The image is cropped in
        the center with target aspect ratio before resizing.
>   rgbrgba	grayscalezInvalid color mode:z); expected "rgb", "rgba", or "grayscale".r   channels_last)   r   )   )r4   N
validationr   trainingr4   zInvalid subset name: z$;expected "training" or "validation")image_data_generatortupletarget_sizekeep_aspect_ratior6   
color_modedata_formatimage_shapesave_to_dirsave_prefixsave_formatinterpolation_validation_splitr   subset)r#   r   r   r   r   r   r   r   r   r   r   validation_splitr   s                r$   set_processing_attrs(BatchFromFilesMixin.set_processing_attrs
  sz   V %9! -!299%; 
 %&??f$?2#'#3#3d#: #'$*:*:#: __%?2#'#3#3d#: #'$*:*:#: ?2#'#3#3d#: #'$*:*:#: &&&*#88JJ%,-:%)1- =CF 
 E
r'   c           	         [         R                  " [        U5      4U R                  -   U R                  S9nU R
                  n[        U5       H  u  pE[        R                  " X5   U R                  U R                  U R                  U R                  S9n[        R                  " X`R                  S9n[        US5      (       a  UR!                  5         U R"                  (       a[  U R"                  R%                  UR&                  5      nU R"                  R)                  Xx5      nU R"                  R+                  U5      nXrU'   M     U R,                  (       a  [        U5       H  u  pE[        R.                  " X$   U R                  SS9nSR1                  U R2                  U[         R4                  R7                  S5      U R8                  S	9n	UR;                  [<        R>                  RA                  U R,                  U	5      5        M     U RB                  S
:X  a  URE                  5       n
GO$U RB                  S;   aN  [         RF                  " [        U5      U R                  S9n
[        U5       H  u  pKU RH                  U   X'   M     OU RB                  S:X  ae  [         R                  " [        U5      [        U RJ                  5      4U R                  S9n
[        U5       H  u  pKSXU RH                  U   4'   M     OQU RB                  S:X  a  U RL                   Vs/ s H  oU   PM	     n
nO"U RB                  S:X  a  U RL                  U   n
OU$ U RN                  c  X*4$ X*U RN                  U   4$ s  snf )rU   dtype)r   r   r   r   )r   closeTscale {prefix}_{index}_{hash}.{format}g    cAprefixindexhashr7   input>   binarysparsecategoricalg      ?multi_outputraw)(r*   zerosr5   r   r   	filepaths	enumerater   load_imgr   r   r   r   img_to_arrayr   hasattrr   r   get_random_transformshapeapply_transformstandardizer   array_to_imgr7   r   r,   randintr   saveri   rz   r   
class_modecopyemptyr   r   labelssample_weight)r#   r    batch_xr   ijimgrd   paramsrw   batch_yn_observationoutputs                r$   r8   7BatchFromFilesMixin._get_batches_of_transformed_samplesc  s    (($"2"22$**

 NN	k*DA&&?? ,,"00"&"8"8C ((:J:JKA sG$$		((22GGP--==aH--99!<AJ# +& !+.!..J 0 0 ;AA++**3/++	 B  d&6&6>? / ??g%llnG__ 44hhs7|4::>G$-k$: !\\-8
 %;__-hhWs4#5#567tzzG %.k$: :=4<<667 %;__.9=Evk*GEG__%kk+.GN%##T%7%7%DDD Fs   M2c                 \    [        SR                  [        U 5      R                  5      5      e)z&List of absolute paths to image files.z;`filepaths` property method has not been implemented in {}.rV   r7   typerX   r.   s    r$   r   BatchFromFilesMixin.filepaths  s*     "&&,fT$Z-@-@&A
 	
r'   c                 \    [        SR                  [        U 5      R                  5      5      e)z"Class labels of every observation.z8`labels` property method has not been implemented in {}.r   r.   s    r$   r   BatchFromFilesMixin.labels  s,     "FMMT
##
 	
r'   c                 \    [        SR                  [        U 5      R                  5      5      e)Nz?`sample_weight` property method has not been implemented in {}.r   r.   s    r$   r   !BatchFromFilesMixin.sample_weight  s(    !&&,fT$Z-@-@&A
 	
r'   )r   r   r   r   r   r   r   r   r   r   r   r   N)rX   rY   rZ   r[   r\   r   r8   propertyr   r   r   r^   rH   r'   r$   r   r     sR    
WrCEJ 
 
 
 
 
 
r'   r   z+keras.preprocessing.image.DirectoryIteratorc                      ^  \ rS rSrSr1 Skr                S	U 4S jjr\S 5       r\S 5       r	\S 5       r
SrU =r$ )
DirectoryIteratori  a)  Iterator capable of reading images from a directory on disk.

Deprecated: `tf.keras.preprocessing.image.DirectoryIterator` is not
recommended for new code. Prefer loading images with
`tf.keras.utils.image_dataset_from_directory` and transforming the output
`tf.data.Dataset` with preprocessing layers. For more information, see the
tutorials for [loading images](
https://www.tensorflow.org/tutorials/load_data/images) and
[augmenting images](
https://www.tensorflow.org/tutorials/images/data_augmentation), as well as
the [preprocessing layer guide](
https://www.tensorflow.org/guide/tf_keras/preprocessing_layers).

Args:
    directory: Path to the directory to read images from. Each subdirectory
      in this directory will be considered to contain images from one class,
      or alternatively you could specify class subdirectories via the
      `classes` argument.
    image_data_generator: Instance of `ImageDataGenerator` to use for random
      transformations and normalization.
    target_size: tuple of integers, dimensions to resize input images to.
    color_mode: One of `"rgb"`, `"rgba"`, `"grayscale"`. Color mode to read
      images.
    classes: Optional list of strings, names of subdirectories containing
      images from each class (e.g. `["dogs", "cats"]`). It will be computed
      automatically if not set.
    class_mode: Mode for yielding the targets:
        - `"binary"`: binary targets (if there are only two classes),
        - `"categorical"`: categorical targets,
        - `"sparse"`: integer targets,
        - `"input"`: targets are images identical to input images (mainly
          used to work with autoencoders),
        - `None`: no targets get yielded (only input images are yielded).
    batch_size: Integer, size of a batch.
    shuffle: Boolean, whether to shuffle the data between epochs.
    seed: Random seed for data shuffling.
    data_format: String, one of `channels_first`, `channels_last`.
    save_to_dir: Optional directory where to save the pictures being
      yielded, in a viewable format. This is useful for visualizing the
      random transformations being applied, for debugging purposes.
    save_prefix: String prefix to use for saving sample images (if
      `save_to_dir` is set).
    save_format: Format to use for saving sample images (if `save_to_dir` is
      set).
    subset: Subset of data (`"training"` or `"validation"`) if
      validation_split is set in ImageDataGenerator.
    interpolation: Interpolation method used to resample the image if the
      target size is different from that of the loaded image. Supported
      methods are "nearest", "bilinear", and "bicubic". If PIL version 1.1.3
      or newer is installed, "lanczos" is also supported. If PIL version
      3.4.0 or newer is installed, "box" and "hamming" are also supported.
      By default, "nearest" is used.
    keep_aspect_ratio: Boolean, whether to resize images to a target size
        without aspect ratio distortion. The image is cropped in the center
        with target aspect ratio before resizing.
    dtype: Dtype to use for generated arrays.
>   Nr   r   r   r   c                   >^ U
c  [         R                  " 5       n
Uc  [         R                  " 5       n[        TU ]  UUUU
UUUUUU5
        TU l        XPl        X`R                  ;  a$  [        SR                  X`R                  5      5      eX`l
        UU l        SU l        U(       d}  / n[        [        R                  " T5      5       HX  n[        R                   R#                  [        R                   R%                  TU5      5      (       d  MG  UR'                  U5        MZ     [)        U5      U l        [-        [/        U[1        [)        U5      5      5      5      U l        [4        R6                  R9                  5       n/ n/ U l        SnU4S jU 5        HK  nUR'                  UR=                  [>        UU R@                  U RB                  U R2                  U45      5        MM     / nU H<  nURE                  5       u  nnUR'                  U5        U =R:                  U-  sl        M>     [)        U R:                  5      U l        [F        RH                  " U R                  4SS9U l        U H+  nXPR                  UU[)        U5      -   & U[)        U5      -  nM-     [J        RL                  " SU R                   SU R*                   S35        URO                  5         UR%                  5         U R:                   Vs/ s H-  n[        R                   R%                  U R
                  U5      PM/     snU l(        [        TU ]  U R                  XxU	5        g s  snf )	N+Invalid class_mode: {}; expected one of: {}r   c              3   d   >#    U  H%  n[         R                  R                  TU5      v   M'     g 7fr)   )ri   rz   r   ).0subdirrs   s     r$   	<genexpr>-DirectoryIterator.__init__.<locals>.<genexpr>@  s#     NgFY77gs   -0int32r   Found z images belonging to 	 classes.)*r   image_data_formatfloatxsuperr   rs   r   allowed_class_modesr6   r7   r   r   samplesrh   ri   listdirrz   isdirr   r~   r5   num_classesdictzipranger   multiprocessingpool
ThreadPoolr   apply_asyncr   r]   r   getr*   r   r   	print_msgr   
_filepathsr%   )r#   rs   r   r   r   r   r   r   r   r   r   r   r   r   rl   r   r   r   r   r   r   resultsr   dirpathclasses_listresr   rw   	__class__s    `                          r$   r%   DirectoryIterator.__init__  s   * !335K=NN$E$ 	
 #555=DD 8 8 
 %
G I!6777==i!@AANN6* 8 w<!#guS\/B"CD##..0 NgNGNN  6//

**$	 O C!$GY(NNi'N  4>>*xxw?#G18LLQW-.WA $ 	T\\N"7 	+	
 	

		=A^^
=KEBGGLL/^
 	zDA
s   64Mc                     U R                   $ r)   r   r.   s    r$   r   DirectoryIterator.filepathsc      r'   c                     U R                   $ r)   )r   r.   s    r$   r   DirectoryIterator.labelsg  s    ||r'   c                     g r)   rH   r.   s    r$   r   DirectoryIterator.sample_weightk  s     r'   )	r   r   r   r   rs   r   r   r   r   )   r  r   Nr       TNNN r   FNnearestFN)rX   rY   rZ   r[   r\   r   r%   r   r   r   r   r^   __classcell__r   s   @r$   r   r     s    8t M  'bBH      r'   r   z,keras.preprocessing.image.NumpyArrayIteratorc                   L   ^  \ rS rSrSr           SU 4S jjrS rSrU =r$ )NumpyArrayIteratoriq  a  Iterator yielding data from a Numpy array.

Deprecated: `tf.keras.preprocessing.image.NumpyArrayIterator` is not
recommended for new code. Prefer loading images with
`tf.keras.utils.image_dataset_from_directory` and transforming the output
`tf.data.Dataset` with preprocessing layers. For more information, see the
tutorials for [loading images](
https://www.tensorflow.org/tutorials/load_data/images) and
[augmenting images](
https://www.tensorflow.org/tutorials/images/data_augmentation), as well as
the [preprocessing layer guide](
https://www.tensorflow.org/guide/tf_keras/preprocessing_layers).

Args:
    x: Numpy array of input data or tuple. If tuple, the second elements is
      either another numpy array or a list of numpy arrays, each of which
      gets passed through as an output without any modifications.
    y: Numpy array of targets data.
    image_data_generator: Instance of `ImageDataGenerator` to use for random
      transformations and normalization.
    batch_size: Integer, size of a batch.
    shuffle: Boolean, whether to shuffle the data between epochs.
    sample_weight: Numpy array of sample weights.
    seed: Random seed for data shuffling.
    data_format: String, one of `channels_first`, `channels_last`.
    save_to_dir: Optional directory where to save the pictures being
      yielded, in a viewable format. This is useful for visualizing the
      random transformations being applied, for debugging purposes.
    save_prefix: String prefix to use for saving sample images (if
      `save_to_dir` is set).
    save_format: Format to use for saving sample images (if `save_to_dir` is
      set).
    subset: Subset of data (`"training"` or `"validation"`) if
      validation_split is set in ImageDataGenerator.
    ignore_class_split: Boolean (default: False), ignore difference
      in number of classes in labels across train and validation
      split (useful for non-classification tasks)
    dtype: Dtype to use for the generated arrays.
c           	      	  > Uc  [         R                  " 5       nUc  [         R                  " 5       nXl        [	        U[
        5      (       d  [	        U[        5      (       a  [	        US   [        5      (       d  [        R                  " US   5      /nO)US    Vs/ s H  n[        R                  " U5      PM     nnUS   nU H@  n[        U5      [        U5      :w  d  M  [        S[        U5      < S[        U5      < 35      e   O/ nUbg  [        U5      [        U5      :w  aO  [        S[        R                  " U5      R                  < S[        R                  " U5      R                  < 35      eUbg  [        U5      [        U5      :w  aO  [        S[        R                  " U5      R                  < S[        R                  " U5      R                  < 35      eUGb  US	;  a  [        S
US5      e[        [        U5      UR                  -  5      nUb\  U(       dU  [        R                  " [        R                  " US U 5      [        R                  " UUS  5      5      (       d  [        S5      eUS:X  a7  US U nU Vs/ s H  n[        R                  " US U 5      PM     nnUb  US U nO6UUS  nU Vs/ s H  n[        R                  " UUS  5      PM     nnUb  UUS  n[        R                  " XR                  S9U l        Xl        U R                   R$                  S:w  a   [        SU R                   R                  5      eUS:X  a  SOSnU R                   R                  U   S;  a  [&        R(                  " SU-   S-   [+        U5      -   S-   [+        U5      -   S-   [+        U R                   R                  5      -   S-   [+        U R                   R                  U   5      -   S-   5        Ub  [        R                  " U5      U l        OS U l        Ub  [        R                  " U5      U l        OS U l        X0l        Xl        Xl        Xl        Xl        [:        TU ]y  UR                  S   XEU5        g s  snf s  snf s  snf )Nr4   r   zUAll of the arrays in `x` should have the same length. Found a pair with: len(x[0]) = z, len(x[?]) = zS`x` (images tensor) and `y` (labels) should have the same length. Found: x.shape = z, y.shape = zV`x` (images tensor) and `sample_weight` should have the same length. Found: x.shape = z, sample_weight.shape = >   r   r   zInvalid subset name:z&; expected "training" or "validation".zTraining and validation subsets have different number of classes after the split. If your numpy arrays are sorted by the label, you might want to shuffle them.r   r   r   zUInput data in `NumpyArrayIterator` should have rank 4. You passed an array with shaper   r      r4   r   r   z=NumpyArrayIterator is set to use the data format convention "" (channels on axis z4), i.e. expected either 1, 3, or 4 channels on axis -. However, it was passed an array with shape  ( channels).)r   r   r   r   
isinstancer   r|   r*   asarrayr5   r6   r   r}   r   array_equaluniquerd   x_miscndimrq   rr   stryr   r   r   r   r   r   r   r%   )r#   rd   r   r   r   r   r   r   r   r   r   r   r   ignore_class_splitr   r  xx	split_idxchannels_axisr   s                      r$   r%   NumpyArrayIterator.__init__  s   " !335K=NN$E
a:a#6#6adD))**QqT*+34Q484R"**R.48!Aq6SW$$ q63r7,   F=SVs1v- ::a=&&

1(;(;=  $Q3}3E)E ::a=&&

=(A(G(GI  77 *< 
 CF%9%K%KKLI *IIa
m,bii)*.F  !'  %jyM?EFv"**R
^4vF=*9AijM?EFv"**R	
^4vF=)*AAZZ066;;! 	  )O;66<<&i7MMO() m$% I	I
 m$% BB dffll#$  dffll=12	3  
  =ZZ]DFDF$!#M!:D!%D$8!&&&&Z$?G 9j G
 Gs    R #R=#R
c                 Z   [         R                  " [        [        U5      /[	        U R
                  R                  5      SS  -   5      U R                  S9n[        U5       H  u  p4U R
                  U   nU R                  R                  UR                  5      nU R                  R                  UR                  U R                  5      U5      nU R                  R                  U5      nXRU'   M     U R                  (       a  [        U5       H  u  p4[        R                   " X#   U R"                  SS9nSR%                  U R&                  U[         R(                  R+                  S5      U R,                  S9nUR/                  [0        R2                  R5                  U R                  U5      5        M     U R6                   V	s/ s H  oU   PM	     n
n	U
(       d  UOU/U
-   4nU R8                  c  US   $ XR8                  U   4-  nU R:                  b  XR:                  U   4-  nU$ s  sn	f )	Nr4   r   Tr   r   g     @r   r   )r*   r   r   r5   r|   rd   r   r   r   r   r   r   astyper   r   r   r   r   r7   r   r,   r   r   r   ri   rz   r   r  r   r   )r#   r    r   r   r   rd   r   r   rw   r"  batch_x_miscsr   s               r$   r8   6NumpyArrayIterator._get_batches_of_transformed_samples  s   ((3{#$tDFFLL'9!"'==>djj
 k*DAq	A..CCAGGLF))99$fA ))55a8AAJ + !+.!..J 0 0 ;AA++**3/++	 B  d&6&6>? / 48;;?;RK;?!.'WI4MO66>!966+&(()))+688F @s   H()
r   r   r   r   r   r   r   rd   r  r   )r  FNNNNr  r   NFN)	rX   rY   rZ   r[   r\   r%   r8   r^   r  r  s   @r$   r  r  q  s>    &Z  }@~   r'   r  c                     U R                  5       R                  U5      =(       a    [        R                  R	                  U 5      $ )zCheck if a filename refers to a valid file.

Args:
    filename: String, absolute path to a file
    white_list_formats: Set, allowed file extensions
Returns:
    A boolean value indicating if the filename is valid or not
)ro   rp   ri   rz   isfile)filenamer]   s     r$   validate_filenamer-  =  s6     >>$$%78 RWW^^> r'   c                      ^  \ rS rSrSr1 Skr                     SU 4S jjrS rS r\	S 5       r
S r\S	 5       r\S
 5       r\S 5       rSrU =r$ )DataFrameIteratoriK  a`  Iterator capable of reading images from a directory as a dataframe.

Args:
    dataframe: Pandas dataframe containing the filepaths relative to
      `directory` (or absolute paths if `directory` is None) of the images
      in a string column. It should include other column/s depending on the
      `class_mode`: - if `class_mode` is `"categorical"` (default value) it
      must include the `y_col` column with the class/es of each image.
      Values in column can be string/list/tuple if a single class or
      list/tuple if multiple classes.
        - if `class_mode` is `"binary"` or `"sparse"` it must include the
          given `y_col` column with class values as strings.
        - if `class_mode` is `"raw"` or `"multi_output"` it should contain
          the columns specified in `y_col`.
        - if `class_mode` is `"input"` or `None` no extra column is needed.
    directory: string, path to the directory to read images from. If `None`,
      data in `x_col` column should be absolute paths.
    image_data_generator: Instance of `ImageDataGenerator` to use for random
      transformations and normalization. If None, no transformations and
      normalizations are made.
    x_col: string, column in `dataframe` that contains the filenames (or
      absolute paths if `directory` is `None`).
    y_col: string or list, column/s in `dataframe` that has the target data.
    weight_col: string, column in `dataframe` that contains the sample
        weights. Default: `None`.
    target_size: tuple of integers, dimensions to resize input images to.
    color_mode: One of `"rgb"`, `"rgba"`, `"grayscale"`. Color mode to read
      images.
    classes: Optional list of strings, classes to use (e.g. `["dogs",
      "cats"]`). If None, all classes in `y_col` will be used.
    class_mode: one of "binary", "categorical", "input", "multi_output",
      "raw", "sparse" or None. Default: "categorical".
      Mode for yielding the targets:
        - `"binary"`: 1D numpy array of binary labels,
        - `"categorical"`: 2D numpy array of one-hot encoded labels.
          Supports multi-label output.
        - `"input"`: images identical to input images (mainly used to work
          with autoencoders),
        - `"multi_output"`: list with the values of the different columns,
        - `"raw"`: numpy array of values in `y_col` column(s),
        - `"sparse"`: 1D numpy array of integer labels, - `None`, no targets
          are returned (the generator will only yield batches of image data,
          which is useful to use in `model.predict()`).
    batch_size: Integer, size of a batch.
    shuffle: Boolean, whether to shuffle the data between epochs.
    seed: Random seed for data shuffling.
    data_format: String, one of `channels_first`, `channels_last`.
    save_to_dir: Optional directory where to save the pictures being
      yielded, in a viewable format. This is useful for visualizing the
      random transformations being applied, for debugging purposes.
    save_prefix: String prefix to use for saving sample images (if
      `save_to_dir` is set).
    save_format: Format to use for saving sample images (if `save_to_dir` is
      set).
    subset: Subset of data (`"training"` or `"validation"`) if
      validation_split is set in ImageDataGenerator.
    interpolation: Interpolation method used to resample the image if the
      target size is different from that of the loaded image. Supported
      methods are "nearest", "bilinear", and "bicubic". If PIL version 1.1.3
      or newer is installed, "lanczos" is also supported. If PIL version
      3.4.0 or newer is installed, "box" and "hamming" are also supported.
      By default, "nearest" is used.
    keep_aspect_ratio: Boolean, whether to resize images to a target size
      without aspect ratio distortion. The image is cropped in the center
      with target aspect ratio before resizing.
    dtype: Dtype to use for the generated arrays.
    validate_filenames: Boolean, whether to validate image filenames in
      `x_col`. If `True`, invalid images will be ignored. Disabling this
      option can lead to speed-up in the instantiation of this class.
      Default: `True`.
>   Nr   r   r   r   r   r   c                   > [         TU ]  UUUUUUUUUU5
        UR                  5       nU=(       d    SU l        Xl        UU l        U R                  UXEXi5        U(       a  U R                  UU5      nU
S;  aL  U R                  UXY5      u  nn	[        U	5      n[        [        U	[        [        U	5      5      5      5      U l        U R                  (       aV  [        U5      n[        U R                  S   U-  5      n[        U R                  S   U-  5      nUR                   UU2S S 24   nU
S;  a  U R#                  UU5      U l        UU   R'                  5       U l        U(       a  UU   R*                  OS U l        U
S:X  a=  U Vs/ s H*  n[.        R0                  " UU   R'                  5       5      PM,     snU l        U
S:X  a  UU   R*                  U l        [        U R(                  5      U l        U(       a  SOSnU
S;   a(  [6        R8                  " S	U R4                   S
U S35        O*[6        R8                  " S	U R4                   S
U SW S35        U R(                   Vs/ s H-  n[:        R<                  R?                  U R                  U5      PM/     snU l         [         TU ]  U R4                  XU5        g s  snf s  snf )Nr  )r   r   r   Nr   r4   r   r   	validatedznon-validatedr    z image filenames.z image filenames belonging to r   )"r   r   r   rs   r   r   _check_params_filter_valid_filepaths_filter_classesr5   r   r   r   r   r   r}   ilocget_classesr   tolistr   values_sample_weightr*   array_targetsr   r   r   ri   rz   r   r   r%   ) r#   	dataframers   r   x_coly_col
weight_colr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   validate_filenamesdfr   r   r   r   colvalidated_stringrw   r   s                                   r$   r%   DataFrameIterator.__init__  s   2 	$ 	
 ^^"b$
2uZA--b%8BCC..r5BKBg,K!%c'5W3F&G!HD::BI

1	12Etzz!}y01DtQ'BCC++B6DLE))+7Abn33t'CHI5CRXXbgnn&675IDMuI,,DM4>>*-K? 	 ??a(8'99JK a(8'9 :  +}I7
 >B^^
=KEBGGLL/^
 	zDA' J 
s   1J>&4Kc                   ^ U R                   U R                  ;  a/  [        SR                  U R                   U R                  5      5      eU R                   S:X  aM  [	        U[
        5      (       d8  [        SR                  U R                   [        U5      R                  5      5      e[        X   R                  S 5      5      (       d  [        SU S35      eU R                   S;   aG  [        X   R                  S 5      5      (       d%  [        S	R                  U R                   U5      5      eU R                   S
:X  a  U(       a>  [        U5      n[        U5      S:w  a#  [        SR                  [        U5      5      5      eO@X   R                  5       S:w  a*  [        SR                  X   R                  5       5      5      eU R                   S:X  a[  [        [
        [        4m[        X   R                  U4S j5      5      (       d%  [        SR                  U R                   U5      5      eU(       a?  U R                   S;   a/  [         R"                  " SR                  U R                   5      5        U(       aE  [%        X   R&                  R                  [(        R*                  5      (       d  [        SU S35      eg g )Nr   r   z6If class_mode="{}", y_col must be a list. Received {}.c                 "    [        U [        5      $ r)   r  r  rc   s    r$   re   1DataFrameIterator._check_params.<locals>.<lambda>  s    Z3-?r'   zAll values in column x_col=z must be strings.>   r   r   c                 "    [        U [        5      $ r)   rH  rc   s    r$   re   rI    s    As1Cr'   z=If class_mode="{}", y_col="{}" column values must be strings.r      zGIf class_mode="binary" there must be 2 classes. {} class/es were given.zAIf class_mode="binary" there must be 2 classes. Found {} classes.r   c                    > [        U T5      $ r)   )r  )rd   typess    r$   re   rI  !  s    Au1Er'   zPIf class_mode="{}", y_col="{}" column values must be type string, list or tuple.>   Nr   r   r   z3`classes` will be ignored given the class_mode="{}"zColumn weight_col=z must be numeric.)r   r   r6   r7   r  r|   	TypeErrorr   rX   allapplysetr5   nuniquer  r   rq   rr   
issubclassr   r*   number)r#   rB  r>  r?  r@  r   rM  s         @r$   r3  DataFrameIterator._check_params  sZ   ??$":"::=DDOOT%=%=  OO~-z%7N7NHOOOOT%[%9%9  29??#?@AA-eW4EF  ??22ry'CDEE..4fT__e.L 
 ??h&g,w<1$$;;A6#g,;O  %
 ""$) ((.ry/@/@/B(C 
 ??m+$&Ery'EFGGAAGB  t +
 
 MMELLOO j)=)=)B)BBIINN0<MNOO O:r'   c                     / nX    Hl  n[        U[        [        45      (       a0  UR                  U Vs/ s H  oPR                  U   PM     sn5        MN  UR                  U R                  U   5        Mn     U$ s  snf r)   )r  r|   r   r~   r   )r#   rB  r?  r   labellbls         r$   r7  DataFrameIterator.get_classes8  sl    YE%$//%H%311#6%HId0078	 
  Is   A9
c                   ^^^ U R                  5       n U4S jmT(       aS  [        [        R                  R	                  T5      R                  5       5      mU T   R                  UU4S j5      U T'   O`[        5       mU T    HB  n[        U[        [        45      (       a  TR                  U5        M1  TR                  U5        MD     [        T5      mU R                  T/S9T4$ )Nc                   > [        U [        [        45      (       a$  U  Vs/ s H  o"U;   d  M
  UPM     n nU =(       d    S $ [        U [        5      (       a	  X;   a  U $ S $ [	        SR                  [        U 5      T5      5      es  snf )Nz7Expect string, list or tuple but found {} in {} column )r  r|   r   r  rN  r7   r   )r   r   clsr?  s      r$   remove_classes9DataFrameIterator._filter_classes.<locals>.remove_classesE  s{    &4-00)/B#'>#B~%FC((!'!2v<<117Ve1L  Cs
   	BBc                    > T" U T5      $ r)   rH   )rd   r   r]  s    r$   re   3DataFrameIterator._filter_classes.<locals>.<lambda>T  s    .G2Lr'   )r   )r   r|   collectionsOrderedDictfromkeyskeysrP  rQ  r  r   updateaddrh   dropna)rB  r?  r   vr]  s    `` @r$   r5  !DataFrameIterator._filter_classesA  s    WWY
	 ;22;;GDIIKLG5	(LMBuIeGYa$//NN1%KKN	 
 WoGyyy('11r'   c                    ^  X   R                  U 4S j5      nUR                  [        T R                  4S9nU) R	                  5       nU(       a%  [
        R                  " SR                  XR5      5        X   $ )zKeep only dataframe rows with valid filenames.

Args:
    df: Pandas dataframe containing filenames in a column
    x_col: string, column in `df` that contains the filenames or
        filepaths
Returns:
    absolute paths to image files
c                 X   > [         R                  R                  TR                  U 5      $ r)   )ri   rz   r   rs   )rw   r#   s    r$   re   ;DataFrameIterator._filter_valid_filepaths.<locals>.<lambda>j  s    "'',,t~~u=r'   )rM   zTFound {} invalid image filename(s) in x_col="{}". These filename(s) will be ignored.)maprP  r-  r]   sumrq   rr   r7   )r#   rB  r>  r   mask	n_invalids   `     r$   r4  )DataFrameIterator._filter_valid_filepaths_  sq     IMM=
	 T%<%<$>  
 UKKM	MM55;VI5M xr'   c                     U R                   $ r)   r  r.   s    r$   r   DataFrameIterator.filepathsw  r  r'   c                 R    U R                   S;   a  U R                  $ U R                  $ )N>   r   r   )r   r<  r   r.   s    r$   r   DataFrameIterator.labels{  s#    ??55== <<r'   c                     U R                   $ r)   )r:  r.   s    r$   r   DataFrameIterator.sample_weight  s    """r'   )
r   r:  r<  r   r   r   rs   r   r   r   )NNr,  classNr
  r   Nr   r  TNr   Nr  r   Nr  Ffloat32T)rX   rY   rZ   r[   r\   r   r%   r3  r7  staticmethodr5  r4  r   r   r   r   r^   r  r  s   @r$   r/  r/  K  s    FP ! #/TBlBPH 2 2:0       # #r'   r/  c                     [         R                  " U 5      R                  US5      n U S S S2S4   n U R                  SU5      n U $ )Nr   .)r*   r  swapaxes)rd   axiss     r$   	flip_axisr    sB    


1tQ'A	$B$)A	

1dAHr'   z,keras.preprocessing.image.ImageDataGeneratorc                       \ rS rSrSr                       SS jr          SS jr              SS jr                 SS jrS r	SS	 jr
S
 rSS jrSS jrSrg)ImageDataGeneratori  a4  Generate batches of tensor image data with real-time data augmentation.

Deprecated: `tf.keras.preprocessing.image.ImageDataGenerator` is not
recommended for new code. Prefer loading images with
`tf.keras.utils.image_dataset_from_directory` and transforming the output
`tf.data.Dataset` with preprocessing layers. For more information, see the
tutorials for [loading images](
https://www.tensorflow.org/tutorials/load_data/images) and
[augmenting images](
https://www.tensorflow.org/tutorials/images/data_augmentation), as well as
the [preprocessing layer guide](
https://www.tensorflow.org/guide/tf_keras/preprocessing_layers).

 The data will be looped over (in batches).

Args:
    featurewise_center: Boolean. Set input mean to 0 over the dataset,
      feature-wise.
    samplewise_center: Boolean. Set each sample mean to 0.
    featurewise_std_normalization: Boolean. Divide inputs by std of the
      dataset, feature-wise.
    samplewise_std_normalization: Boolean. Divide each input by its std.
    zca_epsilon: epsilon for ZCA whitening. Default is 1e-6.
    zca_whitening: Boolean. Apply ZCA whitening.
    rotation_range: Int. Degree range for random rotations.
    width_shift_range: Float, 1-D array-like or int
        - float: fraction of total width, if < 1, or pixels if >= 1.
        - 1-D array-like: random elements from the array.
        - int: integer number of pixels from interval `(-width_shift_range,
          +width_shift_range)` - With `width_shift_range=2` possible values
          are integers `[-1, 0, +1]`, same as with `width_shift_range=[-1,
          0, +1]`, while with `width_shift_range=1.0` possible values are
          floats in the interval [-1.0, +1.0).
    height_shift_range: Float, 1-D array-like or int
        - float: fraction of total height, if < 1, or pixels if >= 1.
        - 1-D array-like: random elements from the array.
        - int: integer number of pixels from interval `(-height_shift_range,
          +height_shift_range)` - With `height_shift_range=2` possible
          values are integers `[-1, 0, +1]`, same as with
          `height_shift_range=[-1, 0, +1]`, while with
          `height_shift_range=1.0` possible values are floats in the
          interval [-1.0, +1.0).
    brightness_range: Tuple or list of two floats. Range for picking a
      brightness shift value from.
    shear_range: Float. Shear Intensity (Shear angle in counter-clockwise
      direction in degrees)
    zoom_range: Float or [lower, upper]. Range for random zoom. If a float,
      `[lower, upper] = [1-zoom_range, 1+zoom_range]`.
    channel_shift_range: Float. Range for random channel shifts.
    fill_mode: One of {"constant", "nearest", "reflect" or "wrap"}. Default
      is 'nearest'. Points outside the boundaries of the input are filled
      according to the given mode:
        - 'constant': kkkkkkkk|abcd|kkkkkkkk (cval=k)
        - 'nearest':  aaaaaaaa|abcd|dddddddd
        - 'reflect':  abcddcba|abcd|dcbaabcd
        - 'wrap':  abcdabcd|abcd|abcdabcd
    cval: Float or Int. Value used for points outside the boundaries when
      `fill_mode = "constant"`.
    horizontal_flip: Boolean. Randomly flip inputs horizontally.
    vertical_flip: Boolean. Randomly flip inputs vertically.
    rescale: rescaling factor. If None or 0, no rescaling
      is applied, otherwise we multiply the data by the value provided
      (after applying all other transformations). Defaults to `None`.
    preprocessing_function: function that will be applied on each input. The
      function will run after the image is resized and augmented.
        The function should take one argument: one image (Numpy tensor with
          rank 3), and should output a Numpy tensor with the same shape.
    data_format: Image data format, either "channels_first" or
      "channels_last". "channels_last" mode means that the images should
      have shape `(samples, height, width, channels)`, "channels_first" mode
      means that the images should have shape `(samples, channels, height,
      width)`. When unspecified, uses `image_data_format` value found in
      your TF-Keras config file at `~/.keras/keras.json` (if exists) else
      'channels_last'. Defaults to "channels_last".
    validation_split: Float. Fraction of images reserved for validation
      (strictly between 0 and 1).
    dtype: Dtype to use for the generated arrays.

Raises:
  ValueError: If the value of the argument, `data_format` is other than
        `"channels_last"` or `"channels_first"`.
  ValueError: If the value of the argument, `validation_split` > 1
        or `validation_split` < 0.

Examples:

Example of using `.flow(x, y)`:

```python
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
y_train = utils.to_categorical(y_train, num_classes)
y_test = utils.to_categorical(y_test, num_classes)
datagen = ImageDataGenerator(
    featurewise_center=True,
    featurewise_std_normalization=True,
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2,
    horizontal_flip=True,
    validation_split=0.2)
# compute quantities required for featurewise normalization
# (std, mean, and principal components if ZCA whitening is applied)
datagen.fit(x_train)
# fits the model on batches with real-time data augmentation:
model.fit(datagen.flow(x_train, y_train, batch_size=32,
         subset='training'),
         validation_data=datagen.flow(x_train, y_train,
         batch_size=8, subset='validation'),
         steps_per_epoch=len(x_train) / 32, epochs=epochs)
# here's a more "manual" example
for e in range(epochs):
    print('Epoch', e)
    batches = 0
    for x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=32):
        model.fit(x_batch, y_batch)
        batches += 1
        if batches >= len(x_train) / 32:
            # we need to break the loop by hand because
            # the generator loops indefinitely
            break
```

Example of using `.flow_from_directory(directory)`:

```python
train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
        'data/train',
        target_size=(150, 150),
        batch_size=32,
        class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
        'data/validation',
        target_size=(150, 150),
        batch_size=32,
        class_mode='binary')
model.fit(
        train_generator,
        steps_per_epoch=2000,
        epochs=50,
        validation_data=validation_generator,
        validation_steps=800)
```

Example of transforming images and masks together.

```python
# we create two instances with the same arguments
data_gen_args = dict(featurewise_center=True,
                     featurewise_std_normalization=True,
                     rotation_range=90,
                     width_shift_range=0.1,
                     height_shift_range=0.1,
                     zoom_range=0.2)
image_datagen = ImageDataGenerator(**data_gen_args)
mask_datagen = ImageDataGenerator(**data_gen_args)
# Provide the same seed and keyword arguments to the fit and flow methods
seed = 1
image_datagen.fit(images, augment=True, seed=seed)
mask_datagen.fit(masks, augment=True, seed=seed)
image_generator = image_datagen.flow_from_directory(
    'data/images',
    class_mode=None,
    seed=seed)
mask_generator = mask_datagen.flow_from_directory(
    'data/masks',
    class_mode=None,
    seed=seed)
# combine generators into one which yields image and masks
train_generator = zip(image_generator, mask_generator)
model.fit(
    train_generator,
    steps_per_epoch=2000,
    epochs=50)
```
Nc                 0   Uc  [         R                  " 5       nUc  [         R                  " 5       nXl        X l        X0l        X@l        XPl        X`l        Xpl	        Xl
        Xl        Xl        Xl        Xl        Xl        Xl        UU l        UU l        UU l        UU l        UU l        UU l        US;  a  [/        SU-  5      eUU l        US:X  a  SU l        SU l        SU l        US:X  a  SU l        SU l        SU l        U(       a  SUs=:  a  S:  d  O  [/        S	U-  5      eUU l        S U l        S U l        S U l        [A        U[B        [D        45      (       a  SU-
  SU-   /U l        OE[G        U5      S:X  a'  [I        S
 U 5       5      (       a  US   US   /U l        O[/        SU< 35      eU(       aH  U(       d  SU l        [J        RL                  " S5        U(       a  SU l        [J        RL                  " S5        U(       a$  U(       d  SU l        [J        RL                  " S5        U(       a$  U(       d  SU l        [J        RL                  " S5        U
b9  [A        U
[N        [P        45      (       a  [G        U
5      S:w  a  [/        SU
< 35      eXl)        g )N>   r   channels_firstz`data_format` should be `"channels_last"` (channel after row and column) or `"channels_first"` (channel before row and column). Received: %sr  r4   rK  r   r   r   zB`validation_split` must be strictly between 0 and 1.  Received: %sc              3   N   #    U  H  n[        U[        [        45      v   M     g 7fr)   )r  floatr}   )r   vals     r$   r   .ImageDataGenerator.__init__.<locals>.<genexpr>  s!      *
5?cJsUCL))Zs   #%zK`zoom_range` should be a float or a tuple or list of two floats. Received: TzcThis ImageDataGenerator specifies `zca_whitening`, which overrides setting of `featurewise_center`.FzlThis ImageDataGenerator specifies `zca_whitening` which overrides setting of`featurewise_std_normalization`.zsThis ImageDataGenerator specifies `featurewise_std_normalization`, which overrides setting of `featurewise_center`.zqThis ImageDataGenerator specifies `samplewise_std_normalization`, which overrides setting of `samplewise_center`.C`brightness_range should be tuple or list of two floats. Received: )*r   r   r   featurewise_centersamplewise_centerfeaturewise_std_normalizationsamplewise_std_normalizationzca_whiteningzca_epsilonrotation_rangewidth_shift_rangeheight_shift_rangeshear_range
zoom_rangechannel_shift_range	fill_modecvalhorizontal_flipvertical_fliprescalepreprocessing_functionr   interpolation_orderr6   r   channel_axisrow_axiscol_axisr   meanstdzca_whitening_matrixr  r  r}   r5   rO  rq   rr   r   r|   brightness_range)r#   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   r  r   s                           r$   r%   ImageDataGenerator.__init__F  s   4 !335K=NN$E"4!2-J*,H)*&,!2"4&$#6 "	.*&<#
#6 AA "--  '** !DDMDM/) !DDMDMA(8$<1$< "23  "2	$(!j5#,// :~q:~>DO_!c *
5?*
 '
 '
  *!}jm<DO #-/ 
 %*.'7
 -5:27 )%*.', ($)-&+ '/%??'(A- &69  !1r'   c                 V    [        UUU UUUUU R                  UUU	U
UU R                  S9$ )aA  Takes data & label arrays, generates batches of augmented data.

Args:
    x: Input data. Numpy array of rank 4 or a tuple. If tuple, the first
      element should contain the images and the second element another
      numpy array or a list of numpy arrays that gets passed to the
      output without any modifications. Can be used to feed the model
      miscellaneous data along with the images. In case of grayscale
      data, the channels axis of the image array should have value 1, in
      case of RGB data, it should have value 3, and in case of RGBA
      data, it should have value 4.
    y: Labels.
    batch_size: Int (default: 32).
    shuffle: Boolean (default: True).
    sample_weight: Sample weights.
    seed: Int (default: None).
    save_to_dir: None or str (default: None). This allows you to
      optionally specify a directory to which to save the augmented
      pictures being generated (useful for visualizing what you are
      doing).
    save_prefix: Str (default: `''`). Prefix to use for filenames of
      saved pictures (only relevant if `save_to_dir` is set).
    save_format: one of "png", "jpeg", "bmp", "pdf", "ppm", "gif",
      "tif", "jpg" (only relevant if `save_to_dir` is set). Default:
      "png".
    ignore_class_split: Boolean (default: False), ignore difference
      in number of classes in labels across train and validation
      split (useful for non-classification tasks)
    subset: Subset of data (`"training"` or `"validation"`) if
      `validation_split` is set in `ImageDataGenerator`.

Returns:
    An `Iterator` yielding tuples of `(x, y)`
        where `x` is a numpy array of image data
        (in the case of a single image input) or a list
        of numpy arrays (in the case with
        additional inputs) and `y` is a numpy array
        of corresponding labels. If 'sample_weight' is not None,
        the yielded tuples are of the form `(x, y, sample_weight)`.
        If `y` is None, only the numpy array `x` is returned.
Raises:
  ValueError: If the Value of the argument, `subset` is other than
        "training" or "validation".

)r   r   r   r   r   r   r   r   r!  r   r   )r  r   r   )r#   rd   r   r   r   r   r   r   r   r   r!  r   s               r$   flowImageDataGenerator.flow  sF    v "!'((###1**
 	
r'   c                     [        UU 40 SU_SU_SU_SU_SU_SU R                  _SU_SU_S	U_S
U	_SU
_SU_SU_SU_SU_SU R                  _6$ )ao  Takes the path to a directory & generates batches of augmented data.

Args:
  directory: string, path to the target directory. It should contain
    one subdirectory per class. Any PNG, JPG, BMP, PPM or TIF images
    inside each of the subdirectories directory tree will be included
    in the generator. See [this script](
    https://gist.github.com/fchollet/0830affa1f7f19fd47b06d4cf89ed44d)
    for more details.
  target_size: Tuple of integers `(height, width)`. The dimensions to
    which all images found will be resized. Defaults to `(256,256)`.
  color_mode: One of "grayscale", "rgb", "rgba". Default: "rgb".
    Whether the images will be converted to have 1, 3, or 4 channels.
  classes: Optional list of class subdirectories (e.g. `['dogs',
    'cats']`). Default: None. If not provided, the list of classes
    will be automatically inferred from the subdirectory
    names/structure under `directory`, where each subdirectory will be
    treated as a different class (and the order of the classes, which
    will map to the label indices, will be alphanumeric). The
    dictionary containing the mapping from class names to class
    indices can be obtained via the attribute `class_indices`.
  class_mode: One of "categorical", "binary", "sparse",
    "input", or None.
    Determines the type of label arrays that are returned:
      - "categorical" will be 2D one-hot encoded labels,
      - "binary" will be 1D binary labels,
      - "sparse" will be 1D integer labels,
      - "input" will be images identical
        to input images (mainly used to work with autoencoders).
      - If None, no labels are returned
        (the generator will only yield batches of image data,
        which is useful to use with `model.predict_generator()`).
        Please note that in case of class_mode None,
        the data still needs to reside in a subdirectory
        of `directory` for it to work correctly.
      Defaults to "categorical".
  batch_size: Size of the batches of data. Defaults to `32`.
  shuffle: Whether to shuffle the data If `False`, sorts the
    data in alphanumeric order. Defaults to `True`.
  seed: Optional random seed for shuffling and transformations.
  save_to_dir: None or str (default: None). This allows you to
    optionally specify a directory to which to save the augmented
    pictures being generated (useful for visualizing what you are
    doing).
  save_prefix: Str. Prefix to use for filenames of saved pictures
    (only relevant if `save_to_dir` is set).
  save_format: one of "png", "jpeg", "bmp", "pdf", "ppm", "gif",
    "tif", "jpg" (only relevant if `save_to_dir` is set).
    Defaults to "png".
  follow_links: Whether to follow symlinks inside
    class subdirectories. Defaults to `False`.
  subset: Subset of data (`"training"` or `"validation"`) if
    `validation_split` is set in `ImageDataGenerator`.
  interpolation: Interpolation method used to resample the image if
    the target size is different from that of the loaded image.
    Supported methods are `"nearest"`, `"bilinear"`, and `"bicubic"`.
    If PIL version 1.1.3 or newer is installed, `"lanczos"` is also
    supported. If PIL version 3.4.0 or newer is installed, `"box"` and
    `"hamming"` are also supported. Defaults to `"nearest"`.
  keep_aspect_ratio: Boolean, whether to resize images to a target
    size without aspect ratio distortion. The image is cropped in
    the center with target aspect ratio before resizing.

Returns:
  A `DirectoryIterator` yielding tuples of `(x, y)`
    where `x` is a numpy array containing a batch
    of images with shape `(batch_size, *target_size, channels)`
    and `y` is a numpy array of corresponding labels.
r   r   r   r   r   r   r   r   r   r   r   r   rl   r   r   r   )r   r   r   )r#   rs   r   r   r   r   r   r   r   r   r   r   rl   r   r   r   s                   r$   flow_from_directory&ImageDataGenerator.flow_from_directory  s    n !
 $
 "	

 0
 
 "
 ((
 "
 
 
 $
 $
 $
 &
  !
" (#
$ **%
 	
r'   c                    SU;   a  [         R                  " S[        5        SU;   a  [         R                  " S[        5        U	S:X  a  [         R                  " S[        5        Sn	SU;   a  [         R                  " S	[        5        [        UUU 40 S
U_SU_SU_SU_SU_SU_SU	_SU R                  _SU
_SU_SU_SU_SU_SU_SU_SU_SU_SU R
                  _6$ )a  Takes the dataframe and the path to a directory + generates batches.

 The generated batches contain augmented/normalized data.

**A simple tutorial can be found **[here](
                            http://bit.ly/keras_flow_from_dataframe).

Args:
    dataframe: Pandas dataframe containing the filepaths relative to
        `directory` (or absolute paths if `directory` is None) of the
        images in a string column. It should include other column/s
        depending on the `class_mode`:
        - if `class_mode` is `"categorical"` (default value) it must
            include the `y_col` column with the class/es of each image.
            Values in column can be string/list/tuple if a single class
            or list/tuple if multiple classes.
        - if `class_mode` is `"binary"` or `"sparse"` it must include
            the given `y_col` column with class values as strings.
        - if `class_mode` is `"raw"` or `"multi_output"` it should
            contain the columns specified in `y_col`.
        - if `class_mode` is `"input"` or `None` no extra column is
            needed.
    directory: string, path to the directory to read images from. If
      `None`, data in `x_col` column should be absolute paths.
    x_col: string, column in `dataframe` that contains the filenames (or
      absolute paths if `directory` is `None`).
    y_col: string or list, column/s in `dataframe` that has the target
      data.
    weight_col: string, column in `dataframe` that contains the sample
        weights. Default: `None`.
    target_size: tuple of integers `(height, width)`, default: `(256,
      256)`. The dimensions to which all images found will be resized.
    color_mode: one of "grayscale", "rgb", "rgba". Default: "rgb".
      Whether the images will be converted to have 1 or 3 color
      channels.
    classes: optional list of classes (e.g. `['dogs', 'cats']`). Default
      is None. If not provided, the list of classes will be
      automatically inferred from the `y_col`, which will map to the
      label indices, will be alphanumeric). The dictionary containing
      the mapping from class names to class indices can be obtained via
      the attribute `class_indices`.
    class_mode: one of "binary", "categorical", "input", "multi_output",
        "raw", sparse" or None. Default: "categorical".
        Mode for yielding the targets:
        - `"binary"`: 1D numpy array of binary labels,
        - `"categorical"`: 2D numpy array of one-hot encoded labels.
          Supports multi-label output.
        - `"input"`: images identical to input images (mainly used to
          work with autoencoders),
        - `"multi_output"`: list with the values of the different
          columns,
        - `"raw"`: numpy array of values in `y_col` column(s),
        - `"sparse"`: 1D numpy array of integer labels,
        - `None`, no targets are returned (the generator will only yield
          batches of image data, which is useful to use in
          `model.predict()`).
    batch_size: size of the batches of data (default: 32).
    shuffle: whether to shuffle the data (default: True)
    seed: optional random seed for shuffling and transformations.
    save_to_dir: None or str (default: None). This allows you to
      optionally specify a directory to which to save the augmented
      pictures being generated (useful for visualizing what you are
      doing).
    save_prefix: str. Prefix to use for filenames of saved pictures
      (only relevant if `save_to_dir` is set).
    save_format: one of "png", "jpeg", "bmp", "pdf", "ppm", "gif",
      "tif", "jpg" (only relevant if `save_to_dir` is set). Default:
      "png".
    subset: Subset of data (`"training"` or `"validation"`) if
      `validation_split` is set in `ImageDataGenerator`.
    interpolation: Interpolation method used to resample the image if
      the target size is different from that of the loaded image.
      Supported methods are `"nearest"`, `"bilinear"`, and `"bicubic"`.
      If PIL version 1.1.3 or newer is installed, `"lanczos"` is also
      supported. If PIL version 3.4.0 or newer is installed, `"box"` and
      `"hamming"` are also supported. By default, `"nearest"` is used.
    validate_filenames: Boolean, whether to validate image filenames in
      `x_col`. If `True`, invalid images will be ignored. Disabling this
      option can lead to speed-up in the execution of this function.
      Defaults to `True`.
    **kwargs: legacy arguments for raising deprecation warnings.

Returns:
    A `DataFrameIterator` yielding tuples of `(x, y)`
    where `x` is a numpy array containing a batch
    of images with shape `(batch_size, *target_size, channels)`
    and `y` is a numpy array of corresponding labels.
has_extz\has_ext is deprecated, filenames in the dataframe have to match the exact filenames in disk.sortzssort is deprecated, batches will be created in thesame order than the filenames provided if shuffleis set to False.otherzB`class_mode` "other" is deprecated, please use `class_mode` "raw".r   drop_duplicateszldrop_duplicates is deprecated, you can drop duplicates by using the pandas.DataFrame.drop_duplicates method.r>  r?  r@  r   r   r   r   r   r   r   r   r   r   r   r   r   rA  r   )rq   rr   DeprecationWarningr/  r   r   )r#   r=  rs   r>  r?  r@  r   r   r   r   r   r   r   r   r   r   r   r   rA  rN   s                       r$   flow_from_dataframe&ImageDataGenerator.flow_from_dataframe  sY   \ MM8"
 VMM# #	  MM&"
 J&MMH" !
 	

 
 "
 $
 "
 
 "
 ((
 "
 
 
 $
  $!
" $#
$ %
& ('
(  2)
* **+
 	
r'   c                 r   U R                   (       a  U R                  U5      nU R                  (       a  XR                  -  nU R                  (       a  U[        R                  " USS9-  nU R
                  (       a  U[        R                  " USS9S-   -  nU R                  (       a2  U R                  b  XR                  -  nO[        R                  " S5        U R                  (       a5  U R                  b  XR                  S-   -  nO[        R                  " S5        U R                  (       a  U R                  bc  UR                  S[        R                  " UR                  SS 5      5      nX R                  -  n[        R                  " X1R                  5      nU$ [        R                  " S	5        U$ )
a  Applies the normalization configuration in-place to a batch of
inputs.

`x` is changed in-place since the function is mainly used internally
to standardize images and feed them to your network. If a copy of `x`
would be created instead it would have a significant performance cost.
If you want to apply this method without changing the input in-place
you can call the method creating a copy before:

standardize(np.copy(x))

Args:
    x: Batch of inputs to be normalized.

Returns:
    The inputs, normalized.
T)keepdimsư>NzThis ImageDataGenerator specifies `featurewise_center`, but it hasn't been fit on any training data. Fit it first by calling `.fit(numpy_data)`.zThis ImageDataGenerator specifies `featurewise_std_normalization`, but it hasn't been fit on any training data. Fit it first by calling `.fit(numpy_data)`.r|  zThis ImageDataGenerator specifies `zca_whitening`, but it hasn't been fit on any training data. Fit it first by calling `.fit(numpy_data)`.)r  r  r  r*   r  r  r  r  rq   rr   r  r  r  reshapeprodr   )r#   rd   flat_xwhite_xs       r$   r   ImageDataGenerator.standardize'  sQ   $ &&++A.A<<A!!T**A,,D)D00A""yy$YY; --xx#XX_$; ((42rwwqwwrs|'<= #<#<<JJw0  ; r'   c                    U R                   S-
  nU R                  S-
  nUb  [        R                  R	                  U5        U R
                  (       a6  [        R                  R                  U R
                  * U R
                  5      nOSnU R                  (       az   [        R                  R                  U R                  5      nU[        R                  R                  SS/5      -  n[        R                  " U R                  5      S:  a  XaU   -  nOSnU R                  (       az   [        R                  R                  U R                  5      nU[        R                  R                  SS/5      -  n[        R                  " U R                  5      S:  a  XqU   -  nOSnU R                  (       a6  [        R                  R                  U R                  * U R                  5      nOSnU R                  S   S:X  a  U R                  S   S:X  a  Su  pO=[        R                  R                  U R                  S   U R                  S   S5      u  p[        R                  R                  5       S:  U R                  -  n[        R                  R                  5       S:  U R                  -  nSnU R                   S:w  a5  [        R                  R                  U R                   * U R                   5      nSnU R"                  b:  [        R                  R                  U R"                  S   U R"                  S   5      nUUUUU	U
UUUUS.
nU$ ! [         a9    [        R                  R                  U R                  * U R                  5      n GNf = f! [         a9    [        R                  R                  U R                  * U R                  5      n GNbf = f)	a  Generates random parameters for a transformation.

Args:
    img_shape: Tuple of integers.
        Shape of the image that is transformed.
    seed: Random seed.

Returns:
    A dictionary containing randomly chosen parameters describing the
    transformation.
r4   Nr   r|  r4   r4   rK        ?)
thetatxtyshearzxzyflip_horizontalflip_verticalchannel_shift_intensity
brightness)r  r  r*   r,   r   r  uniformr  choicer6   maxr  r  r  r  r  r  r  )r#   	img_shaper   img_row_axisimg_col_axisr  r  r  r  r  r  r  r  r  r  transform_parameterss                   r$   r   'ImageDataGenerator.get_random_transforme  s>    }}q(}}q(IINN4 II%%t':':&:D<O<OPEE""YY%%d&=&=>bii&&Aw//
 vvd--.2--B!!YY%%d&<&<=bii&&Aw//
 vvd,,-1--BII%%t'7'7&79I9IJEE??1"tq'9Q'>FBYY&&"DOOA$6FB 99++-3t7K7KK))+c1T5G5GG"&##q(&(ii&7&7)))4+C+C'# 
  ,**%%a($*?*?*BJ
 .*'>$ 
 $#}  YY&&,,,d.E.E  YY&&+++T-C-Cs&   AM )AN ?NN?OOc                    U R                   S-
  nU R                  S-
  nU R                  S-
  n[        UUR	                  SS5      UR	                  SS5      UR	                  SS5      UR	                  SS5      UR	                  SS5      UR	                  SS5      UUUU R
                  U R                  U R                  S	9nUR	                  S
5      b  [        UUS
   U5      nUR	                  SS5      (       a  [        X5      nUR	                  SS5      (       a  [        X5      nUR	                  S5      b  [        XS   S5      nU$ )a  Applies a transformation to an image according to given parameters.

Args:
    x: 3D tensor, single image.
    transform_parameters: Dictionary with string - parameter pairs
        describing the transformation.
        Currently, the following parameters
        from the dictionary are used:
        - `'theta'`: Float. Rotation angle in degrees.
        - `'tx'`: Float. Shift in the x direction.
        - `'ty'`: Float. Shift in the y direction.
        - `'shear'`: Float. Shear angle in degrees.
        - `'zx'`: Float. Zoom in the x direction.
        - `'zy'`: Float. Zoom in the y direction.
        - `'flip_horizontal'`: Boolean. Horizontal flip.
        - `'flip_vertical'`: Boolean. Vertical flip.
        - `'channel_shift_intensity'`: Float. Channel shift intensity.
        - `'brightness'`: Float. Brightness shift intensity.

Returns:
    A transformed version of the input (same shape).
r4   r  r   r  r  r  r  r  )r  r  r  r  r  orderr  r  Fr  r  )r  r  r  apply_affine_transformr   r  r  r  apply_channel_shiftr  apply_brightness_shift)r#   rd   r  r  r  img_channel_axiss         r$   r   "ImageDataGenerator.apply_transform  sT   0 }}q(}}q(,,q0" $$Wa0 $$T1- $$T1- $$Wa0 $$T1- $$T1-!!)nn**
   ##$=>J#$%>? A  ##$5u==!*A##OU;;!*A##L1=&5uA r'   c                 \    U R                  UR                  U5      nU R                  X5      $ )zApplies a random transformation to an image.

Args:
    x: 3D tensor, single image.
    seed: Random seed.

Returns:
    A randomly transformed version of the input (same shape).
)r   r   r   )r#   rd   r   r   s       r$   random_transform#ImageDataGenerator.random_transform   s+     **177D9##A..r'   c                    [         R                  " XR                  S9nUR                  S:w  a!  [	        S[        UR                  5      -   5      eUR                  U R                     S;  a  [        R                  " SU R                  -   S-   [        U R                  5      -   S-   [        U R                  5      -   S-   [        UR                  5      -   S	-   [        UR                  U R                     5      -   S
-   5        Ub  [         R                  R                  U5        [         R                  " U5      nU R                  (       a  XR                  -  nU(       a  [         R                  " [!        X1R                  S   -  /[#        UR                  5      SS -   5      U R                  S9n[%        U5       HI  n[%        UR                  S   5       H*  nU R'                  X   5      XWXaR                  S   -  -   '   M,     MK     UnU R(                  (       a  [         R*                  " USU R,                  U R.                  4S9U l        / SQnUR                  U R                     XR                  S-
  '   [         R0                  " U R*                  U5      U l        XR*                  -  nU R2                  (       a  [         R4                  " USU R,                  U R.                  4S9U l        / SQnUR                  U R                     XR                  S-
  '   [         R0                  " U R4                  U5      U l        XR4                  S-   -  nU R6                  (       a  [9        U5      n	[         R0                  " XS45      n
[         R:                  R=                  U
R>                  SS9u  pn[         R@                  " U	5      XRB                  -   -  nX-  RE                  UR>                  5      U l#        gg)a  Fits the data generator to some sample data.

This computes the internal data stats related to the
data-dependent transformations, based on an array of sample data.

Only required if `featurewise_center` or
`featurewise_std_normalization` or `zca_whitening` are set to True.

When `rescale` is set to a value, rescaling is applied to
sample data before computing the internal data stats.

Args:
    x: Sample data. Should have rank 4.
     In case of grayscale data,
     the channels axis should have value 1, in case
     of RGB data, it should have value 3, and in case
     of RGBA data, it should have value 4.
    augment: Boolean (default: False).
        Whether to fit on randomly augmented samples.
    rounds: Int (default: 1).
        If using data augmentation (`augment=True`),
        this is how many augmentation passes over the data to use.
    seed: Int (default: None). Random seed.
r   r   z<Input to `.fit()` should have rank 4. Got array with shape: r  zSExpected input to be images (as Numpy array) following the data format convention "r  z3), i.e. expected either 1, 3 or 4 channels on axis r  r  r  Nr   r4   r~  )r4   r4   r4   r  r|  F)full_matrices)$r*   r  r   r  r6   r  r   r  rq   rr   r   r,   r   r   r  r   r   r|   r   r  r  r  r  r  r  r  r  r  r5   r   svdTsqrtr  dotr  )r#   rd   augmentroundsr   axrr   broadcast_shaper   r  usru   s_invs                  r$   fitImageDataGenerator.fit  s7   2 JJq

+66Q;Nagg,  774$$%Y6MM9""# )) d''(	)
 HH d''() BB agg, 	 aggd//01
2    IINN4 GGAJ<<Av
*+d177mAB.??@jjB 6]qwwqz*A-1-B-B14-HB1wwqz>)* + # A""DMM4==(IJDI'O56WWT=N=N5OO--12

499o>DINA--vvaq$--&GHDH'O56WWT=N=N5OO--12zz$((O<DHD AAAZZr7+FiimmFHHEmBGA!GGAJ!&6&6"67E)*(<D% r'   )r   r  r  r  r  r  r   r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  )FFFFFr  r           r  Nr  r  r  r  r  FFNNNr  r4   N)
Nr  TNNNr  r   FN)r
  r   Nr   r  TNNr  r   FNr  F)Nr,  rx  Nr
  r   Nr   r  TNNr  r   Nr  Tr)   )Fr4   N)rX   rY   rZ   r[   r\   r%   r  r  r  r   r   r   r  r  r^   rH   r'   r$   r  r    s   tp !&+%*#1F1V  J
^  !j
^  '_
B<|Y$v>@/T=r'   r  z)keras.preprocessing.image.random_rotationc                 h    [         R                  R                  U* U5      n[        U UUUUUUUS9n U $ )a  Performs a random rotation of a Numpy image tensor.

Deprecated: `tf.keras.preprocessing.image.random_rotation` does not operate
on tensors and is not recommended for new code. Prefer
`tf.keras.layers.RandomRotation` which provides equivalent functionality as
a preprocessing layer. For more information, see the tutorial for
[augmenting images](
https://www.tensorflow.org/tutorials/images/data_augmentation), as well as
the [preprocessing layer guide](
https://www.tensorflow.org/guide/tf_keras/preprocessing_layers).

Args:
    x: Input tensor. Must be 3D.
    rg: Rotation range, in degrees.
    row_axis: Index of axis for rows in the input tensor.
    col_axis: Index of axis for columns in the input tensor.
    channel_axis: Index of axis for channels in the input tensor.
    fill_mode: Points outside the boundaries of the input
        are filled according to the given mode
        (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
    cval: Value used for points outside the boundaries
        of the input if `mode='constant'`.
    interpolation_order: int, order of spline interpolation.
        see `ndimage.interpolation.affine_transform`

Returns:
    Rotated Numpy image tensor.
)r  r  r  r  r  r  r  r*   r,   r  r  )	rd   rgr  r  r  r  r  r  r  s	            r$   random_rotationr  d  sF    N IIrc2&E	!!		A Hr'   z&keras.preprocessing.image.random_shiftc	                     U R                   U   U R                   U   p[        R                  R                  U* U5      U	-  n[        R                  R                  U* U5      U
-  n[	        U UUUUUUUUS9	n U $ )a  Performs a random spatial shift of a Numpy image tensor.

Deprecated: `tf.keras.preprocessing.image.random_shift` does not operate on
tensors and is not recommended for new code. Prefer
`tf.keras.layers.RandomTranslation` which provides equivalent functionality
as a preprocessing layer. For more information, see the tutorial for
[augmenting images](
https://www.tensorflow.org/tutorials/images/data_augmentation), as well as
the [preprocessing layer guide](
https://www.tensorflow.org/guide/tf_keras/preprocessing_layers).

Args:
    x: Input tensor. Must be 3D.
    wrg: Width shift range, as a float fraction of the width.
    hrg: Height shift range, as a float fraction of the height.
    row_axis: Index of axis for rows in the input tensor.
    col_axis: Index of axis for columns in the input tensor.
    channel_axis: Index of axis for channels in the input tensor.
    fill_mode: Points outside the boundaries of the input
        are filled according to the given mode
        (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
    cval: Value used for points outside the boundaries
        of the input if `mode='constant'`.
    interpolation_order: int, order of spline interpolation.
        see `ndimage.interpolation.affine_transform`

Returns:
    Shifted Numpy image tensor.
)r  r  r  r  r  r  r  r  )r   r*   r,   r  r  )rd   wrghrgr  r  r  r  r  r  hwr  r  s                r$   random_shiftr    s    R 778aggh/q			C4	%	)B			C4	%	)B	!!
	A Hr'   z&keras.preprocessing.image.random_shearc                 h    [         R                  R                  U* U5      n[        U UUUUUUUS9n U $ )a  Performs a random spatial shear of a Numpy image tensor.

Args:
    x: Input tensor. Must be 3D.
    intensity: Transformation intensity in degrees.
    row_axis: Index of axis for rows in the input tensor.
    col_axis: Index of axis for columns in the input tensor.
    channel_axis: Index of axis for channels in the input tensor.
    fill_mode: Points outside the boundaries of the input
        are filled according to the given mode
        (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
    cval: Value used for points outside the boundaries
        of the input if `mode='constant'`.
    interpolation_order: int, order of spline interpolation.
        see `ndimage.interpolation.affine_transform`

Returns:
    Sheared Numpy image tensor.
)r  r  r  r  r  r  r  r  )	rd   	intensityr  r  r  r  r  r  r  s	            r$   random_shearr    sE    < IIyj)4E	!!		A Hr'   z%keras.preprocessing.image.random_zoomc                     [        U5      S:w  a  [        SU< 35      eUS   S:X  a  US   S:X  a  Su  pO)[        R                  R	                  US   US   S5      u  p[        U UU	UUUUUUS9	n U $ )a  Performs a random spatial zoom of a Numpy image tensor.

Deprecated: `tf.keras.preprocessing.image.random_zoom` does not operate on
tensors and is not recommended for new code. Prefer
`tf.keras.layers.RandomZoom` which provides equivalent functionality as
a preprocessing layer. For more information, see the tutorial for
[augmenting images](
https://www.tensorflow.org/tutorials/images/data_augmentation), as well as
the [preprocessing layer guide](
https://www.tensorflow.org/guide/tf_keras/preprocessing_layers).

Args:
    x: Input tensor. Must be 3D.
    zoom_range: Tuple of floats; zoom range for width and height.
    row_axis: Index of axis for rows in the input tensor.
    col_axis: Index of axis for columns in the input tensor.
    channel_axis: Index of axis for channels in the input tensor.
    fill_mode: Points outside the boundaries of the input
        are filled according to the given mode
        (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
    cval: Value used for points outside the boundaries
        of the input if `mode='constant'`.
    interpolation_order: int, order of spline interpolation.
        see `ndimage.interpolation.affine_transform`

Returns:
    Zoomed Numpy image tensor.

Raises:
    ValueError: if `zoom_range` isn't a tuple.
rK  z@`zoom_range` should be a tuple or list of two floats. Received: r   r4   r  )r  r  r  r  r  r  r  r  )r5   r6   r*   r,   r  r  )
rd   r  r  r  r  r  r  r  r  r  s
             r$   random_zoomr    s    T :!
 	

 !}jmq0B"":a=*Q-C	!!
	A Hr'   z-keras.preprocessing.image.apply_channel_shiftc                 F   [         R                  " XS5      n [         R                  " U 5      [         R                  " U 5      pCU  Vs/ s H  n[         R                  " XQ-   X45      PM     nn[         R
                  " USS9n [         R                  " U SUS-   5      n U $ s  snf )zPerforms a channel shift.

Args:
    x: Input tensor. Must be 3D.
    intensity: Transformation intensity.
    channel_axis: Index of axis for channels in the input tensor.

Returns:
    Numpy image tensor.
r   r  r4   )r*   rollaxisminr  clipstack)rd   r  r  min_xmax_x	x_channelchannel_imagess          r$   r  r  A	  s     	AQ'A66!9bffQi5FGFG	%u4a   	a(A
Aq,*+AHs   #Bz.keras.preprocessing.image.random_channel_shiftc                 X    [         R                  R                  U* U5      n[        XUS9$ )zPerforms a random channel shift.

Args:
    x: Input tensor. Must be 3D.
    intensity_range: Transformation intensity.
    channel_axis: Index of axis for channels in the input tensor.

Returns:
    Numpy image tensor.
)r  )r*   r,   r  r  )rd   intensity_ranger  r  s       r$   random_channel_shiftr  W	  s*     		!!?"2ODIq,GGr'   z0keras.preprocessing.image.apply_brightness_shiftc                    [         c  [        S5      e[        R                  " U 5      [        R                  " U 5      pCUS:  =(       d    US:  n[
        R                  " X=(       d    US9n [         R                  " U 5      =pUR                  U5      n [
        R                  " U 5      n U(       d  U(       a  U S-  XC-
  -  U-   n U $ )aK  Performs a brightness shift.

Args:
    x: Input tensor. Must be 3D.
    brightness: Float. The new brightness value.
    scale: Whether to rescale the image such that minimum and maximum values
        are 0 and 255 respectively. Default: True.

Returns:
    Numpy image tensor.

Raises:
    ImportError: if PIL is not available.
z<Using brightness shifts requires PIL. Install PIL or Pillow.r      r   )
r
   ImportErrorr*   r  r  r   r   
Brightnessenhancer   )rd   r  r   x_minx_maxlocal_scaleimgenhancer_Brightnesss          r$   r  r  g	  s      J
 	
 66!9bffQi519.%#+K  *>?A!-!8!8!;;A&&z2A  #A[Gu}%-Hr'   z+keras.preprocessing.image.random_brightnessc                     [        U5      S:w  a  [        SU< 35      e[        R                  R	                  US   US   5      n[        XU5      $ )a<  Performs a random brightness shift.

Deprecated: `tf.keras.preprocessing.image.random_brightness` does not
operate on tensors and is not recommended for new code. Prefer
`tf.keras.layers.RandomBrightness` which provides equivalent functionality
as a preprocessing layer. For more information, see the tutorial for
[augmenting images](
https://www.tensorflow.org/tutorials/images/data_augmentation), as well as
the [preprocessing layer guide](
https://www.tensorflow.org/guide/tf_keras/preprocessing_layers).

Args:
    x: Input tensor. Must be 3D.
    brightness_range: Tuple of floats; brightness range.
    scale: Whether to rescale the image such that minimum and maximum values
        are 0 and 255 respectively. Default: True.

Returns:
    Numpy image tensor.

Raises:
    ValueError if `brightness_range` isn't a tuple.
rK  r  r   r4   )r5   r6   r*   r,   r  r  )rd   r  r   r  s       r$   random_brightnessr  	  sX    2 !.1
 	

 			*1-/?/BCA!!..r'   c                 (   [        U5      S-  S-
  n[        U5      S-  S-
  n[        R                  " SSU/SSU// SQ/5      n[        R                  " SSU* /SSU* // SQ/5      n[        R                  " [        R                  " XP5      U5      nU$ )NrK  r  r4   r   r   r   r4   )r  r*   r;  r  )matrixrd   r   o_xo_yoffset_matrixreset_matrixtransform_matrixs           r$   transform_matrix_offset_centerr  	  s    
(Q,
C
(Q,
CHHq!SkAq#;	BCM88aSD\Aq3$<CDLvvbff];\Jr'   z0keras.preprocessing.image.apply_affine_transformc                 ^   [         c  [        S5      e[        R                  " XxU	/5      R                  S:w  a  [        S5      e[        / SQ5      n[        XxU	/5      nX:w  a  [        SX-
   35      eU R                  S:w  a  [        S5      eU	S;  a  [        S	5      eSnUS
:w  a  [        R                  " U5      n[        R                  " [        R                  " U5      [        R                  " U5      * S
/[        R                  " U5      [        R                  " U5      S
// SQ/5      nUnUS
:w  d  US
:w  a>  [        R                  " SS
U/S
SU// SQ/5      nUc  UnO[        R                  " UU5      nUS
:w  a}  [        R                  " U5      n[        R                  " S[        R                  " U5      * S
/S
[        R                  " U5      S
// SQ/5      nUc  UnO[        R                  " UU5      nUS:w  d  US:w  a>  [        R                  " US
S
/S
US
// SQ/5      nUc  UnO[        R                  " UU5      nUb  U R                  U   U R                  U   nn[        UUU5      n[        R                  " X	S
5      n X:  a   USS2SS
/4   USS2S
S/4'   USS
/   US
S/'   USS2SS24   nUSS2S4   nU  Vs/ s H%  n[         R"                  R%                  UUUUU
US9PM'     nn[        R&                  " US
S9n [        R                  " U S
U	S-   5      n U $ s  snf )a  Applies an affine transformation specified by the parameters given.

Args:
    x: 3D numpy array - a 2D image with one or more channels.
    theta: Rotation angle in degrees.
    tx: Width shift.
    ty: Heigh shift.
    shear: Shear angle in degrees.
    zx: Zoom in x direction.
    zy: Zoom in y direction
    row_axis: Index of axis for rows (aka Y axis) in the input
        image. Direction: left to right.
    col_axis: Index of axis for columns (aka X axis) in the input
        image. Direction: top to bottom.
    channel_axis: Index of axis for channels in the input image.
    fill_mode: Points outside the boundaries of the input
        are filled according to the given mode
        (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
    cval: Value used for points outside the boundaries
        of the input if `mode='constant'`.
    order: int, order of interpolation

Returns:
    The transformed version of the input.

Raises:
    ImportError: if SciPy is not available.
Nz3Image transformations require SciPy. Install SciPy.r   z;'row_axis', 'col_axis', and 'channel_axis' must be distinct)r   r4   rK  zInvalid axis' indices: z-Input arrays must be multi-channel 2D images.)r   rK  z7Channels are allowed and the first and last dimensions.r   r  r4   rK  )r  moder  r  )scipyr	  r*   r  sizer6   rQ  r  deg2radr;  cossinr  r   r  r  r	   r   affine_transformr  )rd   r  r  r  r  r  r  r  r  r  r  r  r  valid_indicesactual_indicesr  rotation_matrixshift_matrixshear_matrixzoom_matrixr  r  final_affine_matrixfinal_offsetr  r  s                             r$   r  r  	  sU   X }OPP
 
yy(l3499Q>I
 	

 	NM(l;<N&%n&D%EF
 	
 	vv{HII6!E
 	
 z

5!((2uq1
 +	Qw"'xx!QaBZ CD#+!vv&6Ez

5!xx"&&-#a%:IF
 #+!vv&6E	Qw"'hhQ
QAJ	BC#*!vv&6D#wwx !''("319a
 KK+ *:1q!f9*EQAY''7A'?aV$.rr2A2v6'A. 

 	 !!22# 3   	 

 HH^!,KK1lQ./H

s   
,L*)r4   rK  r   r  r  r4   )r   )T)r   r   r   r   r4   r4   r4   rK  r   r  r  r4   )+r\   ra  r   ri   r   rq   numpyr*   tf_keras.srcr   tf_keras.src.utilsr   r   r    tensorflow.python.util.tf_exportr   r  r   r	   r	  PILr
   Sequencer   rx   r   r   r   r  r-  r/  r  r  r  r  r  r  r  r  r  r  r  r  rH   r'   r$   <module>r1     s  "   	      ) * ' :	 
 23w"z"" w" 4w"t":/dz
 z
z ;<l+X l =l^ <=H H >HVy#+X y#x	 <=R= R= >R=j 9: 	1 ;1h 67
 	6 86r 67 	( 8(V 56 	> 7>B => ?* >?H @H @A B< ;</ =/D @A 
	
L BLCL  		  Ls#   F F FFF&%F&