
    9iek                     B   S SK r S SKrS SKJ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Jr  S SKrS SKrS SKJrJr  S SKJr  \" 5       rSrSrS	r/ S
Qr " S S\R                  5      r " S S5      rSS\\\4   4S jjr " S S\R@                  5      r!g)    N)Path)FunctionType)DictUnion)ConfigFields	ModelFile)
get_logger_base__delete__deprecation_)filenametextpretty_textc                   2   ^  \ rS rSrSrS rU 4S jrSrU =r$ )
ConfigDict   zDict which support get value through getattr

Examples:
    >>> cdict = ConfigDict({'a':1232})
    >>> print(cdict.a)
    >>> # 1232
c                     [        U5      eN)KeyErrorselfnames     W/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/utils/config.py__missing__ConfigDict.__missing__(   s    tn    c                    >  [         [        U ]  U5      nU$ ! [         a*    [	        SU R
                  R                   SU S35      n Ue[         a  nUn S nAUeS nAff = f)N'z' object has no attribute ')superr   __getattr__r   AttributeError	__class____name__	Exception)r   r   valueexer"   s        r   r    ConfigDict.__getattr__+   s{    	*d7=E L  	7!DNN$;$;#< =..2V1!6 7B 	  	B 		s    0A!	A!AA! )	r#   
__module____qualname____firstlineno____doc__r   r    __static_attributes____classcell__r"   s   @r   r   r      s    
 
r   r   c                   D  ^  \ rS rSrSr\S 5       r\S 5       r\S 5       rSU 4S jjr	\
S 5       r\
S 5       r\
S	 5       rS
 rS rS rS rS rS rS rS rS rU 4S jrU 4S jrS S\4S jjrS!S\4U 4S jjjrS"U 4S jjr\S#S j5       rS\4S jrS$S jr Sr!U =r"$ )%Config8   a  A facility for config and config files.

It supports common file formats as configs: python/json/yaml. The interface
is the same as a dict object and also allows access config values as
attributes.

Example:
    >>> cfg = Config(dict(a=1, b=dict(c=[1,2,3], d='dd')))
    >>> cfg.a
    1
    >>> cfg.b
    {'c': [1, 2, 3], 'd': 'dd'}
    >>> cfg.b.d
    'dd'
    >>> cfg = Config.from_file('configs/examples/configuration.json')
    >>> cfg.filename
   'configs/examples/configuration.json'
    >>> cfg.b
    {'c': [1, 2, 3], 'd': 'dd'}
    >>> cfg = Config.from_file('configs/examples/configuration.py')
    >>> cfg.filename
    "configs/examples/configuration.py"
    >>> cfg = Config.from_file('configs/examples/configuration.yaml')
    >>> cfg.filename
    "configs/examples/configuration.yaml"
c                    [         R                  " [         R                  " U 5      5      n [         R                  " U 5      (       d  [	        SU  35      e[         R
                  " U 5      S   nUS;  a  [        S5      e[        R                  " 5        n[        R                  " X!S9n[        R                  " 5       S:X  a  UR                  5         [         R                  " UR                  5      n[        R                   " XR                  5        U R#                  S5      (       a  SS	KJn  U" [         R(                  " X$5      5      u  pg0 nUR*                  R-                  5        Hc  u  pU	R/                  S
5      (       a  M  [1        U
[2        R4                  5      (       a  M>  [1        U
[2        R6                  5      (       a  M_  XU	'   Me     [8        R:                  U	 O.U R#                  S5      (       a  SSKJn  U" UR                  5      nUR                  5         S S S 5        U S-   n[A        U SSS9 nXRC                  5       -  nS S S 5        WU4$ ! , (       d  f       N== f! , (       d  f       WU4$ = f)NzFile does not exists    .py.json.yaml.yml-Only py/yml/yaml/json type are supported now!)dirsuffixWindowsr7   r   )import_modules_from_file__)r:   r9   r8   )load
rutf-8encoding)"ospabspath
expanduserexists
ValueErrorsplitextIOErrortempfileTemporaryDirectoryNamedTemporaryFileplatformsystemclosebasenamer   shutilcopyfileendswithmodelscope.utils.import_utilsr?   join__dict__items
startswith
isinstancetypes
ModuleTyper   sysmodulesmodelscope.fileiorA   openread)r   fileExtnametmp_cfg_dirtmp_cfg_filetmp_cfg_namer?   module_nanmemodcfg_dictr   r%   rA   cfg_textfs                 r   
_file2dictConfig._file2dictT   s   ;;s~~h78zz(##4XJ?@@ll8,Q/??IJJ((*k#665L I-""$<<(9(9:LOOH&7&78  ''R$<HH[7%9!#&<<#5#5#7KD??400%eU-=-=>>%eU-?-?@@).	 $8 KK-""#=>>2 1 12 5 +8 d?(C'2a H 3 !!C +*: 32 !!s,   C-II%IAI6I&
I#&
I7c                     [        U [        5      (       a  [        U 5      n [        R	                  U 5      u  p[        XU S9$ )N)rl   r   )r]   r   strr2   rn   )r   rk   rl   s      r   	from_fileConfig.from_file   s8    h%%8}H#..x8hHEEr   c                 l   US;  a  [        S5      eUS:w  a  SU ;   a  [        R                  S5        [        R                  " SSUSS	9 nUR                  U 5        S
S
S
5        [        R                  WR                  5      n[        R                  " UR                  5        U$ ! , (       d  f       NO= f)zGenerate config from config str.

Args:
    cfg_str (str): Config str.
    file_format (str): Config file format corresponding to the
       config str. Only py/yml/yaml/json type are supported now!

Returns:
    :obj:`Config`: Config obj.
r6   r;   r7   dict(z6Please check "file_format", the file format may be .pywrD   F)rF   r=   deleteN)rM   loggerwarningrN   rP   writer2   rr   r   osremove)cfg_strfile_format	temp_filecfgs       r   from_stringConfig.from_string   s     ??IJJ%Gw$6NNHJ((gk!*OOG$ y~~.
		)..!
 s   
B%%
B3c                   > Uc  [        5       nO,[        U[         5      (       d  [        S[        U5       35      eU H  nU[        ;   d  M  [        U S35      e   [        U[        5      (       a  [        U5      n[        [        U ]+  S[        U5      5        [        [        U ]+  SU5        U(       a  UnO.U(       a%  [        USSS9 nUR                  5       nS S S 5        OSn[        [        U ]+  S	W5        g ! , (       d  f       N#= f)
Nz!cfg_dict must be a dict, but got z is reserved for config file	_cfg_dict	_filenamerC   rD   rE    _text)dictr]   	TypeErrortypeRESERVED_KEYSr   r   rq   r   r2   __setattr__r   rc   rd   )r   rk   rl   r   keyr   rm   r"   s          r   __init__Config.__init__   s    vHHd++ ##'>"24 5 5Cm##&BCDD  h%%8}Hfd'Z5IJfd'X>Dhg6!vvx 76 Dfd'6	 76s   
C;;
D	c                     U R                   $ r   )r   r   s    r   r   Config.filename   s    ~~r   c                     U R                   $ r   )r   r   s    r   r   Config.text   s    zzr   c                    ^^^^	^
^ SmS m
SU
U4S jjmSUUU
U4S jjm	S mSUUUU	U
U4S jjmU R                   R                  5       nT" USS9n[        S	SSS
9nSSKJn  U" X#SS9u  p%U$ )N   c                     U R                  S5      n[        U5      S:X  a  U $ UR                  S5      nU Vs/ s H
  oAS-  U-   PM     nnSR                  U5      nUS-   U-   nU$ s  snf )NrB   r5   r    )splitlenpoprY   )s_
num_spacessfirstlines        r   _indent#Config.pretty_text.<locals>._indent   sm    A1v{	EE!HE789qts"d*qA9		!Aq AH :s   A&c                    > [        U[        5      (       a  SU S3nO[        U5      nU(       a.  [        U [        5      (       a  SU  S3O
[        U 5      nU SU 3nO[        U 5       SU 3nT" UT5      nU$ )Nr   : =)r]   rq   )kvuse_mappingv_strk_strattr_strr   indents         r   _format_basic_types/Config.pretty_text.<locals>._format_basic_types   s}    !S!!A3aA$.q#$6$6!A3aCF#WBug.!!fXQug.x0HOr   c                 P  > [        S U 5       5      (       a  SnUSR                  UUU	4S jU 5       5      R                  S5      -  nU(       a.  [        U [        5      (       a  SU  S3O
[	        U 5      nU SU 3nO[	        U 5       SU 3nT" UT	5      S	-   nU$ T" XU5      nU$ )
Nc              3   B   #    U  H  n[        U[        5      v   M     g 7fr   )r]   r   ).0_s     r   	<genexpr>;Config.pretty_text.<locals>._format_list.<locals>.<genexpr>   s     21:a&&s   z[
rB   c              3   J   >#    U  H  nS T" T" U5      T5       S3v   M     g7f)ru   z),Nr)   )r   v__format_dictr   r   s     r   r   r      s.      #! GL$4f=>bAs    #,r   r   r   ])allrY   rstripr]   rq   )
r   r   r   r   r   r   r   r   r   r   s
         r   _format_list(Config.pretty_text.<locals>._format_list   s    2222 #!#! !!'- (21c(:(:as!HAE"'5'2H"%a&5'2H"8V4s: O /q[AOr   c                 ^    SnU  H$  nU[        U5      R                  5       (       + -  nM&     U$ )NF)rq   isidentifier)dict_strcontain_invalid_identifierkey_names      r   _contain_invalid_identifier7Config.pretty_text.<locals>._contain_invalid_identifier   s8    ).&$*X33557* % .-r   c                 p  > Sn/ nT" U 5      nU(       a  US-  n[        U R                  5       5       H  u  nu  pgU[        U 5      S-
  :  nU(       d  U(       a  SOSn	[        U[        5      (       a`  ST" U5      -   n
U(       a.  [        U[
        5      (       a  SU S3O
[        U5      nU SU
 3nO[        U5       SU
 3nT" UT5      S	-   U	-   nO.[        U[        5      (       a  T" XgU5      U	-   nOT" XgU5      U	-   nUR                  U5        M     USR                  U5      -  nU(       a  US
-  nU$ )Nr   {r5   r   rB   r   z: dict(z=dict()})		enumerater[   r   r]   r   rq   listappendrY   )
input_dictoutest_levelrC   r   r   idxr   r   is_lastendr   r   r   r   r   r   r   r   r   s                r   r   (Config.pretty_text.<locals>._format_dict   s6   AA5jAKS()9)9);<VaZ1!44(Gba&& <?2E",6q#,>,>!A3aCF&+WGE7#;&)!fXVE7#;&x83>DH4((+A+>DH21EKH"!  =" 1ASHr   T)r   pep8)based_on_style%blank_line_before_nested_class_or_def+split_before_expression_after_opening_parenr   )
FormatCode)style_configverifyF)r   to_dictr   yapf.yapflib.yapf_apir   )r   rk   r   
yapf_styler   r   r   r   r   r   r   r   s         @@@@@@r   r   Config.pretty_text   s}     		 		 	"	.	 	: >>))+H48!268<>
 	5T4Hr   c                 V    SU R                    SU R                  R                  5        3$ )NzConfig (path: z): )r   r   __repr__r   s    r   r   Config.__repr__"  s'    c$..2I2I2K1LMMr   c                 ,    [        U R                  5      $ r   )r   r   r   s    r   __len__Config.__len__%  s    4>>""r   c                 .    [        U R                  U5      $ r   )getattrr   r   s     r   r    Config.__getattr__(  s    t~~t,,r   c                 8    U R                   R                  U5      $ r   )r   __getitem__r   s     r   r   Config.__getitem__+  s    ~~))$//r   c                 z    [        U[        5      (       a  [        U5      nU R                  R	                  X5        g r   )r]   r   r   r   r   r   r   r%   s      r   r   Config.__setattr__.  +    eT""u%E""4/r   c                 z    [        U[        5      (       a  [        U5      nU R                  R	                  X5        g r   )r]   r   r   r   __setitem__r   s      r   r   Config.__setitem__3  r   r   c                 ,    [        U R                  5      $ r   )iterr   r   s    r   __iter__Config.__iter__8  s    DNN##r   c                 H    U R                   U R                  U R                  4$ r   )r   r   r   r   s    r   __getstate__Config.__getstate__;  s    

;;r   c                     U R                   nUR                  U5      nUR                  R                  U R                  5        U$ r   )r"   __new__rZ   update)r   clsothers      r   __copy__Config.__copy__>  s4    nnC dmm,r   c                    > U R                   nUR                  U5      nX1[        U 5      '   U R                  R	                  5        H-  u  pE[
        [        U]  U[        R                  " XQ5      5        M/     U$ r   )
r"   r   idrZ   r[   r   r2   r   copydeepcopy)r   memor   r   r   r%   r"   s         r   __deepcopy__Config.__deepcopy__E  s_    nnC RX----/JC&%,S$--2LM 0 r   c                    > Uu  p#n[         [        U ]  SU5        [         [        U ]  SU5        [         [        U ]  SU5        g )Nr   r   r   )r   r2   r   )r   stater   r   r   r"   s        r   __setstate__Config.__setstate__O  s@    &+#	efd'Y?fd'Y?fd'7r   	key_chainc                   ^^
  UR                  S5      nU R                  nU H  m
SnST
;   a'  T
R                  S5      u  m
nUR                  S5      u  pg[        U[        [        45      (       a*  Tc   S5       e[        [        U
U4S jU5      5      nUS   nOUT
   nUc  M  U[        U5         nM     U$ ! [         a<  n	[        R                  SU S	U 35        [        R                  U	5        Us Sn	A	$ Sn	A	ff = f)
a  Get a value with a key-chain in str format, if key does not exist, the default value will be returned.

This method is safe to call, and will not edit any value.

Args:
    key_chain: The input key chain, for example: 'train.hooks[0].type'
    default: The default value returned when any key does not exist, default None.
    type_field: Get an object from a list or tuple for example by 'train.hooks.CheckPointHook', in which
        'hooks' is a list, and 'CheckPointHook' is a value of the content of key `type_field`.
        If there are multiple matched objects, the first element will be returned.
Returns:
    The value, or the default value.
.N[r   zWGetting object without an index from a list or tuple needs an valid `type_field` param.c                    > U T   T:H  $ r   r)   )subr   
type_fields    r   <lambda>!Config.safe_get.<locals>.<lambda>p  s    3z?c+Ar   r   zKey not valid in Config: z, return the default value: )
r   r   r]   r   tuplefilterintr$   rx   debug)r   r
  defaultr  keysr   valr   _sub_cfg_dictr'   r   s      `      @r   safe_getConfig.safe_getU  s   	??3'DI#:"yy~HC YYs^FCi$77%1 X 4X X1$(A9M%OM -a 0I )#I? )#c( 3I    	LL+I;6RSZR[\ LLON	s$   BB8 $B8 8
C>1C93C>9C>filec                   > SSK Jn  [        [        U ]  S5      R                  5       nUc]  U R                  b   U R                  R                  S5      (       a  U R                  $ U R                  R                  S5      S   nU" X4S9$ UR                  S5      (       a0  [        US	S
S9 nUR                  U R                  5        SSS5        gUR                  S5      S   nU" X1US9$ ! , (       d  f       g= f)a  Dumps config into a file or returns a string representation of the
config.

If a file argument is given, saves the config to that file using the
format defined by the file argument extension.

Otherwise, returns a string representing the config. The formatting of
this returned string is defined by the extension of `self.filename`. If
`self.filename` is not defined, returns a string representation of a
 dict (lowercased and using ' for strings).

Examples:
    >>> cfg_dict = dict(item1=[1, 2], item2=dict(a=0),
    ...     item3=True, item4='test')
    >>> cfg = Config(cfg_dict=cfg_dict)
    >>> dump_file = "a.py"
    >>> cfg.dump(dump_file)

Args:
    file (str, optional): Path of the output file where the config
        will be dumped. Defaults to None.
r   )dumpr   Nr7   r  )r~   rv   rD   rE   )r  r~   )rb   r  r   r2   __getattribute__r   r   rW   r   r   rc   rz   )r   r  r  rk   r~   rm   r"   s         r   r  Config.dump~  s    . 	+7DLLN<}}$(>(>u(E(E'''"mm11#6r:H>>]]5!!dC'2a(() 32 **S/"-KEE	 32s   *C**
C8c           
      >  > 0 nUR                  5        HK  u  pVUnUR                  S5      nUSS  H!  n	UR                  U	[        5       5        Xy   nM#     US   n	XgU	'   MM     [        [
        U ]  S5      n
[        [
        U ]  S[
        R                  UU
UUS95        g)a  Merge dict into cfg_dict.

Merge the dict parsed by MultipleKVAction into this cfg.

Examples:
    >>> options = {'model.backbone.depth': 50,
    ...            'model.backbone.with_cp':True}
    >>> cfg = Config(dict(model=dict(backbone=dict(type='ResNet'))))
    >>> cfg.merge_from_dict(options)
    >>> cfg_dict = super(Config, self).__getattribute__('_cfg_dict')
    >>> assert cfg_dict == dict(
    ...     model=dict(backbone=dict(type='ResNet', depth=50, with_cp=True)))

    >>> # Merge list element for replace target index
    >>> cfg = Config(dict(pipeline=[
    ...     dict(type='Resize'), dict(type='RandomDistortion')]))
    >>> options = dict(pipeline={'0': dict(type='MyResize')})
    >>> cfg.merge_from_dict(options, allow_list_keys=True)
    >>> cfg_dict = super(Config, self).__getattribute__('_cfg_dict')
    >>> assert cfg_dict == dict(pipeline=[
    ...     dict(type='MyResize'), dict(type='RandomDistortion')])

    >>> # Merge list element for replace args and add to list, only support list of type dict with key ``type``,
    >>> # if you add new list element, the list does not guarantee the order,
    >>> # it is only suitable for the case where the order of the list is not concerned.
    >>> cfg = Config(dict(pipeline=[
    ...     dict(type='Resize', size=224), dict(type='RandomDistortion')]))
    >>> options = dict(pipeline=[dict(type='Resize', size=256), dict(type='RandomFlip')])
    >>> cfg.merge_from_dict(options, allow_list_keys=True)
    >>> cfg_dict = super(Config, self).__getattribute__('_cfg_dict')
    >>> assert cfg_dict == dict(pipeline=[
    ...     dict(type='Resize', size=256), dict(type='RandomDistortion'), dict(type='RandomFlip')])

    >>> # force usage
    >>> options = {'model.backbone.depth': 18,
    ...            'model.backbone.with_cp':True}
    >>> cfg = Config(dict(model=dict(backbone=dict(type='ResNet', depth=50))))
    >>> cfg.merge_from_dict(options, force=False)
    >>> cfg_dict = super(Config, self).__getattribute__('_cfg_dict')
    >>> assert cfg_dict == dict(
    ...     model=dict(backbone=dict(type='ResNet', depth=50, with_cp=True)))

Args:
    options (dict): dict of configs to merge from.
    allow_list_keys (bool): If True, int string keys (e.g. '0', '1')
      are allowed in ``options`` and will replace the element of the
      corresponding index in the config if the config is a list.
      Or you can directly replace args for list or add new list element,
      only support list of type dict with key ``type``,
      but if you add new list element, the list does not guarantee the order,
      It is only suitable for the case where the order of the list is not concerned.
      Default: True.
    force (bool): If True, existing key-value will be replaced by new given.
        If False, existing key-value will not be updated.
r  Nr   r   )allow_list_keysforce)	r[   r   
setdefaultr   r   r2   r!  r   _merge_a_into_b)r   optionsr$  r%  option_cfg_dictfull_keyr   dkey_listsubkeyrk   r"   s              r   merge_from_dictConfig.merge_from_dict  s    p "==?KHA~~c*H"3B-VZ\2I ( b\FfI + 7Dfd'"" /	 # 	r   c                    UR                  5       nU R                  5        GH  u  pEU(       ap  UR                  5       (       a[  [        U[        5      (       aF  [        U5      n[        U5      U::  a  [        SU SU 35      e[        R                  XQU   X#S9X'   M}  U(       Ga  [        U[        5      (       Ga  XA;   Ga  [        X   [        5      (       d(  [        S[        U5       S[        X   5       SU 35      eSnX   U-    H2  n[        U[        5      (       a  SU;  d  M   XA;  d  U(       a  XQU'   S	nM4     U(       Ga.  / n/ / p[        X   5       Ho  u  p[        U5       H[  u  pUS   US   :X  d  M  UR                  [        R                  UUUUS95        U
R                  U5        U	R                  U5          Mm     Mq     [        [        X   5      5       Vs/ s H  nX;  d  M
  X   U   PM     nn[        [        U5      5       Vs/ s H  oU
;  d  M
  X[   PM     nnUU-   nU[        [        U5      5       Vs/ s H  n[        R                  UU   0 X#S9PM     sn-  nXU'   GMU  GMX  [        U[        5      (       a  XA;   a  UR!                  ["        S	5      (       dq  U(       a  [        [        4O[        n[        X   U5      (       d)  [%        U S
U SU S[        X   5       S["         S3
5      e[        R                  XQU   X#S9X'   GM  XA;  d
  U(       d  GM  XQU'   GM     U$ s  snf s  snf s  snf )a  merge dict ``a`` into dict ``b`` (non-inplace).

Values in ``a`` will overwrite ``b``. ``b`` is copied first to avoid
in-place modifications.

Args:
    a (dict): The source dict to be merged into ``b``.
    b (dict): The origin dict to be fetch keys from ``a``.
    allow_list_keys (bool): If True, int string keys (e.g. '0', '1')
      are allowed in source ``a`` and will replace the element of the
      corresponding index in b if b is a list. Default: False.
    force (bool): If True, existing key-value will be replaced by new given.
        If False, existing key-value will not be updated.

Returns:
    dict: The modified dict of ``b`` using ``a``.

Examples:
    # Normally merge a into b.
    >>> Config._merge_a_into_b(
    ...     dict(obj=dict(a=2)), dict(obj=dict(a=1)))
    {'obj': {'a': 2}}

    # Delete b first and merge a into b.
    >>> Config._merge_a_into_b(
    ...     dict(obj=dict(_delete_=True, a=2)), dict(obj=dict(a=1)))
    {'obj': {'a': 2}}

    # b is a list
    >>> Config._merge_a_into_b(
    ...     {'0': dict(a=2)}, [dict(a=1), dict(b=2)], True)
    [{'a': 2}, {'b': 2}]

    # value of a and b are both list, only support list of type dict with key ``type``,
    # You can directly replace args for list or add new list element,
    # but if you add new list element, the list does not guarantee the order,
    # it is only suitable for the case where the order of the list is not concerned.
    >>> Config._merge_a_into_b(
    ...     {'k': [dict(a=2), dict(c=3)]}, {'k': [dict(a=1), dict(b=2)]}, True)
    {'k': [dict(a=2), dict(b=2), dict(c=3)]}

    # force is False
    >>> Config._merge_a_into_b(
    ...     dict(obj=dict(a=2, b=2)), dict(obj=dict(a=1))), True, force=False)
    {'obj': {'a': 1, b=2}}
zIndex z exceeds the length of list )r%  ztype mismatch z and z between a and b for key Tr   Fr   z2 in child config cannot inherit from base because z. is a dict in the child config but is of type z in base config. You may set `z =True` to ignore the base config)r  r[   isdigitr]   r   r  r   r   r2   r'  rK   r   r   r   r   ranger   
DELETE_KEYr   )abr$  r%  r   r   _is_dict_with_typelist_ires_listadded_index_bkadded_index_vib_lija_ljrest_bkrest_vrestallowed_typess                      r   r'  Config._merge_a_into_b  sS   ` FFHGGIDA199;;:a3F3FFq6Q;"VA3.J1##NOO--t_ . ; Z4%8%8QV!!$--$(a	tADzlB[\][^_  &*"dQhF%fd33vV7K:#$aD-2*	 '
 &!H46M#,QT?'0|GA#F|tF|; ($*$:$:(,(,(7.3	 %; %5!6 !. 4 4Q 7 . 5 5a 8 % (4 $3 */s14y)9)9A2  Q)9  
 ',CFm&37Mm   #V+D "'s4y!1! "2A .. GR / G!1! H
 $aD9 &: A " "&'fQUU:u5M5M0?tT!!$66##Qqc "##$# &  $QT
| ,&<'GIJ J
 --t_ . ; :aDy z 9!s   %	L92L9	L>"L>"Mreturnc                 6    U R                   R                  5       $ )z-Convert Config object to python dict
        )r   r   r   s    r   r   Config.to_dict_  s     ~~%%''r   c                    / nU R                   R                  5        GH   u  pESU 3nU(       a  UR                  SS5      n[        U[        5      (       a  U(       a  UR                  U5        MS  [        U[        [        [        45      (       a-  UR                  U5        UR                  [        U5      5        M  [        U[        5      (       a`  UR                  U5        [        U[        [        [        [        45      (       d   SUS    35       eUR                  [        U5      5        GM  [        SU 35      e   U" U5      $ )a{  Convert config obj to args using parse_fn

Args:
    parse_fn: a function object, which takes args as input,
        such as ['--foo', 'FOO'] and return parsed args, an
        example is given as follows
        including literal blocks::
            def parse_fn(args):
                parser = argparse.ArgumentParser(prog='PROG')
                parser.add_argument('-x')
                parser.add_argument('--foo')
                return parser.parse_args(args)
    use_hyphen (bool, optional): if set true, hyphen in keyname
        will be converted to underscore
Return:
    args: arg object parsed by argparse.ArgumentParser
z--r   -zJElement type in list is expected to be either int,str,float, but got type r   ztype in config file which supported to be converted to args should be either bool, int, str, float or list of them but got type )r   r[   replacer]   boolr   r  rq   floatr   rK   )r   parse_fn
use_hyphenargsr   r   arg_names          r   to_argsConfig.to_argsd  s   $ NN((*DAA3xH#++C5!T""qH%AS%011H%CF#At$$H%!!c3t%<== S @LLMaD6@S S=CF# DDE3HI I +( ~r   r)   )NNN)Nr   r   )TT)FT)T)#r#   r*   r+   r,   r-   staticmethodrn   rr   r   r   propertyr   r   r   r   r   r    r   r   r   r   r   r   r  r  rq   r  r  r.  r'  r   r   rP  r.   r/   r0   s   @r   r2   r2   8   s   6 )" )"V F F  670     \ \|N#-00
0
$<8'# 'R$F $F $FLIV m m^( (
' 'r   r2   r   c                   ^  [        T [        5      (       a  [        R                  T 5      m SU 4S jjnU" [        R
                  5        U" [        R                  5        U" [        R                  5        U(       aY  U" [        R                  5        U" [        R                  5        U" [        R                  5        U" [        R                  5        gg)zCheck whether configuration file is valid, If anything wrong, exception will be raised.

Args:
    cfg (str or ConfigDict): Config file path or config object.
    is_training: indicate if checking training related elements
c                 d   > [        TU 5      (       d   SU  S[        R                   SU 35       eg )Nz
Attribute z is missing from z. )hasattrr   CONFIGURATION)	attr_namemsgr   s     r   
check_attr check_config.<locals>.check_attr  s=    sI&& 	0*YK?P&&'r#)0 	0&r   N)r   )r]   rq   r2   rr   r   	frameworktaskpipelinemodeltrainpreprocessor
evaluation)r   is_trainingrZ  s   `  r   check_configrd    s     #ss#0 |%%&|  !|$$%<%%&<%%&<,,-<**+	 r   c                       \ rS rSrSrS rSrg)JSONIteratorEncoderi  zImplement this method in order that supporting arbitrary iterators, it returns
a serializable object for ``obj``, or calls the base implementation
(to raise a ``TypeError``).

c                     [        U[        5      (       a  g  [        U5      n[        U5      $ ! [         a     Of = f[
        R                  R                  X5      $ r   )r]   r   r   r   r   jsonJSONEncoderr  )r   objiterables      r   r  JSONIteratorEncoder.default  sY    c<((	"CyH >!  		 ''22s   . 
;;r)   N)r#   r*   r+   r,   r-   r  r.   r)   r   r   rf  rf    s    	3r   rf  r   )"r  r{   os.pathpathrG   rQ   rU   r`   rN   r^   pathlibr   r   typingr   r   addictrh  modelscope.utils.constantr   r   modelscope.utils.loggerr	   rx   BASE_KEYr3  DEPRECATION_KEYr   r   r2   rq   rd  ri  rf  r)   r   r   <module>rv     s   
  	    
        = .	
!3 2S	 S	l,eCO, ,43$** 3r   