
    ij)                       d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddl!m"Z" ddl#m$Z$ ddl#m%Z% ddl&m'Z( 	 ddl)Z)	 ddl+Z+dZ,dZ-dZ.e. dZ/e. dZ0dZ1dZ2dZ3dZ4dZ5dFdZ6d Z7d Z8d  Z9d! Z:dGd"Z;d# Z<d$ Z=dZ>dZ?d% Z@d& ZAd' ZB	 dHd(ZC	 dId)ZDdJd*ZEd+ ZFd, ZGd- ZHd. ZI	 	 	 	 dKd/ZJd0 ZKd1 ZL	 dLd2ZM	 dLd3ZN G d4 d5      ZOd6 ZPdZQd7ZRd8 ZS G d9 d:      ZT G d; d<eT      ZU G d= d>      ZVd? ZWd@ ZXdA ZYdB ZZdC Z[dD Z\dE Z]y# e*$ r dZ)Y w xY w# e*$ r dZ+Y w xY w)Mz3Python-based idempotent model-saving functionality.    N)format)backend)global_state)ObjectSharingScope)deserialize_keras_object)serialize_keras_object)dtype_utils)
file_utils)io_utils)naming)
plot_model)check_pydot)h5py)readable_memory_size)weight_memory_size)__version__config.jsonzmetadata.jsonzmodel.weightsz.h5z.npzassetsg      ?l        d   a  
---
library_name: keras
---

This model has been uploaded using the Keras library and can be used with JAX,
TensorFlow, and PyTorch backends.

This model card has been generated automatically and should be completed by the
model author.
See [Model Cards documentation](https://huggingface.co/docs/hub/model-cards) for
more information.

For more details about the model architecture, check out
[config.json](./config.json).c                 J   |dk(  rt         t        d      | j                  st        j                  dd       t        |t        j                        rt        | ||       yt        |      }|j                  d      }|r|j                  d      st        d	|       |s|j                  d      rt        d
|       |r|rt        d| d|       |rt        | ||       y|st        | ||       yt        j                   |      r`t        j"                         }t        | ||       t        j$                  |d      5 }|j'                  |j)                                ddd       yt+        |d      5 }t        | ||       ddd       y# 1 sw Y   yxY w# 1 sw Y   yxY w)a  Save a zip-archive representing a Keras model to the given file or path.

    The zip-based archive contains the following structure:

    - JSON-based configuration file (config.json): Records of model, layer, and
        other saveables' configuration.
    - H5-based saveable state files, found in respective directories, such as
        model/states.npz, model/dense_layer/states.npz, etc.
    - Metadata file.

    The states of Keras saveables (layers, optimizers, loss, and metrics) are
    automatically saved as long as they can be discovered through the attributes
    returned by `dir(Model)`. Typically, the state includes the variables
    associated with the saveable, but some specially purposed layers may
    contain more such as the vocabularies stored in the hashmaps. The saveables
    define how their states are saved by exposing `save_state()` and
    `load_state()` APIs.

    For the case of layer states, the variables will be visited as long as
    they are either 1) referenced via layer attributes, or 2) referenced via a
    container (list, tuple, or dict), and the container is referenced via a
    layer attribute.
    h5Nz0h5py must be installed in order to save a model.zYou are saving a model that has not yet been built. It might not contain any weights yet. Consider building the model first by calling it on some data.   
stacklevelhf://.keraszOInvalid `filepath` argument: expected a `.keras` extension. Received: filepath=zbWhen using `zipped=False`, the `filepath` argument should not end in `.keras`. Received: filepath=zaWhen saving to the Hugging Face Hub, you should not save the model as zipped. Received: filepath=z	, zipped=wb)r   ImportErrorbuiltwarningswarn
isinstanceioIOBase_save_model_to_fileobjstr
startswithendswith
ValueError_upload_model_to_hf_save_model_to_dirr
   is_remote_pathBytesIOFilewritegetvalueopen)modelfilepathweights_formatzippedis_hfzip_filepathfs          p/var/www/html/emotional.easysim.app/public_html/venv/lib/python3.12/site-packages/keras/src/saving/saving_lib.py
save_modelr:   K   s   0 $,LMM;; 	
 (BII&uh?8}H(Eh''1""*-
 	
 h''133;*>
 	
 %33;*IfXO
 	
 E8^<5(N;$$X.::<L"5,G40 1A--/01 1 h% A&ua@A A1 1A As    F6FFF"c                    t               5  t        |       }d d d        t        j                        }t        j                  t        t
        j
                  j                         j                  d      d      }||fS # 1 sw Y   ixY w)Nz%Y-%m-%d@%H:%M:%S)keras_version
date_saved)r   r   jsondumpsr<   datetimenowstrftime)r2   serialized_model_dictconfig_jsonmetadata_jsons       r9   _serialize_model_as_jsonrF      sx    		 > 6u =>**23KJJ*"++//1::;NO	
M %%> >s   A??Bc                 B   t        j                  |      st        j                  |       t        |       \  }}t	        t        j
                  |t              d      5 }|j                  |       d d d        t	        t        j
                  |t              d      5 }|j                  |       d d d        t        j
                  |t              }t        j
                  |t              }	 |dk(  rt        |d      }n!|dk(  rt        |d      }nt        d|       t        |d      }	t        | ||	dt!                      |j#                          |	j#                          y # 1 sw Y   xY w# 1 sw Y   xY w# j#                          	j#                          w xY w)Nwr   modenpzTUnknown `weights_format` argument. Expected 'h5' or 'npz'. Received: weights_format= weights_storeassets_store
inner_pathvisited_saveables)r
   existsmakedirsrF   r1   join_METADATA_FILENAMEr/   _CONFIG_FILENAME_VARS_FNAME_H5_ASSETS_DIRNAME	H5IOStore
NpzIOStorer)   DiskIOStore_save_statesetclose)
r2   dirpathr4   rD   rE   r8   weights_filepathassert_dirpathrO   asset_stores
             r9   r+   r+      sh   W%G$!9%!@K	joog'9:C	@ A		joog'78#	> !	!w?__Wo>NT!%&6SAMu$&'7cBM,,:+;= 
 ".s;'$!e	
 	7  0 	s%   E$E0*AE< $E-0E9<"Fc           	         t        |       \  }}t        j                  |d      5 }|j                  t        d      5 }|j                  |j                                d d d        |j                  t        d      5 }|j                  |j                                d d d        d }d }d }	d}
	 |dk(  rx	 t        |       rt        t        |d      }nXt        j                  |j                        j                  }t        j                   |      }t        |j                  d      }d}
n&|dk(  rt#        t$        |d      }nt'        d	|       t)        t*        |d      }	t-        | ||	d
t/                      	 |r|j3                          |	r|	j3                          |
r"|r |j                  |j                  t               |r|j3                          	 d d d        y # 1 sw Y   xY w# 1 sw Y   RxY w#  t        t        |d      }Y xY w#  d}
|rd |_         xY w# |r|j3                          |	r|	j3                          |
r"|r |j                  |j                  t               |r|j3                          w w xY w# 1 sw Y   y xY w)NrH   Fr   archiverJ   dirrI   TrK   rL   rM   rN   )rF   zipfileZipFiler1   rV   r/   encoderW   is_memory_sufficientrZ   rX   pathlibPathnameparenttempfileNamedTemporaryFiler[   _VARS_FNAME_NPZr)   r\   rY   r]   r^   rf   r_   )r2   fileobjr4   rD   rE   zfr8   weights_file_pathrO   rc   write_zfworking_dirs               r9   r%   r%      sw   !9%!@K	#	& G*"WW'- 	,GGM((*+	,WW%s+ 	*qGGK&&()	* !=	*%+E2 )2*BS) '.ll7<<&@&G&G,4,G,G +-) )2-22) $(  5( *#Rc! !00>/?A  &orLK+("%% ##%!!#-*//@ !'')OG* G*	, 	,	* 	*8 %.&%M.	H(,%##%!!#-*//@ !'') !MG* G*sz   J GJ: G*J+H1A6G7'AH9AJG'	"J*G4	/J7HHHH!!AI>>JJ
c                    t         t        d      |}|j                  d      r|dd  }|j                  d      dkD  rt	        d|       t        j
                  dt              }|j                  |d	
      }|j                  }t        j                         5 }t        | ||       t        }t               rJt        j                  |dd      }	t!        | |	d	d	d	       t#        | j$                        dk  r|dz  }n|dz  }t'        t        j                  |d      d      5 }
|
j)                  |       d d d        |j+                  ||d       t-        j.                  d| d| d       d d d        y # 1 sw Y   BxY w# 1 sw Y   y xY w)NzWTo save models to the Hugging Face Hub, you must install the `huggingface_hub` package.r      /   zVInvalid `hf_path` argument: expected `namespace/model_name` format. Received: hf_path=keras)library_namelibrary_versionTexist_okr   zsummary_plot.png)to_fileshow_layer_namesshow_shapes
show_dtype
   z 

![](./assets/summary_plot.png)zCA plot of the model can be found [here](./assets/summary_plot.png).z	README.mdrH   zSave model using Keras.)repo_idfolder_pathcommit_messagez%Model saved to the Hugging Face Hub: z<
To load back the model, use `keras.saving.load_model('hf://z')`)huggingface_hubr   r'   countr)   HfApir<   create_repor   rq   TemporaryDirectoryr+   _MODEL_CARD_TEMPLATEr   r
   rU   r   lenlayersr1   r/   upload_folderr   	print_msg)r2   hf_pathr4   original_hf_pathapirepo_urlr   tmp_dir
model_card	plot_pathr8   s              r9   r*   r*     s   >
 	

 '"!"+}}SA**:);=
 	

 

mC w6HG		$	$	& "
'5'>:)
=";MNI!!%  5<< B&BB
9

 *//';7= 	 GGJ	  	4 	 	

 	3H: >..5Yc;	
="
 "
,	  	 -"
 "
s%   BF"E548F5E>	:FF
c                 Z   t        | t        j                        rt        | |||      S t	        |       j                  d      r@t        t        d      | dd }t        j                  |dt              }t        ||||      S t	        |       } | j                  d      s^t        j                  |       xr) t        j                  t        j                  | d            }|rt        | |||      S t!        d	|        t#        | d
      5 }t        ||||      cddd       S # 1 sw Y   yxY w)z.Load a zip archive representing a Keras model.r   NzYTo load models from the Hugging Face Hub, you must install the `huggingface_hub` package.rz   r}   )r   r~   r   r   r   zDInvalid filename: expected a `.keras` extension. Received: filepath=rb)r"   r#   r$   _load_model_from_fileobjr&   r'   r   r   snapshot_downloadr<   _load_model_from_dirr(   r
   isdirrS   rU   r)   r1   )r3   custom_objectscompile	safe_moder   r   is_keras_dirr8   s           r9   
load_modelr   K  sG   (BII&'ngy
 	
 
X	!	!'	*"B 
 12,%77 )

 $)
 	
 x=  *%++H5 *:K:K-8;L +ngy  &&.Z1  (D! 	Q+>7I	 	 	s   	D!!D*c           	         t        j                  |       st        d|        t        j                  |       st        d|        t	        t        j
                  | t              d      5 }|j                         }d d d        t        |||      }t        j                  |       }	 t        |v r(t        j
                  | t              }t        |d      }	nJt        |v r(t        j
                  | t              }t        |d      }	nt        dt         dt         d      t        |      dkD  r&t        t        j
                  | t               d      }
nd }
t#               }i }t%        ||	|
d	t#               ||
       |	j'                          |
r|
j'                          	 |rt)        |       |S # 1 sw Y   6xY w# 	j'                          
r|
j'                          w w xY w)NzDirectory doesn't exist: zPath isn't a directory: rrI   Expected a  or  file.   rM   rO   rP   rQ   rR   failed_saveables
error_msgs)r
   rS   r)   r   r1   rU   rW   read_model_from_configlistdirrX   rZ   rs   r[   r   r\   rY   r^   _load_stater_   _raise_loading_failure)r`   r   r   r   r8   rD   r2   all_filenamesrv   rO   rc   r   r   s                r9   r   r   u  s   W%4WI>??G$3G9=>>	joog'78#	> !ffh{NGYOE&&w/M" ]* * H%&7cBM- * I&'8sCMn-T/1B&I  }!%9K
 K5
'$!e-!	
 	z*LW J 	 s   +F0(CF= 0F:=%G"c                     t        j                  |       }|sd |d<   t               5  t        |||      }d d d        |S # 1 sw Y   S xY w)Ncompile_config)r   )r>   loadsr   r   )rD   r   r   r   config_dictr2   s         r9   r   r     sU     **[)K(,$%		 
(9

 L	
 Ls   A  A
c           
         | j                  |      }|j                  t        kD  r\|j                  t        |j                  z  kD  r;t        d| dt        |j                         dt        |j                         d      yy)z<Raise if a ZIP member is a decompression bomb (see CWE-409).zNot allowed: ZIP member '' declares 
 but only zE are stored on disk; refusing to load a potential decompression bomb.N)getinfo	file_size_ZIP_MEMBER_BOMB_FLOOR_BYTES_ZIP_MEMBER_MAX_EXPANSIONcompress_sizer)   r   )rf   ro   infos      r9   _reject_zip_bombr     s    ??4 D55NN69K9KKK'v[#DNN34J#D$6$678 9??
 	
 L 	6    c                     t        | |       | j                  |d      5 }|j                         cddd       S # 1 sw Y   yxY w)z=Read a ZIP member into memory, rejecting bombs (see CWE-409).r   N)r   r1   r   )rf   ro   r8   s      r9   _safe_zip_readr     s:    Wd#	dC	  Avvx  s	   9Ac           
         t        j                  | d      5 }t        |t              }t	        ||||      }|j                         }d }d }	d }
	 t        |v rt        |t               	 t        |      rEt        j                  |j                  t        d      j                               }t        |d      }	nt        j                  t!        j"                  | j$                        j&                        }|j)                  t        |j$                         t        t!        j"                  |j$                  t              d      }	n5t*        |v rt-        t*        |d      }	nt/        dt         dt*         d      t1        |      dkD  rt3        t4        |d      }
t7               }i }t9        ||	|
d	t7               ||
       |	r|	j;                          |
r|
j;                          |r|j=                          	 |rt?        |       d d d        |S #  t        t        |d      }	Y xY w# |	r|	j;                          |
r|
j;                          |r|j=                          w w xY w# 1 sw Y   S xY w)Nr   rI   rg   r   r   r   r   re   rM   r   ) ri   rj   r   rW   r   namelistrX   r   rl   r#   r-   r1   r   rZ   rq   r   rm   rn   ro   rp   extractrs   r[   r)   r   r\   rY   r^   r   r_   cleanupr   )rt   r   r   r   ru   rD   r2   r   extract_dirrO   rc   io_filer   r   s                 r9   r   r     s9   	#	& J/"$R)9:")
 <	&. !^4L+E2 #%**GGNC8==?# )2'(D
 '/&A&A 'W\\ : A A' 

>;3C3CD(1#LL)9)9>J!$) !M1 *?BS I !.!1o5FfM  =!A%)/2CP"uJ+("%%!1% ##%!!###%":.UJ/V LIL %.nbs$KM. ##%!!###% MJ/V Ls>   5I!H%&CHA<H%>AI!H" H%%9II!!I+c                    | j                   st        d      t        |      }d}d}||j                  d      st        d|       ||j                  d      st        d|       	 t	        j
                  |      rKt               }t        j                  j                  |t        j                  j                  |            }|}|}|t        ||d      }nt        |d      }|t        d	 |D              }	n
t               }	t        | |dd
|	       |j                          |.t	        j                   ||       t#        j$                  |d       yy# |.t	        j                   ||       t#        j$                  |d       w w xY w)zjSave only the weights of a model to a target filepath.

    Supports both `.weights.h5` and `.keras`.
    zYou are saving a model that has not yet been built. Try building the model first by calling it on some data or by using `build()`.N.weights.h5z;The filename must end in `.weights.h5`. Received: filepath=)
weights.h5weights.jsonz`The filename must end in `.weights.json` when `max_shard_size` is specified. Received: filepath=rH   rI   c              3   2   K   | ]  }t        |        y wNid.0os     r9   	<genexpr>z$save_weights_only.<locals>.<genexpr>R       #CaBqE#C   rM   rN   Tignore_errors)r   r)   r&   r(   r
   r,   get_temp_dirospathrU   basenameShardedH5IOStorerZ   r^   r]   r_   copyshutilrmtree)
r2   r3   max_shard_sizeobjects_to_skipfilepath_strr   remote_filepathlocal_filepathrO   rR   s
             r9   save_weights_onlyr   )  s    ;;"
 	
 x=LGOl&;&;M&J"".1
 	
 
	#L,A,A&- --9N<
 	
7$$X."nGWW\\'2773C3CH3MNN&O%H%,X~CPM%hS9M& ##C?#C C #'/	
 	OOHo6MM'6 7OOHo6MM'6 s   *B=E 2F
c           
      |   | j                   st        d      d}d}t        |      }	 t        j                  |      rat               }t        j                  j                  |t        j                  j                  |            }t        j                  ||       |x}}|j                  d      rt        |d      }nX|j                  d      rt        |d      }n9|j                  d      r(t        j                  |d      }t        t         |d      }t#               }	|t#        d	 |D              }
n
t#               }
i }t%        | dd
||
|	|       |j'                          |r|j'                          |	rt)        ||       |t+        j,                  |d       yy# |t+        j,                  |d       w w xY w)znLoad the weights of a model from a filepath (.keras or .weights.h5).

    Note: only supports h5 for now.
    zYou are loading weights into a model that has not yet been built. Try building the model first by calling it on some data or by using `build()`.Nr   r   rI   r   r   re   c              3   2   K   | ]  }t        |        y wr   r   r   s     r9   r   z$load_weights_only.<locals>.<genexpr>  r   r   rM   )rO   rP   rQ   skip_mismatchrR   r   r   )	warn_onlyTr   )r   r)   r&   r
   r,   r   r   r   rU   r   r   r(   rZ   r   ri   rj   rX   r^   r   r_   r   r   r   )r2   r3   r   r   rf   r   r   r   rO   r   rR   r   s               r9   load_weights_onlyr   c  s    ;;"
 	
 GGx=L)7$$\2"nGWW\\)),7N OOL.9&44L8  .%hS9M"">2,XC@M""8,ooh4G%ngCPM5& ##C?#C C #
''/-!		
 	MMO":GMM'6 7MM'6 s   EF F;c                    t        | j                               d   }| |   \  }}dt        |        d| d| d| j                         D cg c]  }|d   	 c} }|rt	        j
                  |       y t        |      c c}w )Nr   zA total of z? objects could not be loaded. Example error message for object z:

z,

List of objects that could not be loaded:
)listkeysr   valuesr    r!   r)   )r   r   	first_keyex_saveableex_errorxmsgs          r9   r   r     s    Z__&'*I&y1K
c*o& 'e* 6$++-.QAaD.
/	1  co /s   
A>c                 :   t        j                  |      s| j                  ||       y t        j                  |      D ][  }t        j                  ||      j                  dd      }t        j                  ||      j                  dd      }t        | ||       ] y )N\r{   )r
   r   r/   r   rU   replace_write_to_zip_recursively)zipfile_to_savesystem_pathzip_path	file_namesystem_file_pathzip_file_paths         r9   r   r     s    K(k84#++K8 		I){IFNNc  'OOHi@HHcM &!1=		r   c                 2    | j                  d      rd|  S | S )z3Make sure that private attributes are visited last._~r'   )ro   s    r9   	_name_keyr    s    s4&zKr   c              #   j  K   ddl m} t        | |      st        d|  dt	        |              | j                         }t        |      }|dv rd| j                  f t        t        |       d       D ]+  }|j                  d	      s||v r	 t        | |      }||f - y # t        $ r Y :w xY ww)
Nr   KerasSaveablez>Expected object to be an instance of `KerasSaveable`, but got 	 of type )
Sequential
Functionalr   c                     t        |       S r   )r  r   s    r9   <lambda>z _walk_saveable.<locals>.<lambda>  s
    )A, r   )key__)keras.src.saving.keras_saveabler	  r"   r)   type	_obj_typeget_attr_skipsetr   sortedrh   r'   getattr	Exception)saveabler	  obj_typeattr_skipset
child_attr	child_objs         r9   _walk_saveabler    s     =h.*Id8n%57
 	
 !!#H#H-L
 //''S]0FG $
  &**D	*5I )##$
  		s*   BB3B$	B3$	B0-B3/B00B3c           
         ddl m} t        |t        t        t
        t        d       f      st        d| dt        |             t        |t        t        d       f      st        d| dt        |             t        |       |v ry t        | d      r[|rYt        | d      r)t        | j                  t              rd| j                  i}nd }| j                  |j                  ||             t        | d	      r"|r | j                  |j                  |             |j!                  t        |              t#        |       D ]  \  }}t        ||      r5t%        |||t'        j(                  ||      j+                  d
d      |       Gt        |t,        t.        t0        f      sct3        |||t'        j(                  ||      j+                  d
d      |        y )Nr   r  rExpected `weights_store` to be an instance of `H5IOStore`, `ShardedH5IOStore`, `NpzIOStore`, or `None`. Received: r
  PExpected `assets_store` to be an instance of `DiskIOStore` or `None`. Received: save_own_variablesro   metadatasave_assetsr   r{   rQ   rR   )r  r	  r"   rZ   r   r[   r  r)   r\   r   hasattrro   r&   r"  maker%  addr  r]   r
   rU   r   r   dicttuple_save_container_state)	r  rO   rP   rQ   rR   r	  r$  r  r  s	            r9   r]   r]     s    >	#3ZdL &ym1D0EG
 	

 l[$t*$=>%i\0B/CE
 	
 
(|((x-.=8V$HMM3)G.HH##zH=	
 x'L\..z:;"X,' "0!9 
Ii/%??:zBJJ# #4 	D$#67!%??:zBJJ# #4r   c                    ddl m} t        |t        t        t
        t        d       f      st        d| dt        |             t        |t        t        d       f      st        d| dt        |             |rt        |       |v ry d}	t        | d      rH|rF|s|"	 | j                  |j                  |             n | j                  |j                  |             t        | d	      rH|rF|s|"	 | j                  |j                  |             n | j                  |j                  |             |t!        |      }nd}t#        |       D ]  \  }}t        ||      r8t%        |||t'        j(                  ||      j+                  d
d      ||||       Jt        |t,        t.        t0        f      sft3        |||t'        j(                  ||      j+                  d
d      ||||        |t!        |      |z
  }nd}|	sg||dk  r|j                  t        |              |Ct        |       |v r5|j5                  t        |              |j7                  t        |              y y y y # t        $ r9}
||j                  t        |              | |
f|t        |       <   d}	Y d }
~
d }
~
ww xY w# t        $ r9}
||j                  t        |              | |
f|t        |       <   d}	Y d }
~
d }
~
ww xY w)Nr   r  r   r
  r!  Fload_own_variablesTload_assetsr   r{   rQ   r   rR   r   r   )r  r	  r"   rZ   r   r[   r  r)   r\   r   r'  r.  getr  r)  r/  r   r  r   r
   rU   r   r   r*  r+  _load_container_stateremovepop)r  rO   rP   rQ   r   rR   r   r   r	  failureecurrently_failedr  r  newly_faileds                  r9   r   r   (  s    >	#3ZdL &ym1D0EG
 	

 l[$t*$=>%i\0B/CE
 	
 R\->>Gx-.=,8++M,=,=j,IJ ''(9(9*(EFx'L,8$$\%5%5j%AB   !1!1*!=>#/0 "0!9 
Ii/%??:zBJJ# ,"3!1% 	D$#67!%??:zBJJ# ,"3!1%8 #+,/??(\Q->!!"X,/'BxL<L,L##BxL1NN2h<( -M' w  #/$((H6+3Q;
2h<(	  #/$((H6+3Q;
2h<(	s0     I, 4 J1 ,	J.5.J))J.1	K3:.K..K3c                 F    | |v r|| xx   dz  cc<   |  d||     S d|| <   | S )Nr|   r  r    )ro   
used_namess     r9   _get_unique_namer<    s@    z4AqD)*++JtKr   c                 b    | duxr | j                  |      xs |duxr |j                  |      S )u   True if either store has anything under `path`.

    Used to detect legacy files that predate the nested-container
    recursion added in PR #22362 — older files don't contain the
    `container*` groups the new loader expects.
    N)has_path)rO   rP   r   s      r9   _container_path_presentr?    s>     %F-*@*@*F D @\%:%:4%@r   c           
      ~   ddl m} |
t               }t        |       |v ry |j	                  t        |              i }t        | t              rt        | j                               } | D ]  }t        ||      rht        t        j                  |j                  j                        |      }	t        |||t        j                   ||	      j#                  dd      |       wt        |t        t        t$        f      st        d|      }	t'        |||t        j                   ||	      j#                  dd      ||        y )Nr   r  r   r{   r&  	container)rQ   rR   visited_containers)r  r	  r^   r   r)  r"   r*  r   r   r<  r   to_snake_case	__class____name__r]   r
   rU   r   r+  r,  )
rA  rO   rP   rQ   rR   rB  r	  r;  r  ro   s
             r9   r,  r,    s    >! U	)}**2i=)J)T"))+,	 h. $$$X%7%7%@%@AD %??:t<DDT3O"3 4u"56#K<D!%??:t<DDT3O"3#5%r   c	                 \   ddl m}	 |
t               }t        |       |v ry |j	                  t        |              i }
t        | t              rt        | j                               } | D ]A  }t        ||	      rkt        t        j                  |j                  j                        |
      }t        |||t        j                   ||      j#                  dd      ||||       {t        |t        t        t$        f      st        d|
      }t        j                   ||      j#                  dd      }t'        |||      sX||n	t               }t)        |      }t+        ||||d||||	       t)        |      |kD  rt-        j.                  d	| d
d       .t+        |||||||||	       D y )Nr   r  r   r{   r0  rA  T)rQ   r   rR   r   r   rB  zSkipping nested container at 'z': no matching group found in the saved file. This usually means the file was saved with a Keras version that did not serialize sublayers nested inside containers. Affected layers will retain their freshly-initialized weights.r   r   )r  r	  r^   r   r)  r"   r*  r   r   r<  r   rC  rD  rE  r   r
   rU   r   r+  r?  r   r2  r    r!   )rA  rO   rP   rQ   r   rR   r   r   rB  r	  r;  r  ro   nested_pathtracked_failuresfailed_befores                   r9   r2  r2    s    >! U	)}**2i=)J)T"))+,	 Hh.#$$X%7%7%@%@AD %??:t<DDT3O+"3!1%	 4u"56#K<D$//*d;CCD#NK*|[ )9(D$#% ! !$$4 5%! *"&&7%5)'9
 '(=8
 MM8 F= = $% !&+"3!1%#5
}Hr   c                   6    e Zd ZdZd	dZd Zd Zd Zd Zd Z	y)
r\   zAsset store backed by disk storage.

    If `archive` is specified, then `root_path` refers to the filename
    inside the archive.

    If `archive` is not specified, then `root_path` refers to the full path of
    the target directory.
    Nc                    || _         || _        || _        d | _        | j                  rt	               | _        | j                   dk(  r*t        j                  | j                  | j                         t        j                  | j                  | j                        j                  dd      | _	        | j                   dk(  r t        j                  | j                         y y |dk(  r|| _	        y t	               | _        t        j                  | j                  | j                        j                  dd      | _	        t        j                  | j                         y )Nr   r   r{   rH   )rJ   	root_pathrf   r   r   r
   extract_open_archiverU   r   rx   rT   selfrL  rf   rJ   s       r9   __init__zDiskIOStore.__init__?  s   	"<<'>DLyyC//dllK)dnn gdC   yyC##D$4$45   s{#, +~#-??LL$..$'$$   ##D$4$45r   c                    |j                  dd      }t        j                  | j                        rg|j	                  d      sd|v sd|j                  d      v rt        d| d      t        j                  | j                  |      j                  dd      S t        j                  t        j                  | j                        |      }|t        d| d      |j                  dd      S )z:Resolve `path` under the working dir, rejecting traversal.r   r{   z://z..zInvalid asset path: 'z' escapes the asset directory.)
r   r
   r,   rx   r'   splitr)   rU   resolve_sub_pathresolve_path)rO  r   resolveds      r9   
_full_pathzDiskIOStore._full_pathW  s     ||D#&$$T%5%56 s#u}

38O +D61OP  ??4#3#3T:BB4MM..##D$4$45t
 'v-KL  c**r   c                     |s| j                   S | j                  |      }t        j                  |      st        j                  |       |S r   )rx   rV  r
   rS   rT   rO  r   s     r9   r(  zDiskIOStore.makel  s@    ###t$  &%r   c                 p    |s| j                   S | j                  |      }t        j                  |      r|S y r   )rx   rV  r
   rS   rX  s     r9   r1  zDiskIOStore.gett  s5    ###t$T"Kr   c                     |st        j                  | j                        S 	 t        j                  | j                  |            S # t        $ r Y yw xY w)z<Return True if `path` exists on disk under the store's root.F)r
   rS   rx   rV  r)   rX  s     r9   r>  zDiskIOStore.has_path|  sM    $$T%5%566	$$T__T%:;; 		s   #A 	AAc                 (   | j                   dk(  r7| j                  r+t        | j                  | j                  | j                         | j
                  r@t        j                  | j
                        r t        j                  | j
                         y y y NrH   )	rJ   rf   r   rx   rL  r   r
   rS   r   rO  s    r9   r_   zDiskIOStore.close  sd    99%d.. <<J--dll;dll+ <<r   NN)
rE  
__module____qualname____doc__rP  rV  r(  r1  r>  r_   r:  r   r9   r\   r\   5  s%    60+*,r   r\   c                 .   || vrt        |      | j                  |ddd      }|t        j                  t        j                  fv rt        d|j                         | |   }t        |t        j                        st        dt        |             |S )zRetrieve a Group within a given File or Group.

    Args:
        parent: the parent h5py.File or h5py.Group.
        name: the name of the Group to retrieve.

    Returns:
        The child h5py.Group.
    NTdefaultgetclassgetlinkNot allowed: H5 file with z-Invalid H5 file, expected Group but received )
KeyErrorr1  r   ExternalLinkSoftLinkr)   rE  r"   Groupr  )rp   ro   
group_typegroups       r9   safe_get_h5_grouprn    s     6tnD$tLJd''775j6I6I5JKLL4LEeTZZ(;DK=I
 	
 Lr   i  c           
         || vrt        |      | j                  |ddd      }|t        j                  t        j                  fv rt        d|j                         | |   }t        |t        j                        st        dt        |             |j                  rt        d|j                         |j                  rt        d      t        j                  |j                        |j                  j                   z  }|j"                  j%                         }|t&        kD  r3|t(        |z  kD  r't        d| d	t+        |       d
t+        |       d      |S )zRetrieve a Dataset within a given Group.

    Args:
        group: the parent h5py.Group.
        name: the name of the Dataset to retrieve.

    Returns:
        The child h5py.Dataset.
    NTrc  rg  z,Invalid H5 file, expected Dataset, received z,Not allowed: H5 file with external Dataset: z)Not allowed: H5 file with virtual DatasetzNot allowed: H5 dataset 'r   r   zK are stored on disk; refusing to load a potential decompression/shape bomb.)rh  r1  r   ri  rj  r)   rE  r"   Datasetr  external
is_virtualmathprodshapedtypeitemsizer   get_storage_size_H5_DATASET_BOMB_FLOOR_BYTES_H5_DATASET_MAX_EXPANSIONr   )rm  ro   dataset_typedatasetdeclared_bytesstored_bytess         r9   safe_get_h5_datasetr    sZ    5tn99T4$9ML))4==995l6K6K5LMNNDkGgt||,:4=/J
 	
 :7;K;K:LM
 	
 DEEYYw}}-0F0FFN::..0L556EE'v[#N34J#L12 3EE
 	
 Nr   c                   l    e Zd ZdZddZd ZddZddZd Zd Z	d	 Z
dd
Zd Zd Zd Zd Zd Zd Zy)rZ   a  Numerical variable store backed by HDF5.

    Args:
        path_or_io: `str`, `pathlib.Path` or `io.BytesIO` object. The path where
            to save the model.
        archive: Optional `zipfile.ZipFile` object. If specified, the h5 file
            will be saved inside the archive and `path_or_io` will be used as
            the filename.
        mode: `str`. One of {`"r"`, `"w"`}. The mode to open the h5 file.
            Defaults to `"r"`.
    Nc                    |dvrt        d|       t        |t        t        j                  f      rt        j                  |      | _        nJt        |t        j                        r|t        d      || _        nt        d| dt        |       d      || _
        || _        d | _        | j                  | j
                        | _        d | _        i | _        d | _        d| _        y )NrH   r   .`mode` should be either 'w' or 'r'. Received: zHWhen `path_or_io` is an `io.BytesIO` object, `archive` should be `None`.z\`path_or_io` should be a `str`, `pathlib.Path` or `io.BytesIO` object. Received: path_or_io=r
  .F)r)   r"   r&   rm   rn   
path_or_ior#   r-   	TypeErrorr  rJ   rf   r   _get_h5_fileh5_file_h5_entry_path_h5_entry_group_h5_entry_metadata_h5_entry_initialized)rO  r  rf   rJ   s       r9   rP  zH5IOStore.__init__  s    z!@G  j3"56%ll:6DO
BJJ/" (  )DO==GL IZ(), 
 	 ((9 #!"&%*"r   c                 6    | j                   j                         S r   )r  __bool__r]  s    r9   r  zH5IOStore.__bool__  s     ||$$&&r   c                 `   |xs | j                   }|dvrt        d|       | j                  rj|dk(  rt        j                         | _        n*| j                  j                  t        |      d      | _        t        j                  | j
                  |      S t        j                  ||      S )N)r   rH   az3`mode` should be either 'r', 'w' or 'a'. Received: rH   r   rI   )
rJ   r)   rf   r#   r-   r   r1   r&   r   r.   )rO  r  rJ   s      r9   r  zH5IOStore._get_h5_file  s     tyy&EdVL  <<s{!zz|#||00Z#F99T\\5599Zd33r   c                     | j                   dk7  rt        d      t        |t        t	        d      f      st        d|       || _        |r| j                  ||       | S i | _        d| _        | S )a  Make a new H5 entry group.

        This method is only available in write mode. It defers the creation of
        the H5 entry group until `__setitem__` is called, preventing the
        creation of empty groups.

        Args:
            path: `str`. The variable path.
            metadata: Optional `dict`. The metadata to save with the H5 entry
                group. Defaults to `None`.
        rH   z%`make` is only allowed in write mode.Nz1`metadata` should be a dict or `None`. Received: r#  F)	rJ   r)   r"   r*  r  r  _create_h5_groupr  r  rO  r   r$  s      r9   r(  zH5IOStore.make!  s     99DEE(T4:$67CH:N  #!!$!:  $&D ).D&r   c                    | j                   dk7  rt        d      || _        i | _        d| _        |s+d| j
                  v rt        | j
                  d      | _        | S || j
                  v r-t        | j
                  |      }d|v rt        |d      | _        | S d| j
                  v rK|j                  dd      }|| j
                  v r+t        | j
                  |      }d|v rt        |d      | _        | S )zGet the H5 entry group.

        This method is only available in read mode.

        Args:
            path: `str`. The variable path.
        r   z#`get` is only allowed in read mode.Tvars_layer_checkpoint_dependenciesr   )rJ   r)   r  r  r  r  rn  r   )rO  r   
path_groups      r9   r1  zH5IOStore.get>  s     99BCC"!%)"%'8v'N$K4<<*4<<>J#'8V'L$ ,t||;<<*JKDt||#.t||TB
Z'+<Z+PD(r   c                     || j                   v S )z7Return True if a group exists at `path` in the H5 file.)r  rX  s     r9   r>  zH5IOStore.has_pathb  s    t||##r   c                 J   | j                   j                          | j                  dk(  rS| j                  rG| j                  j	                  t        | j                        | j                  j                                | j                  r| j                  j                          y y r\  )	r  r_   rJ   rf   writestrr&   r  r   r0   r]  s    r9   r_   zH5IOStore.closef  sj    99LL!!#doo"68M8M8OP<<LL  r   c                    |s!| j                   j                  d      | _        n/| j                   j                  |      j                  d      | _        |r1|j                         D ]  \  }}|| j                  j                  |<     d| _        y )Nr  T)r  create_groupr  itemsattrsr  )rO  r   r$  kvs        r9   r  zH5IOStore._create_h5_groupo  s    #'<<#<#<V#DD #'<<#<#<T#B#O#O$D   ( 2101$$**1-2 &*"r   c                 6    | j                   j                         S r   )r  __len__r]  s    r9   r  zH5IOStore.__len__|  s    ##++--r   c                 6    | j                   j                         S r   )r  r   r]  s    r9   r   zH5IOStore.keys  s    ##((**r   c                 6   t        | j                  |      }t        |d      rGd|j                  v r9|j                  d   dk(  r't	        j
                  |t        j                        }|S t        |t        j                        st	        j
                  |      }|S )Nr  rv  bfloat16rv  )
r  r  r'  r  nparray	ml_dtypesr  r"   ndarray)rO  r  values      r9   __getitem__zH5IOStore.__getitem__  sz    #D$8$8#>E7#5;;&G$
2HHU)*<*<=E  E2::.HHUOEr   c                 j   | j                   dvrt        d      | j                  s| j                  | j                         t        j                  |      }t        j                  |j                        dk(  r-| j                  j                  ||      }d|j                  d<   y || j                  |<   y )NrH   r  z.Setting a value is only allowed in write mode.r  )datarv  )rJ   r)   r  r  r  r   convert_to_numpystandardize_dtyperv  r  create_datasetr  )rO  r  r  dss       r9   __setitem__zH5IOStore.__setitem__  s    99J&MNN))!!$"5"56((/$$U[[1Z?%%44Su4EB *BHHW(-D  %r   c                 P    | j                   dvrt        d      | j                  |= y )Nr  z/Deleting a value is only allowed in write mode.)rJ   r)   r  )rO  r  s     r9   __delitem__zH5IOStore.__delitem__  s(    99J&NOO  %r   c                     || j                   v S r   )r  )rO  items     r9   __contains__zH5IOStore.__contains__  s    t++++r   Nr   r   )rE  r_  r`  ra  rP  r  r  r(  r1  r>  r_   r  r  r   r  r  r  r  r:  r   r9   rZ   rZ     sO    
+B'
4:"H$!*.+
.&
,r   rZ   c                        e Zd ZdZddZd fd	Z fdZd Zd Zd Z	d Z
d	 Zd
 Zd Zd Z fdZ fdZ fdZd Z xZS )r   aV  Sharded numerical variable store backed by HDF5.

    Args:
        path_or_io: `str` or `pathlib.Path` object. The path where to save the
            model.
        max_shard_size: `int` or `float`. Maximum size in GB for each sharded
            file. If `None`, no sharding will be done. Defaults to `None`.
        archive: Optional `zipfile.ZipFile` object. If specified, the h5 file
            will be saved inside the archive and `path_or_io` will be used as
            the filename.
        mode: `str`. One of {'r', 'w'}. The mode to open the h5 file. Defaults
            to `"r"`.
    c           	         |dvrt        d|       t        |t        t        j                  f      st        d| dt        |       d      t        j                  |      | _        || _        || _	        d | _
        t        |      dz  | _        | j                  j                  j                  dd      | _        | j                  j                   d	k7  ro| j                  d
k(  rdnd}| j                  j#                  d	      }t%        j&                  | dt        | j                         dt        |       d       || _        d | _        i | _        d | _        d| _        d| _        d| _        d| _        d | _        g | _        | j                  d
k(  rddii d| _        n| j                  rBt=        j>                  tA        | j                  t        | j                                    | _        n9tC        | j                  d      5 }t=        jD                  |      | _        d d d        | jG                         | _$        y # 1 sw Y   xY w)Nr  r  zL`path_or_io` should be a `str`, `pathlib.Path` object. Received: path_or_io=r
  r     @z.weightsrM   z.jsonrH   SavingLoadingzH sharded weights requires `*.json` as the extension. The original path: z will be renamed to Fr   
total_size)r$  
weight_mapr   )%r)   r"   r&   rm   rn   r  r  r   rJ   rf   r   floatr   stemr   	base_namesuffixwith_suffixr    r!   r  r  r  r  current_shard_indexcurrent_shard_sizetotal_shard_sizecurrent_shard_pathcurrent_shard_filenamessharding_configr>   r   r   r1   load_create_new_shard_filer  )rO  r  r   rf   rJ   methodnew_pathmap_files           r9   rP  zShardedH5IOStore.__init__  s   z!@G  *sGLL&9:((2|9T*=M<NaQ  LL,		#N3g=//
B?99w&!%c!1XyFyy,,W5HMM( 114TYY0@ A!(m_A/
 !DI #!"&%*" $% "# !"&')$99 !! !	$D  ||'+zz"4<<TYY@($ $))S) ?X+/99X+>D(?224? ?s   H;;Ic                     g | _         | j                  L| j                   j                  t        j                  | j                  j
                        j                         t        | !  ||      S )a  Make a new H5 entry group.

        This method is only available in write mode. It defers the creation of
        the H5 entry group until `__setitem__` is called, preventing the
        creation of empty groups.

        The information about the current shard is reset.

        Args:
            path: `str`. The variable path.
            metadata: Optional `dict`. The metadata to save with the H5 entry
                group. Defaults to `None`.
        )	r  r  appendrm   rn   filenamero   superr(  )rO  r   r$  rD  s      r9   r(  zShardedH5IOStore.make  sZ     (*$<<#((//T\\22388 w|D(++r   c                    |sd}n|}| j                   d   }|j                  |      xs |j                  d| d      }| t        |t              s|g}|| _        |d   }n	g | _        d}|i|| j
                  j                  k7  rP| j                          | j                  j                  |      | _        | j                  | j
                        | _        t        |   |      S )zGet the H5 entry group.

        This method is only available in read mode. If the path is not found in
        the current shard, it will switch to the correct shard.

        Args:
            path: `str`. The variable path.
        z/varsr  r{   Nr   )r  r1  r"   r   r  r  ro   r_   r   	with_namer  r  r  )rO  r   parsed_pathr  	filenamesr  rD  s         r9   r1  zShardedH5IOStore.get  s     !KK )),7
NN;/ 
:>>}E"4
	  i.&K	+4D( |H+-D(HH0G0G0L0L$LJJL&*ii&9&9(&CD#,,T-D-DEDLw{4  r   c                 |    | j                   j                  di       }d|  dt        fd|D              S )zReturn True if any shard has a group under `path`.

        Resolves via the shard weight-map rather than the currently open
        shard, so the answer is independent of which shard is active.
        r  r{   c              3   N   K   | ]  }|k(  xs |j                          y wr   r  )r   r  leadingprefixs     r9   r   z,ShardedH5IOStore.has_path.<locals>.<genexpr>,  s&     LA1<71<<#77Ls   "%)r  r1  any)rO  r   r  r  r  s      @@r9   r>  zShardedH5IOStore.has_path#  sD     ))--lB?
dV*9ALLLLr   c                    | j                   !| j                   j                          d | _         | j                  dk(  r| j                  | j                  d   d<   t        j                  | j                  d      }| j                  rw| j                  j                  t        | j                        |       | j                  j                  t        | j                        | j                  j                                n0t        | j                  d      5 }|j                  |       d d d        | j                  r| j                  j                          y y # 1 sw Y   1xY w)NrH   r$  r     )indent)r  r_   rJ   r  r  r>   r?   rf   r  r&   r   r  r   r0   r1   r/   )rO  json_strr8   s      r9   r_   zShardedH5IOStore.close.  s   <<#LL DL99%%   ,\: zz$"6"6qAH||%%c$))nh?%%//0$,,2G2G2I $))S) &QGGH%&<<LL  & &s   EEc                 r   | j                    d| j                  dd}| xj                  dz  c_        | j                  j                  |      | _        | j                  | j                        }| j                  j                  t        j                  |j                        j                         d| _        |S )z6Create a new shard file and return the H5 file object.r  05r   r|   F)r  r  r   r  r  r  r  r  rm   rn   r  ro   r  )rO  new_shard_pathr  s      r9   r  z'ShardedH5IOStore._create_new_shard_fileD  s     ~~a 8 8<KH 	 	  A% "&))"5"5n"E##D$;$;<$$++GLL9I9I,J,O,OP%*"r   c                     |dvrt        d|       | j                          | j                  | j                  j	                  |      |      | _        | j                  | j                         y)zSwitch to a different H5 file with the specified mode.

        This is useful for retrieving information from all shards, such as the
        total length, keys, and items.
        )r   r  z.`mode` should be either 'r' or 'a'. Received: rI   N)r)   r_   r  r   r  r  _get_h5_groupr  )rO  r  rJ   s      r9   _switch_h5_filez ShardedH5IOStore._switch_h5_fileP  so     z!@G  	

((II) ) 
 	4../r   c                    t        j                  | j                  j                        j                  | j
                  j                  k7  r;| j                  dk(  rdnd}| j                  | j
                  j                  |       yy)z1Ensure the current shard is the last one created.rH   r  r   rI   N)rm   rn   r  r  ro   r  rJ   r  )rO  rJ   s     r9   _restore_h5_filez!ShardedH5IOStore._restore_h5_file`  sl     LL../44&&++, ))s*3D  !8!8!=!=D I	,r   c                     	 |st        | j                  d      | _        n%t        t        | j                  |      d      | _        d| _        y# t        $ r i | _        d| _        Y yw xY w)zBGet the H5 entry group. If it doesn't exist, return an empty dict.r  TFN)rn  r  r  r  rh  rX  s     r9   r  zShardedH5IOStore._get_h5_groupk  sc    
	/'8v'N$'8%dllD96($ *.D& 	/#%D ).D&	/s   A
A A'&A'c                    | j                   j                         }| j                  D ]L  }|| j                  j                  k(  r| j                  |d       || j                   j                         z  }N | j                          |S Nr   rI   )r  r  r  r  ro   r  r  )rO  	total_lenr  s      r9   r  zShardedH5IOStore.__len__{  s    ((002	44 	8H422777   4--5577I		8
 	r   c                 B   g }t        | j                  j                               }| j                  D ]Z  }|| j                  j
                  k(  r||z  }"| j                  |d       |t        | j                  j                               z  }\ | j                          |S r  )r   r  r   r  r  ro   r  r  )rO  r   current_shard_keysr  s       r9   r   zShardedH5IOStore.keys  s    !$"6"6";";"=>44 	:H422777**$$XC$8T1166899	: 	r   c                 R   || j                   v rt        | 	  |      S | j                  D ]`  }|| j                  j
                  k(  r| j                  |d       || j                   v s?t        | 	  |      }| j                          |c S  t        d| d| j                         )Nr   rI   Key '"' not found in any of the shards: )	r  r  r  r  r  ro   r  r  rh  )rO  r  r  r  rD  s       r9   r  zShardedH5IOStore.__getitem__  s    $&&&7&s++44 	H422777   4d***w*3/%%'	 C5:++,.
 	
r   c           	         | j                          t        j                  |      }t        j                  |j                        }t        j                  |j                        }t        j                  |      }||z  dz  }| xj                  |z  c_
        || j                  kD  r5t        |      }t        | j                        }t        d| d| d| d      | xj                  |z  c_        | j                  | j                  kD  r,| j                          | j!                         | _        || _        t$        | M  ||       | j(                  j*                  }	| j,                  j*                  }
| j.                  d   }|	|vr|
||	<   y t1        ||	   t2              s	||	   g||	<   |
||	   vr||	   j5                  |
       y y )N   zThe size of z is z& which exceeds the maximum shard size zJ. You can increase the `max_shard_size` parameter to accommodate the size.r  )r  r   r  r  rv  rs  rt  ru  r	   
dtype_sizer  r   r   r)   r  r_   r  r  r  r  r  ro   r  r  r"   r   r  )rO  r  r  rv  weight_countsper_param_size
value_sizevalue_size_strmax_shard_size_strvariable_pathshard_filenamer  rD  s               r9   r  zShardedH5IOStore.__setitem__  s    ((/))%++6		%++.$//6"^3a7
++++1*=N!5d6I6I!Jse4'7 822D1E F  	:-""T%8%88JJL668DL&0D#C' ,,110055)),7

*(6J}%j7>-7-F,G
=)Z%>>=)00@ ?r   c                 P   || j                   v rt        | 	  |       y | j                  D ]^  }|| j                  j
                  k(  r| j                  |d       || j                   v s?t        | 	  |       | j                           y  t        d| d| j                         )Nr  rI   r  r  )	r  r  r  r  r  ro   r  r  rh  )rO  r  r  rD  s      r9   r  zShardedH5IOStore.__delitem__  s    $&&&G$44 	H422777   4d***#C(%%'	 C5:++,.
 	
r   c                     || j                   v ry| j                  D ]O  }|| j                  j                  k(  r| j	                  |d       || j                   v s?| j                           y | j                          y)NTr   rI   F)r  r  r  ro   r  r  )rO  r  r  s      r9   r  zShardedH5IOStore.__contains__  s    4'''44 	H422777   4t+++%%'	 	r   )rz   Nr   r   )rE  r_  r`  ra  rP  r(  r1  r>  r_   r  r  r  r  r  r   r  r  r  r  __classcell__)rD  s   @r9   r   r     sY    75r,* !D	M!,
0 J/ 

"'AR
$r   r   c                   4    e Zd ZddZd	dZd Zd Zd Zd Zy)
r[   Nc                    || _         || _        || _        |dk(  ri | _        y| j                  r|j	                  |d      | _        nt	        |d      | _        t        j                  | j
                  d      | _        y)a  Numerical variable store backed by NumPy.savez/load.

         If `archive` is specified, then `root_path` refers to the filename
        inside the archive.

        If `archive` is not specified, then `root_path` refers to the path of
        the npz file on disk.
        rH   r   rI   r   F)allow_pickleN)rL  rJ   rf   contentsr1   r8   r  r  rN  s       r9   rP  zNpzIOStore.__init__  sf     #	3;DM|| ic:id3GGDFF?DMr   c                 ~    |si | j                   d<   | j                   d   S i | j                   |<   | j                   |   S N__root__r  r  s      r9   r(  zNpzIOStore.make  s?    (*DMM*%==,, d}}T""r   c                     |s(d| j                   v rt        | j                   d         S i S || j                   v r.| j                  |       | j                   |   j                         S i S r  )r  r*  _reject_npz_bombtolistrX  s     r9   r1  zNpzIOStore.get	  sa    T]]*DMM*566I4== !!$'==&--//	r   c           
      X   t        | j                  dd      }|y	 |j                  | d      }|j	                  |      5 }t        j                  |      \  }}t        t
        d| dt
        j                        } ||      \  }}}	ddd       t        j                        	j                  z  }
t        |j                  d      }|
t        kD  r>|
t        |z  kD  r1t        d| dt!        |
       d	t!        |j                         d
      yy# t        $ r Y yw xY w# 1 sw Y   xY w)a  Guard against npz shape/decompression bombs.

        Reading `self.contents[path]` makes NumPy allocate an array sized to
        the `.npy` header's declared shape before the stored data is
        validated, so a tiny member can declare a huge shape and drive an
        unbounded allocation. Reject a member whose declared size hugely
        exceeds the number of bytes actually stored for it.
        zipNz.npyread_array_header__0r|   zRefusing to load npz weight 'z': its header declares r   zD is stored on disk; refusing to load a potential decompression bomb.)r  r  r   rh  r1   
npy_format
read_magicread_array_header_2_0rs  rt  rw  maxr   _NPZ_MEMBER_BOMB_FLOOR_BYTES_NPZ_MEMBER_MAX_EXPANSIONr)   r   )rO  r   zip_filer   member_filemajorr  read_headerru  rv  r}  r~  s               r9   r
  zNpzIOStore._reject_npz_bomb  sI    4==%6	##tfDM2D ]]4  	7K!,,[9HE1!$UG2.00K
 *+6OE1e	7 5)ENN:4--q199!:\!II/v5L'78
'(:(:;< =II  J :  			7 	7s   D AD 	DD D)c                     || j                   v S )z:Return True if `path` exists as a key in the npz contents.r  rX  s     r9   r>  zNpzIOStore.has_path8  s    t}}$$r   c                 V   | j                   dk(  r| j                  r.| j                  j                  | j                  dd      | _        nt        | j                  d      | _        t        j                  | j                  fi | j                   | j                  j                          y )NrH   T)rJ   force_zip64r   rI   )	rJ   rf   r1   rL  r8   r  savezr  r_   r]  s    r9   r_   zNpzIOStore.close<  su    99||**NN$ +  dnn48HHTVV-t}}-r   r  r   )	rE  r_  r`  rP  r(  r1  r
  r>  r_   r:  r   r9   r[   r[     s"    @*##J%	r   r[   c                  z    t        j                         } t        j                  |       }|j                          | S )Nrg   )rq   mkdtempTemporaryFiler_   )temp_dirtestfiles     r9   r   r   H  s/    !H%%(3HNNOr   c                 R   t        j                  d|  d       }||S t        dg      }| dk(  r)ddlm}  |       }|j                  t        |             n| dk(  r)ddlm}  |       }|j                  t        |             n| dk(  r.ddlm}  |       }|j                  t        |      d	d
gz          nU| dk(  r-ddlm}  |       }|j                  t        |      dgz          n#| dk(  rCddl	m
} ddlm}  |       } |g g       }|j                  t        |      t        |      z          n| dk(  r:ddlm}	  |	d      }|j                  t        |             |j                  d       n| dk(  r(ddlm}
  |
       }|j                  t        |             no| dk(  r*ddlm}  |dd      }|j                  t        |             n@| dk(  r,ddlm}  |dd d      }|j                  t        |             nt+        d| d       t        j,                  d!|  |       |S )"Nsaving_attr_skiplist_$_self_unconditional_dependency_names	Operationr   )r&  Layer)r'  r  
operations_operationsr  _functionalMetric)r+  )CompileMetrics	Optimizer)r-  g      ?	variablesLoss)r/  Cross)r0  r:  r|   Feature)r1  int32c                     | S r   r:  r  s    r9   r  z"get_attr_skipset.<locals>.<lambda>  s    Q r   intz&get_attr_skipset got invalid obj_type=z. Accepted values for `obj_type` are ['Operation', 'Layer', 'Functional', 'Sequential', 'Metric', 'Optimizer', 'Loss', 'Cross', 'Feature']saving_attr_skipset_)r   get_global_attributer^   keras.src.ops.operationr&  updaterh   keras.src.layers.layerr'  keras.src.metrics.metricr+   keras.src.trainers.compile_utilsr,  keras.src.optimizers.optimizerr-  r3  keras.src.losses.lossr/  ,keras.src.layers.preprocessing.feature_spacer0  r1  r)   set_global_attribute)r  skipsetr&  ref_objr'  r+  r,  	ref_obj_a	ref_obj_br-  r/  r0  r1  s                r9   r  r  O  s   //
z*DG 2	
G
 ;5+s7|$	W	0's7|$	\	!0's7||]&CCD	\	!0's7|}o56	X	3CH	"2r*	s9~I67	[	 <C.s7|${#	V	.&s7|$	W	FA,s7|$	Y	H';6s7|$5H; 77 7
 	
 %%
xj)7 Nr   c                     t         d}nt        j                         j                  }t        | j                        |t
        z  k  S )zCheck if there is sufficient memory to load the model into memory.

    If psutil is installed, we can use it to determine whether the memory is
    sufficient. Otherwise, we use a predefined value of 1 GB for available
    memory.
    r  )psutilvirtual_memory	availabler   r.  _MEMORY_UPPER_BOUND)r2   available_memorys     r9   rl   rl     sC     ~-!002<<5??+
0
0	1r   c                     g }	 t         j                  j                  |       \  }}|r|j                  |       n|r|j                  |       nn|} N|j	                          |S )zSplit a relative path into a list of individual components.

    Uses ``os.path.split`` iteratively so the result is independent of
    the platform path separator.

    Example::

        _split_path_components("a/b/c.txt") -> ["a", "b", "c.txt"]
    )r   r   rR  r  reverse)r   partsheadtails       r9   _split_path_componentsrO    s`     E
WW]]4(
dLLLL  
MMOLr   c                 d   | j                         D ]  \  }}t        j                  j                  |v s6t        j                  j                  r*t        j                  j                  |v rt        d|       t        j                  ||      }|t        d|       t        |t              r$t        j                  |d       t        ||       t        |t        j                        st        |d      5 }|j                  |j!                                ddd        y# 1 sw Y   xY w)av  Recursively write a nested dict of numpy arrays to a directory tree.

    Each dict key becomes a directory or filename. Leaf values (numpy
    arrays) are written as binary files.

    Args:
        tree: A nested dictionary of numpy arrays.
        base_dir: The base directory to write the assets to. Must be resolved
            via `file_utils.resolve_path` first.
    zInvalid asset path: NTr   r   )r  r   r   sepaltsepr)   r
   rS  r"   r*  rT   _write_nested_dict_to_dirr  r  r1   r/   tobytes)treebase_dirr  r  
child_pathr8   s         r9   rS  rS    s     jjl )
U77;;#"''..RWW^^s5J3C59::003?
3C59::eT"KK
T2%eZ8rzz*j$' )1() ))) )s   9 D%%D/	c                    t        dd      }	 t        | d|dt                      i }|j                  }t	        j
                  |      D ]  \  }}}|D ]  }t        j                  j                  ||      }t        j                  j                  ||      }	t        |	      }
t        |d      5 }t        j                  |j                         t        j                        }ddd       |}|
dd	 D ]  }|j                  |i       } ||
d	   <     |r|nd	 |j!                          S # 1 sw Y   JxY w# |j!                          w xY w)
a  Save model assets to a nested dictionary.

    Collects assets (e.g. vocabulary files) from the model using the
    Keras ``_save_state`` mechanism and returns them as a nested dictionary
    that mirrors the directory hierarchy. Leaf values are numpy uint8
    arrays containing file contents.

    For example, a file at ``layer/sublayer/vocab.txt`` is stored as::

        {"layer": {"sublayer": {"vocab.txt": np.array([...])}}}

    Using a nested structure instead of flat path keys avoids
    platform-specific path separator issues and zip-slip vulnerabilities.

    Args:
        model: The model whose assets should be collected.

    Returns:
        A nested dictionary of numpy uint8 arrays mirroring the asset
        directory tree, or ``None`` if the model has no assets.
    r   rH   rI   NrM   rN   r   r  )r\   r]   r^   rx   r   walkr   rU   relpathrO  r1   r  
frombufferr   uint8
setdefaultr_   )r2   rP   assets_treerx   rootdirsfilesfname	file_pathrelrL  r8   r  nodeparts                  r9   _save_assets_to_dictrh    s=   , xc2L%!e	
 "..!#!5 
	'D$ 	'GGLLu5	ggooi=.s3)T* Ca==BDC"!#2J 5D??44D5"&U2Y	'
	' *{t3C C 	s$   BD6 -4D*!7D6 *D3/D6 6Ec           
         |syt        j                         5 }t        j                  |      }t	        ||       t        |d      }t        | d|dt               t               i        |j                          ddd       y# 1 sw Y   yxY w)a  Load assets from a nested dictionary into the model.

    Reconstructs the asset directory tree from a nested dictionary
    produced by ``_save_assets_to_dict`` and loads the assets into
    the model via the Keras ``_load_state`` mechanism.

    Args:
        model: The model to load assets into.
        assets_dict: Nested dictionary mirroring the asset directory
            tree, with numpy uint8 arrays as leaf values.
    Nr   rI   rM   r   )	rq   r   r
   rT  rS  r\   r   r^   r_   )r2   assets_dictr   rP   s       r9   _load_assets_from_dictrk    s     		$	$	& '))'2!+w7"75%!e U	
 	  s   A!BB)r   T)NTTr^  )FN)F)FNNNr   )^ra  r@   r#   r>   rs  r   rm   r   rq   r    ri   r  numpyr  	numpy.libr   r  	keras.srcr   keras.src.backend.commonr   "keras.src.saving.serialization_libr   r   r   keras.src.utilsr	   r
   r   r   r   #keras.src.utils.model_visualizationr   keras.src.utils.module_utilsr   keras.src.utils.summary_utilsr   r   keras.src.versionr   r<   rE  r   r   rW   rV   _VARS_FNAMErX   rs   rY   rH  r  r  r   r:   rF   r+   r%   r*   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r]   r   r<  r?  r,  r2  r\   rn  ry  rz  r  rZ   r   r[   r   r  rl   rO  rS  rh  rk  r:  r   r9   <module>rw     s   9  	   	        *  1 A G E ' & $ " & ; - > < :
 ! $ =$ M&   '  ! "FAR
&DJ*Z8
v'T1h.  '  
L` ;?77v ;?;7|" $<>L d)N	$ -r _DV, V,rB  '   )XB, B,JEy EP
Y YxGT"2)40fY?  F  Os$   E E& E#"E#&E0/E0