o $ i?@sddlmZddlZddlZddlZddlZddlmZmZddl m Z m Z ddl m Z ddlmZddlmZddlmZdd lmZmZmZmZmZmZmZgd ZGd d d eZGd ddZGdddZGdddeeZ GdddeZ!dS)) annotationsN)ABCabstractmethod)MappingSequence) import_module)pformat)Any)EXPR_KEY) CompInitMode ensure_tuplefirst instantiateoptional_import run_debugrun_eval)ComponentLocator ConfigItemConfigExpressionConfigComponent Instantiablec@s,eZdZdZed ddZedd d Zd S)rz0 Base class for an instantiable object. argsr kwargsreturnboolcOtd|jjd)z^ Return a boolean flag to indicate whether the object should be instantiated. subclass  must implement this method.NotImplementedError __class____name__selfrrr$Z/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/bundle/config_item.py is_disabled#zInstantiable.is_disabledobjectcOr)zK Instantiate the target component and return the instance. rrrr"r$r$r%r*r'zInstantiable.instantiateN)rr rr rr)rr rr rr()r! __module__ __qualname____doc__rr&rr$r$r$r%rs  rc@s>eZdZdZdZddddZdd d ZdddZdddZdS)ra7 Scan all the available classes and functions in the MONAI package and map them with the module paths in a table. It's used to locate the module path for provided component name. Args: excludes: if any string of the `excludes` exists in the full module name, don't import this module. monaiNexcludesSequence[str] | str | NonecCs |durgnt||_d|_dSN)r r-_components_table)r#r-r$r$r%__init__>s zComponentLocator.__init__r list[str]csfddtjDS)za Find all the modules start with MOD_START and don't contain any of `excludes`. cs4g|]jrtfddjDrqS)c3s|]}|vVqdSr/r$).0smr$r% GszAComponentLocator._find_module_names...) startswith MOD_STARTallr-)r3r#r5r% Gs4z7ComponentLocator._find_module_names..)sysmodulesr;r$r;r%_find_module_namesBr'z#ComponentLocator._find_module_namesmodnamesSequence[str] | strdict[str, list]c Csi}t|D]9}z.t|}t|D]"\}}t|s t|r4|j|kr4||vr-g||<|||qWqty?Yqw|S)z Find all the classes and functions in the modules with specified `modnames`. Args: modnames: names of the target modules to find all the classes and functions. ) r rinspect getmembersisclass isfunctionr)appendModuleNotFoundError)r#r@tablemodnamemodulenameobjr$r$r%_find_classes_or_functionsIs  z+ComponentLocator._find_classes_or_functionsrLstrlist[str] | str | NonecCsbt|ts td|d|jdur|||_|j|}t|tr/t|dkr/|d}|S)a Get the full module name of the class or function with specified ``name``. If target component name exists in multiple packages or modules, return a list of full module names. Args: name: name of the expected class or function. z(`name` must be a valid string, but got: .Nr) isinstancerO ValueErrorr0rNr?getlistlen)r#rLmodsr$r$r%get_component_module_name`s   z*ComponentLocator.get_component_module_namer/)r-r.)rr2)r@rArrB)rLrOrrP) r!r)r*r+r9r1r?rNrYr$r$r$r%r2s   rc@sBeZdZdZddd d Zdd d Zdd dZddZdddZdS)ra Basic data structure to represent a configuration item. A `ConfigItem` instance can optionally have a string id, so that other items can refer to it. It has a build-in `config` property to store the configuration object. Args: config: content of a config item, can be objects of any types, a configuration resolver may interpret the content to generate a configuration object. id: name of the current config item, defaults to empty string. configr idrOrNonecCs||_||_dSr/r[r\)r#r[r\r$r$r%r1s zConfigItem.__init__cC|jS)zj Get the ID name of current config item, useful to identify config items during parsing. )r\r;r$r$r%get_idzConfigItem.get_idcCs ||_dS)z Replace the content of `self.config` with new `config`. A typical usage is to modify the initial config content at runtime. Args: config: content of a `ConfigItem`. Nr[)r#r[r$r$r% update_configs zConfigItem.update_configcCr_)zA Get the config content of current config item. rbr;r$r$r% get_configrazConfigItem.get_configcCst|jdt|jS)Nz: )typer!rr[r;r$r$r%__repr__szConfigItem.__repr__N)rZ)r[r r\rOrr])rrO)r[r rr]) r!r)r*r+r1r`rcrdrfr$r$r$r%rus   rcsdeZdZdZhdZ   ddfdd Zed ddZddZddZ d!ddZ d"ddZ Z S)#ra Subclass of :py:class:`monai.bundle.ConfigItem`, this class uses a dictionary with string keys to represent a component of `class` or `function` and supports instantiation. Currently, three special keys (strings surrounded by ``_``) are defined and interpreted beyond the regular literals: - class or function identifier of the python module, specified by ``"_target_"``, indicating a monai built-in Python class or function such as ``"LoadImageDict"``, or a full module name, e.g. ``"monai.transforms.LoadImageDict"``, or a callable, e.g. ``"$@model.forward"``. - ``"_requires_"`` (optional): specifies reference IDs (string starts with ``"@"``) or ``ConfigExpression`` of the dependencies for this ``ConfigComponent`` object. These dependencies will be evaluated/instantiated before this object is instantiated. It is useful when the component doesn't explicitly depend on the other `ConfigItems` via its arguments, but requires the dependencies to be instantiated/evaluated beforehand. - ``"_disabled_"`` (optional): a flag to indicate whether to skip the instantiation. - ``"_desc_"`` (optional): free text descriptions of the component for code readability. - ``"_mode_"`` (optional): operating mode for invoking the callable ``component`` defined by ``"_target_"``: - ``"default"``: returns ``component(**kwargs)`` - ``"callable"``: returns ``component`` or, if ``kwargs`` are provided, ``functools.partial(component, **kwargs)`` - ``"debug"``: returns ``pdb.runcall(component, **kwargs)`` Other fields in the config content are input arguments to the python module. .. code-block:: python from monai.bundle import ComponentLocator, ConfigComponent locator = ComponentLocator(excludes=["modules_to_exclude"]) config = { "_target_": "LoadImaged", "keys": ["image", "label"] } configer = ConfigComponent(config, id="test", locator=locator) image_loader = configer.instantiate() print(image_loader) # Args: config: content of a config item. id: name of the current config item, defaults to empty string. locator: a ``ComponentLocator`` to convert a module name string into the actual python module. if `None`, a ``ComponentLocator(excludes=excludes)`` will be used. excludes: if ``locator`` is None, create a new ``ComponentLocator`` with ``excludes``. See also: :py:class:`monai.bundle.ComponentLocator`. >Z_desc__mode__target_ _disabled_Z _requires_rZNr[r r\rOlocatorComponentLocator | Noner-r.rr]cs2tj||d|durt|d|_dS||_dS)Nr^)r-)superr1rrj)r#r[r\rjr-r r$r%r1s"zConfigComponent.__init__rcCst|tod|vS)z Check whether this config represents a `class` or `function` that is to be instantiated. Args: config: input config content to check. rh)rSrrbr$r$r%is_instantiables zConfigComponent.is_instantiablec Cs~t|}|d}t|ts|S|j|}|dur|St|tr8t d|d|d|dd|d}|d|S) z Resolve the target module name from current config content. The config content must have ``"_target_"`` key. rhNz+there are more than 1 component have name `z`: z, use the first one `rzP. if want to use others, please set its full module path in `_target_` directly.rQ) dictrdrUrSrOrjrYrVwarningswarn)r#r[targetrKr$r$r%resolve_module_names     z#ConfigComponent.resolve_module_namecsfddDS)zq Utility function used in `instantiate()` to resolve the arguments from current config content. cs i|] \}}|jvr||qSr$) non_arg_keys)r3kvr;r$r% s z0ConfigComponent.resolve_args..)rditemsr;r$r;r% resolve_argsszConfigComponent.resolve_argscCs2|dd}t|tr|dkSt|S)zg Utility function used in `instantiate()` to check whether to skip the instantiation. riFtrue)rdrUrSrOlowerstripr)r#Z _is_disabledr$r$r%r& s"zConfigComponent.is_disabledrr(cKsX||r |r dS|}|dtj}|}||t ||fi|S)a Instantiate component based on ``self.config`` content. The target component must be a `class` or a `function`, otherwise, return `None`. Args: kwargs: args to override / add the config args when instantiation. Nrg) rnrdr&rsrUr DEFAULTryupdater)r#rrJmoderr$r$r%rs  zConfigComponent.instantiate)rZNN) r[r r\rOrjrkr-r.rr])r[r rr)rr)rr rr() r!r)r*r+rtr1 staticmethodrnrsryr&r __classcell__r$r$rmr%rs0   rcs^eZdZdZeZeZddfd d ZdddZdd ddZ e d!ddZ e d!ddZ Z S)"ra Subclass of :py:class:`monai.bundle.ConfigItem`, the `ConfigItem` represents an executable expression (execute based on ``eval()``, or import the module to the `globals` if it's an import statement). See also: - https://docs.python.org/3/library/functions.html#eval. For example: .. code-block:: python import monai from monai.bundle import ConfigExpression config = "$monai.__version__" expression = ConfigExpression(config, id="test", globals={"monai": monai}) print(expression.evaluate()) Args: config: content of a config item. id: name of current config item, defaults to empty string. globals: additional global context to evaluate the string. rZNr[r r\rOglobals dict | Nonerr]cs,tj||d|dur||_dSi|_dS)Nr^)rlr1r)r#r[r\rrmr$r%r1EszConfigExpression.__init__ import_string Any | NonecCsttt|}t|tjtjfsdSt|jdkrdSt|jdkr.t d|d|jdj |jdj }}|durB|n|}t|tjr^t |j|d\|j|<}|j|St|tjrst |\|j|<}|j|SdS)zJparse single import statement such as "from monai.transforms import ResizeNrRz ignoring multiple import alias 'z'.r)rL)r astiter_child_nodesparserSImport ImportFromrWnamesrprqrLasnamerrKr)r#rnoderLr_r$r$r%_parse_import_stringIs     z%ConfigExpression._parse_import_stringlocalsstr | Any | Nonec Cs|}t|s dS||t|jd}|dur|S|js*|t|jdSt|j}|durM| D]\}}||vrHt d|d|||<q7t srzt |t|jd||WStyq}ztd||d}~wwt d|dddl} | |t|jd||dS)a Execute the current config content and return the result if it is expression, based on Python `eval()`. For more details: https://docs.python.org/3/library/functions.html#eval. Args: globals: besides ``self.globals``, other global symbols used in the expression at runtime. locals: besides ``globals``, may also have some local symbols used in the expression at runtime. Nzthe new global variable `z-` conflicts with `self.globals`, override it.zFailed to evaluate z pdb: value=zV See also Debugger commands documentation: https://docs.python.org/3/library/pdb.html r)rdr is_expressionrrWprefixrrorrxrprqreval Exception RuntimeErrorpdbrun) r#rrvalueoptional_moduleglobals_rurverr$r$r%evaluate\s6    zConfigExpression.evaluatedict | list | strrcCst|to ||jS)z Check whether the config is an executable expression string. Currently, a string starts with ``"$"`` character is interpreted as an expression. Args: config: input config content to check. )rSrOr8rclsr[r$r$r%rs zConfigExpression.is_expressionc CsL||sdSd|vr dStttt|t|jdtjtj fS)z Check whether the config is an import statement (a special case of expression). Args: config: input config content to check. FimportN) rrSr rrrrWrrrrr$r$r%is_import_statements ,z$ConfigExpression.is_import_statement)rZN)r[r r\rOrrrr])rrOrr)NN)rrrrrr)r[rrr)r!r)r*r+r rrr1rr classmethodrrrr$r$rmr%r's  &  r)" __future__rrrCr=rpabcrrcollections.abcrr importlibrpprintrtypingr monai.bundle.utilsr monai.utilsr r r rrrr__all__rrrrrr$r$r$r%s&     $C/