
    rhP                        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
 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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 jB                  e jB                  dddeeeee   f      dee   dedeg ef   dee"   de jF                  fdZ$ G d de      Z%y)    N)ArgumentDefaultsHelpFormatterArgumentParserArgumentTypeError)Iterable)copy)Enum)isclass)Path)AnyCallableLiteralNewTypeOptional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    l/var/www/html/ai-insurance-compliance-backend/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_functionr1   1   s*     8??VS[&(?M22 @s   !)aliaseshelpdefaultdefault_factorymetadatar2   r3   r4   r5   r6   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.
    r2   r3   )r6   r4   r5    )dataclassesfield)r2   r3   r4   r5   r6   kwargss         r#   HfArgr<   @   sO    H %khQ`kdjkkr%   c            	       X    e Zd ZU dZee   ed<   ddeeeee   f      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ej2                  f   ded	eed
f   fdZ	 ddeeej2                  f   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_typesc                    |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_classr8   )
r   r   r   super__init__r9   is_dataclasslistr?   _add_dataclass_arguments)selfr?   r;   dtype	__class__s       r#   rC   zHfArgumentParser.__init__   s    " OOX6./O F*(EF$%"6"##O4./O#O4)) 	1E))%0	1r%   parserr:   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                  t6        t$           k(  rt	        |      }t8        |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<   nt;        |      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 r~|j                  t$        u s|j                  t6        t$           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 defaultr2   
__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&   typer4   TrequiredF?nargsconst+z--no_z--no-store_false)actiondest)!nameappendreplacer6   r   r   rR   r/   RuntimeErrorpopgetattrr   hasattrtypesrO   __args__len
ValueErrorr    r   
issubclassr   valuer1   r4   r9   MISSINGr   r$   r	   rE   r5   add_argument)	rJ   r:   long_optionsr;   r2   origin_typebool_kwargsxr4   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(SW.<X%*K	"F

|$

**3456 %ZZ	
  =Y [ %Bs   WrH   c           	      (   t        |d      r| j                  |j                        }n| }	 t        |      }t        j                  |      D ]5  }|j                  s||j                     |_        | j#                  ||       7 y # t        $ r t        d| d      t        $ rl}t        j                  d d dk  rPdt        |      v rCdj                  t        t        t        j                  d d             }t        d| d	| d
      | d }~w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)rP   )   
   z!unsupported operand type(s) for |.rq   z on Python a6  . Try removing line of `from __future__ import annotations` which opts in union types as `X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To support Python versions that lower than 3.10, you need to use `typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of `X | None`.)ra   add_argument_grouprp   r   	NameErrorr^   	TypeErrorsysversion_infor/   joinmapr9   fieldsinitr[   rR   rn   )rG   rH   rJ   
type_hintsexpython_versionr:   s          r#   rF   z)HfArgumentParser._add_dataclass_arguments   s-   501,,U-G-GHFF	*8*?J* !''. 	7E::#EJJ/EJ''6		7)  	-eW 56 6 
  	#g-2UY\]_Y`2`!$#c33C3CBQ3G*H!I"1%NCS T" "  	s   B  D%A'DD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\   )rR   rY   )argsrM   NrQ   z?Some specified arguments are not used by the HfArgumentParser: r8   )rd   rw   argvr\   r
   with_suffixr   ri   r/   parse_known_argsvarsr+   lstripextendexists	read_textsplitr?   r9   r{   r|   r[   itemsdelattr__dict__re   )rG   r   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outputsrH   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
r   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: r8   )setr   r?   r9   r{   r|   r[   r   difference_updater\   re   sortedtuple)rG   r   r   unused_keysr   rH   r   r   r   r"   r   r   s               r#   
parse_dictzHfArgumentParser.parse_dicts  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   )rG   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   )rG   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__r   r   rC   staticmethodr   r9   Fieldrn   rF   r   r   r   dictr/   r   r    r   osPathLiker   r   __classcell__)rI   s   @r#   r>   r>   o   s@    m,,1}h}F]7]1^(_ 1" g~ gk>O>O g gR 7m  7H !&T 
y#~	TltCH~  RWXacfXfRg : LQsBKK/0DH	y#~	2 LQsBKK/0DH	y#~	r%   r>   )&r9   r   r   rw   rb   argparser   r   r   collections.abcr   r   enumr   inspectr	   pathlibr
   typingr   r   r   r   r   r   r   r   r   r   r$   rE   r/   r1   rh   r   r   r<   r>   r8   r%   r#   <module>r      s     	 
  U U $     S S S  K%	-

3t 3#0D 3" 04&&)4)<)<#,leCcN+,,l 3-,l 	,l
 b#g&,l tn,l ,l^L~ Lr%   