
    謜iM                        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mZmZ d dl	m
Z
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mZmZmZmZ d dlZ ed	e      Z ed
e      Zd Zdede
egef   fdZdde j@                  e j@                  dddeee   z  dz  dedz  dede
g ef   de!dz  de jD                  fdZ# G d de      Z$y)    N)ArgumentDefaultsHelpFormatterArgumentParserArgumentTypeError)CallableIterable)copy)Enum)isclass)Path)AnyLiteralNewTypeUnionget_type_hints	DataClassDataClassTypec                     t        | t              r| S | j                         dv ry| j                         dv ryt        d|  d      )N)yestruety1T)nofalsefn0FzTruthy value expected: got zJ but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).)
isinstanceboollowerr   )vs    U/mnt/e/genesis-system/.venv/lib/python3.12/site-packages/transformers/hf_argparser.pystring_to_boolr#   $   sO    !Twwy22	
4	4)!,vw
 	
    choicesreturnc                 L    | D ci c]  }t        |      | c}fdS c c}w )aN  
    Creates a mapping function from each choices string representation to the actual value. Used to support multiple
    value types for a single argument.

    Args:
        choices (list): List of choices.

    Returns:
        Callable[[str], Any]: Mapping function from string representation to actual value for each choice.
    c                 (    j                  | |       S N)get)argstr_to_choices    r"   <lambda>z+make_choice_type_function.<locals>.<lambda>=   s    }((c2 r$   )str)r%   choicer,   s     @r"   make_choice_type_functionr0   1   s*     8??VS[&(?M22 @s   !)aliaseshelpdefaultdefault_factorymetadatar1   r2   r3   r4   r5   c                 X    |i }| | |d<   |||d<   t        j                  d|||d|S )a  Argument helper enabling a concise syntax to create dataclass fields for parsing with `HfArgumentParser`.

    Example comparing the use of `HfArg` and `dataclasses.field`:
    ```
    @dataclass
    class Args:
        regular_arg: str = dataclasses.field(default="Huggingface", metadata={"aliases": ["--example", "-e"], "help": "This syntax could be better!"})
        hf_arg: str = HfArg(default="Huggingface", aliases=["--example", "-e"], help="What a nice syntax!")
    ```

    Args:
        aliases (Union[str, list[str]], optional):
            Single string or list of strings of aliases to pass on to argparse, e.g. `aliases=["--example", "-e"]`.
            Defaults to None.
        help (str, optional): Help string to pass on to argparse that can be displayed with --help. Defaults to None.
        default (Any, optional):
            Default value for the argument. If not default or default_factory is specified, the argument is required.
            Defaults to dataclasses.MISSING.
        default_factory (Callable[[], Any], optional):
            The default_factory is a 0-argument function called to initialize a field's value. It is useful to provide
            default values for mutable types, e.g. lists: `default_factory=list`. Mutually exclusive with `default=`.
            Defaults to dataclasses.MISSING.
        metadata (dict, optional): Further metadata to pass on to `dataclasses.field`. Defaults to None.

    Returns:
        Field: A `dataclasses.Field` with the desired properties.
    r1   r2   )r5   r3   r4    )dataclassesfield)r1   r2   r3   r4   r5   kwargss         r"   HfArgr;   @   sO    H %khQ`kdjkkr$   c            	       H    e Zd ZU dZee   ed<   ddeee   z  dz  f fdZede	de
j                  fd       Zdefd	Z	 	 	 	 	 dd
eedf   fdZddeeef   ded
eedf   fdZddeej.                  z  ded
eedf   fdZddeej.                  z  ded
eedf   fdZ xZS )HfArgumentParsera  
    This subclass of `argparse.ArgumentParser` uses type hints on dataclasses to generate arguments.

    The class is designed to play well with the native argparse. In particular, you can add more (non-dataclass backed)
    arguments to the parser after initialization and you'll get the output back after parsing as an additional
    namespace. Optional: To create sub argument groups use the `_argument_group_name` attribute in the dataclass.

    Args:
        dataclass_types (`DataClassType` or `Iterable[DataClassType]`, *optional*):
            Dataclass type, or list of dataclass types for which we will "fill" instances with the parsed args.
        kwargs (`dict[str, Any]`, *optional*):
            Passed to `argparse.ArgumentParser()` in the regular way.
    dataclass_typesNc                    |g }nt        |t              s|g}d|vr	t        |d<   t        |   di | t        j                  |      r|g}t        |      | _        | j                  D ]  }| j                  |        y )Nformatter_classr7   )
r   r   r   super__init__r8   is_dataclasslistr>   _add_dataclass_arguments)selfr>   r:   dtype	__class__s       r"   rB   zHfArgumentParser.__init__   s    " OOX6./O F*(EF$%"6"##O4./O#O4)) 	1E))%0	1r$   parserr9   c                    d|j                    g}d|j                   v r.|j                  d|j                   j                  dd              |j                  j	                         }t        |j                  t              rt        d      |j                  dg       }t        |t              r|g}t        |j                  d|j                        }|t        u s,t        t        d      rt        |t        j                        rt        |j                  j                  vr\t!        |j                  j                        dk7  s!t        d       |j                  j                  vrt#        d	|j                    d
      t        d       |j                  j                  vrx|j                  j                  d   t        u r|j                  j                  d   n|j                  j                  d   |_        t        |j                  d|j                        }nt$        |j                  j                  vr{t        d |j                  j                  d         r|j                  j                  d   n|j                  j                  d   |_        t        |j                  d|j                        }i }|t&        u s4t        |j                  t              rt)        |j                  t*              r|t&        u r|j                  j                  |d<   n'|j                  D cg c]  }|j,                   c}|d<   t/        |d         |d<   |j0                  t2        j4                  ur|j0                  |d<   nd|d<   n|j                  t$        u s|j                  t$        d z  k(  rt	        |      }t6        |d<   |j                  t$        u s*|j0                  U|j0                  t2        j4                  ur8|j0                  t2        j4                  u rdn|j0                  }||d<   d|d<   d|d<   nt9        |      rt)        |t:              rs|j                  j                  d   |d<   d|d<   |j<                  t2        j4                  ur|j=                         |d<   n|j0                  t2        j4                  u rvd|d<   np|j                  |d<   |j0                  t2        j4                  ur|j0                  |d<   n5|j<                  t2        j4                  ur|j=                         |d<   nd|d<    | j>                  g ||i | |j0                  du rz|j                  t$        u s|j                  t$        d z  k(  rQd|d<    | j>                  d|j                    d|j                   j                  dd       fd|j                   d| y y y c c}w )Nz--_-zpUnresolved type detected, which should have been done with the help of `typing.get_type_hints` method by defaultr1   
__origin__	UnionType   zOnly `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because the argument parser only supports one type per argument. Problem encountered in field 'z'.   r   r%   typer3   TrequiredF?nargsconst+z--no_z--no-store_false)actiondest) nameappendreplacer5   r   r   rQ   r.   RuntimeErrorpopgetattrr   hasattrtypesrN   __args__len
ValueErrorr   r   
issubclassr	   valuer0   r3   r8   MISSINGr#   r
   rD   r4   add_argument)	rI   r9   long_optionsr:   r1   origin_typebool_kwargsxr3   s	            r"   _parse_dataclass_fieldz'HfArgumentParser._parse_dataclass_field   s    UZZL)*%**"UZZ%7%7S%A$B CD$$& ejj#&< 
 **Y+gs#iGejj,

C%GE;$?J{\a\k\kDl%**---EJJ''(A-d5::CVCV1V 66;jj\E 
 Dz!4!447<zz7J7J17MQT7TUZZ003Z_ZdZdZmZmnoZp
%ejj,

KUZZ000 /9uzz?R?RST?U.VEJJ''*\a\f\f\o\opq\r 
 &ejj,

K '!jT&BzRWR\R\^bGcg%$)JJ$7$7y!6;jj$AQWW$Ay!6vi7HIF6N}}K$7$77$)MMy!%)z"ZZ45::#< v,K ,F6NzzT!emm&?EMMYdYlYlDl#(==K4G4G#G%U]]$+y!"%w"&w[!jd&C"ZZ003F6N!F7O$$K,?,??$)$9$9$;y!+"5"55%)z""ZZF6N}}K$7$77$)MMy!&&k.A.AA$)$9$9$;y!%)z">\>G>v> ==D ejjD&8EJJ$QU+<U%*K	"F

|$

**3456 %ZZ	
  =V [ %Bs   W
rG   c                 B   t        |d      r| j                  |j                        }n| }	 t        |      }t        j                  |      D ]5  }|j                  s||j                     |_
        | j                  ||       7 y # t        $ r t        d| d      w xY w)N_argument_group_namezType resolution failed for z. Try declaring the class in global scope or removing line of `from __future__ import annotations` which opts in Postponed Evaluation of Annotations (PEP 563))r`   add_argument_groupro   r   	NameErrorr]   r8   fieldsinitrZ   rQ   rm   )rF   rG   rI   
type_hintsr9   s        r"   rE   z)HfArgumentParser._add_dataclass_arguments   s    501,,U-G-GHFF	*8*?J !''. 	7E::#EJJ/EJ''6		7  	-eW 56 6 	s   B Br&   .c                     |s|s|rst        t        j                        rYg }|r|j                  t	        |             nU|rSt        t        j                        r:|j                  t	        t        j                  d         j                  d             |rt               }|j                  |t        d       |j                  |      \  }}t        |      j                  |j                  d      d      }	|	r(|j                  |	D 
cg c]  }
t	        |
       c}
       g }|D ]4  }|j                         s||j                         j!                         z  }6 |||z   n|t        j                  dd z   }| j                  |      \  }}g }| j"                  D ]  }t%        j&                  |      D ch c]  }|j(                  s|j*                   }}t        |      j-                         D ci c]  \  }}||v s|| }}}|D ]  }t/        ||         |d
i |}|j                  |        t        |j0                        dkD  r|j                  |       |rg ||S |rt3        d	|       g |S c c}
w c c}w c c}}w )a%  
        Parse command-line args into instances of the specified dataclass types.

        This relies on argparse's `ArgumentParser.parse_known_args`. See the doc at:
        docs.python.org/3/library/argparse.html#argparse.ArgumentParser.parse_args

        Args:
            args:
                List of strings to parse. The default is taken from sys.argv. (same as argparse.ArgumentParser)
            return_remaining_strings:
                If true, also return a list of remaining argument strings.
            look_for_args_file:
                If true, will look for a ".args" file with the same base name as the entry point script for this
                process, and will append its potential content to the command line args.
            args_filename:
                If not None, will uses this file instead of the ".args" file specified in the previous argument.
            args_file_flag:
                If not None, will look for a file in the command-line args specified with this flag. The flag can be
                specified multiple times and precedence is determined by the order (last one wins).

        Returns:
            Tuple consisting of:

                - the dataclass instances in the same order as they were passed to the initializer.abspath
                - if applicable, an additional namespace for more (non-dataclass backed) arguments added to the parser
                  after initialization.
                - The potential list of remaining argument strings. (same as argparse.ArgumentParser.parse_known_args)
        r   z.argsr[   )rQ   rX   )argsrL   NrP   z?Some specified arguments are not used by the HfArgumentParser: r7   )rc   sysargvr[   r   with_suffixr   rh   r.   parse_known_argsvarsr*   lstripextendexists	read_textsplitr>   r8   rr   rs   rZ   itemsdelattr__dict__rd   )rF   rv   return_remaining_stringslook_for_args_fileargs_filenameargs_file_flag
args_filesargs_file_parsercfgcmd_args_file_pathsp	file_args	args_file	namespaceremaining_argsoutputsrG   r   keyskr!   inputsobjs                          r"   parse_args_into_dataclassesz,HfArgumentParser.parse_args_into_dataclasses  s`   J ]/Ac#((mJ!!$}"56#CHH!!$sxx{"3"?"?"HI #1#3  --n3x-X -==4=H	T&*3immN4I4I#4NPT&U#&%%8K&L1tAw&LMI' ?	##%!4!4!6!<!<!>>I? (,'79t#YRSRT=UD$($9$9t$9$D!	>)) 	 E$/$6$6u$=HqAFFHDH'+I'<'<'>Ltq!!t)adLFL &	1%&/&/CNN3	  y!!"Q&NN9%#-W-n-- #bcqbr!sttW;9 'M ILs   
J 8J
J6J
J
rv   allow_extra_keysc                    t        |j                               }g }| j                  D ]  }t        j                  |      D ch c]  }|j
                  s|j                   }}|j                         D 	ci c]  \  }}	||v s||	 }
}}	|j                  |
j                                 |di |
}|j                  |        |s|rt        dt        |             t        |      S c c}w c c}	}w )a<  
        Alternative helper method that does not use `argparse` at all, instead uses a dict and populating the dataclass
        types.

        Args:
            args (`dict`):
                dict containing config values
            allow_extra_keys (`bool`, *optional*, defaults to `False`):
                Defaults to False. If False, will raise an exception if the dict contains keys that are not parsed.

        Returns:
            Tuple consisting of:

                - the dataclass instances in the same order as they were passed to the initializer.
        z0Some keys are not used by the HfArgumentParser: r7   )setr   r>   r8   rr   rs   rZ   r   difference_updater[   rd   sortedtuple)rF   rv   r   unused_keysr   rG   r   r   r   r!   r   r   s               r"   
parse_dictzHfArgumentParser.parse_dictf  s      $))+&)) 	 E$/$6$6u$=HqAFFHDH'+zz|Atq!qDyadAFA))&++-8/&/CNN3	   KOPVWbPcOdeffW~ IAs   C,C,7C1C1	json_filec                     t        t        |      d      5 }t        j                  |j	                               }ddd       | j                  |      }t        |      S # 1 sw Y   'xY w)at  
        Alternative helper method that does not use `argparse` at all, instead loading a json file and populating the
        dataclass types.

        Args:
            json_file (`str` or `os.PathLike`):
                File name of the json file to parse
            allow_extra_keys (`bool`, *optional*, defaults to `False`):
                Defaults to False. If False, will raise an exception if the json file contains keys that are not
                parsed.

        Returns:
            Tuple consisting of:

                - the dataclass instances in the same order as they were passed to the initializer.
        zutf-8)encodingNr   )openr   jsonloadsreadr   r   )rF   r   r   open_json_filedatar   s         r"   parse_json_filez HfArgumentParser.parse_json_file  s]    " $y/G4 	5::n1134D	5//$9I/JW~	5 	5s   $A!!A*	yaml_filec                     | j                  t        j                  t        |      j	                               |      }t        |      S )at  
        Alternative helper method that does not use `argparse` at all, instead loading a yaml file and populating the
        dataclass types.

        Args:
            yaml_file (`str` or `os.PathLike`):
                File name of the yaml file to parse
            allow_extra_keys (`bool`, *optional*, defaults to `False`):
                Defaults to False. If False, will raise an exception if the json file contains keys that are not
                parsed.

        Returns:
            Tuple consisting of:

                - the dataclass instances in the same order as they were passed to the initializer.
        r   )r   yaml	safe_loadr   r   r   )rF   r   r   r   s       r"   parse_yaml_filez HfArgumentParser.parse_yaml_file  s7    " //$..i1J1J1L"M`p/qW~r$   r)   )NFTNN)F)__name__
__module____qualname____doc__r   r   __annotations__rB   staticmethodr   r8   Fieldrm   rE   r   r   r   dictr.   r   r   r   osPathLiker   r   __classcell__)rH   s   @r"   r=   r=   o   s%    m,,18O(ORV(V 1" g~ gk>O>O g gR7m 7. !&T 
y#~	TltCH~  RWXacfXfRg 8r{{): d _denpses_t ,r{{): d _denpses_t r$   r=   )%r8   r   r   rw   ra   argparser   r   r   collections.abcr   r   r   enumr	   inspectr
   pathlibr   typingr   r   r   r   r   r   r   r   r#   rD   r.   r0   rg   r   r   r;   r=   r7   r$   r"   <module>r      s     	 
  U U .     ? ?  K%	-

3t 3#0D 3" '+&&)4)<)< ,l49_t#,l *,l 	,l
 b#g&,l Tk,l ,l^{~ {r$   