U Ph?@sddlmZddlZddlZddlZddlZddlmZmZddl m Z m Z ddl m Z ddlmZddlmZddlmZdd lmZmZmZmZmZmZmZd d d d dgZGdddeZGdd d ZGdd d ZGdd d eeZ Gdd d eZ!dS)) annotationsN)ABCabstractmethod)MappingSequence) import_module)pformat)Any)EXPR_KEY) CompInitMode ensure_tuplefirst instantiateoptional_import run_debugrun_evalComponentLocator ConfigItemConfigExpressionConfigComponent Instantiablec@s<eZdZdZeddddddZedddddd Zd S) rz0 Base class for an instantiable object. r bool)argskwargsreturncOstd|jjddS)z^ Return a boolean flag to indicate whether the object should be instantiated. subclass  must implement this method.NNotImplementedError __class____name__selfrrr#M/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/bundle/config_item.py is_disabled#szInstantiable.is_disabledobjectcOstd|jjddS)zK Instantiate the target component and return the instance. rrNrr!r#r#r$r*szInstantiable.instantiateN)r __module__ __qualname____doc__rr%rr#r#r#r$rs c@sReZdZdZdZdddddZdd d d Zd d dddZdddddZdS)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. monaiNSequence[str] | str | NoneexcludescCs |dkr gnt||_d|_dSN)r r-_components_table)r"r-r#r#r$__init__>szComponentLocator.__init__z list[str]rcsfddtjDS)za Find all the modules start with MOD_START and don't contain any of `excludes`. cs4g|],jrtfddjDrqS)c3s|]}|kVqdSr.r#).0smr#r$ GszAComponentLocator._find_module_names...) startswith MOD_STARTallr-)r2r"r4r$ Gs z7ComponentLocator._find_module_names..)sysmodulesr:r#r:r$_find_module_namesBsz#ComponentLocator._find_module_nameszSequence[str] | strzdict[str, list])modnamesrc Csi}t|D]v}z\t|}t|D]D\}}t|s@t|r$|j|kr$||krZg||<|||q$Wq tk rYq Xq |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_functionsstrzlist[str] | str | None)rIrcCsbt|tstd|d|jdkr4|||_|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) isinstancerL ValueErrorr/rKr>getlistlen)r"rImodsr#r#r$get_component_module_name`s   z*ComponentLocator.get_component_module_name)N) r r'r(r)r8r0r>rKrUr#r#r#r$r2s  c@sXeZdZdZdddddddZdd d d Zddd d dZddZdd ddZdS)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. r rLNone)configidrcCs||_||_dSr.rXrY)r"rXrYr#r#r$r0szConfigItem.__init__r1cCs|jS)zj Get the ID name of current config item, useful to identify config items during parsing. )rYr:r#r#r$get_idszConfigItem.get_idrXrcCs ||_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`. NrX)r"rXr#r#r$ update_configs zConfigItem.update_configcCs|jS)zA Get the config content of current config item. r]r:r#r#r$ get_configszConfigItem.get_configcCst|jdt|jS)Nz: )typer rrXr:r#r#r$__repr__szConfigItem.__repr__N)rV) r r'r(r)r0r[r^r_rar#r#r#r$rus   cseZdZdZdddddhZd d d d d d dfdd Zed ddddZddZddZ ddddZ d ddddZ 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`. _target_ _disabled_Z _requires_Z_desc__mode_rVNr rLzComponentLocator | Noner+rW)rXrYlocatorr-rcs,tj||d|dkr"t|dn||_dS)NrZr,)superr0rre)r"rXrYrer-rr#r$r0szConfigComponent.__init__rr\cCst|tod|kS)z Check whether this config represents a `class` or `function` that is to be instantiated. Args: config: input config content to check. rb)rOrr]r#r#r$is_instantiables zConfigComponent.is_instantiablec Cs~t|}|d}t|ts$|S|j|}|dkr<|St|trpt d|d|d|dd|d}|d|S) z Resolve the target module name from current config content. The config content must have ``"_target_"`` key. rbNz+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.rM) dictr_rQrOrLrerUrRwarningswarn)r"rXtargetrHr#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|]\}}|jkr||qSr#) non_arg_keys)r2kvr:r#r$ s z0ConfigComponent.resolve_args..)r_itemsr:r#r:r$ resolve_argsszConfigComponent.resolve_argsr1cCs2|dd}t|tr*|dkSt|S)zg Utility function used in `instantiate()` to check whether to skip the instantiation. rcFtrue)r_rQrOrLlowerstripr)r"Z _is_disabledr#r#r$r% szConfigComponent.is_disabledr&)rrcKsT||r|rdS|}|dtj}|}||t ||f|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. Nrd) rhr_r%rmrQr DEFAULTrsupdater)r"rrGmoderr#r#r$rs  zConfigComponent.instantiate)rVNN) r r'r(r)rnr0 staticmethodrhrmrsr%r __classcell__r#r#rgr$rs0  cseZdZdZeZeZddddddfd d Zdd d d dZdddddddZ e dddddZ e dddddZ 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. rVNr rLz dict | NonerW)rXrYglobalsrcs&tj||d|dk r|ni|_dS)NrZ)rfr0r|)r"rXrYr|rgr#r$r0EszConfigExpression.__init__z Any | None) import_stringrcCsttt|}t|tjtjfs*dSt|jdkr s$     $C/