Arulkumar03/Wheat_HEAD_Detection_Counting_ComputerVision_Model
0
1# Copyright (c) Facebook, Inc. and its affiliates.2import importlib3import importlib.util4import logging5import numpy as np6import os7import random8import sys9from datetime import datetime10import torch11 12__all__ = ["seed_all_rng"]13 14 15TORCH_VERSION = tuple(int(x) for x in torch.__version__.split(".")[:2])16"""17PyTorch version as a tuple of 2 ints. Useful for comparison.18"""19 20 21DOC_BUILDING = os.getenv("_DOC_BUILDING", False) # set in docs/conf.py22"""23Whether we're building documentation.24"""25 26 27def seed_all_rng(seed=None):28 """29 Set the random seed for the RNG in torch, numpy and python.30 31 Args:32 seed (int): if None, will use a strong random seed.33 """34 if seed is None:35 seed = (36 os.getpid()37 + int(datetime.now().strftime("%S%f"))38 + int.from_bytes(os.urandom(2), "big")39 )40 logger = logging.getLogger(__name__)41 logger.info("Using a generated random seed {}".format(seed))42 np.random.seed(seed)43 torch.manual_seed(seed)44 random.seed(seed)45 os.environ["PYTHONHASHSEED"] = str(seed)46 47 48# from https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path49def _import_file(module_name, file_path, make_importable=False):50 spec = importlib.util.spec_from_file_location(module_name, file_path)51 module = importlib.util.module_from_spec(spec)52 spec.loader.exec_module(module)53 if make_importable:54 sys.modules[module_name] = module55 return module56 57 58def _configure_libraries():59 """60 Configurations for some libraries.61 """62 # An environment option to disable `import cv2` globally,63 # in case it leads to negative performance impact64 disable_cv2 = int(os.environ.get("DETECTRON2_DISABLE_CV2", False))65 if disable_cv2:66 sys.modules["cv2"] = None67 else:68 # Disable opencl in opencv since its interaction with cuda often has negative effects69 # This envvar is supported after OpenCV 3.4.070 os.environ["OPENCV_OPENCL_RUNTIME"] = "disabled"71 try:72 import cv273 74 if int(cv2.__version__.split(".")[0]) >= 3:75 cv2.ocl.setUseOpenCL(False)76 except ModuleNotFoundError:77 # Other types of ImportError, if happened, should not be ignored.78 # Because a failed opencv import could mess up address space79 # https://github.com/skvark/opencv-python/issues/38180 pass81 82 def get_version(module, digit=2):83 return tuple(map(int, module.__version__.split(".")[:digit]))84 85 # fmt: off86 assert get_version(torch) >= (1, 4), "Requires torch>=1.4"87 import fvcore88 assert get_version(fvcore, 3) >= (0, 1, 2), "Requires fvcore>=0.1.2"89 import yaml90 assert get_version(yaml) >= (5, 1), "Requires pyyaml>=5.1"91 # fmt: on92 93 94_ENV_SETUP_DONE = False95 96 97def setup_environment():98 """Perform environment setup work. The default setup is a no-op, but this99 function allows the user to specify a Python source file or a module in100 the $DETECTRON2_ENV_MODULE environment variable, that performs101 custom setup work that may be necessary to their computing environment.102 """103 global _ENV_SETUP_DONE104 if _ENV_SETUP_DONE:105 return106 _ENV_SETUP_DONE = True107 108 _configure_libraries()109 110 custom_module_path = os.environ.get("DETECTRON2_ENV_MODULE")111 112 if custom_module_path:113 setup_custom_environment(custom_module_path)114 else:115 # The default setup is a no-op116 pass117 118 119def setup_custom_environment(custom_module):120 """121 Load custom environment setup by importing a Python source file or a122 module, and run the setup function.123 """124 if custom_module.endswith(".py"):125 module = _import_file("detectron2.utils.env.custom_module", custom_module)126 else:127 module = importlib.import_module(custom_module)128 assert hasattr(module, "setup_environment") and callable(module.setup_environment), (129 "Custom environment module defined in {} does not have the "130 "required callable attribute 'setup_environment'."131 ).format(custom_module)132 module.setup_environment()133 134 135def fixup_module_metadata(module_name, namespace, keys=None):136 """137 Fix the __qualname__ of module members to be their exported api name, so138 when they are referenced in docs, sphinx can find them. Reference:139 https://github.com/python-trio/trio/blob/6754c74eacfad9cc5c92d5c24727a2f3b620624e/trio/_util.py#L216-L241140 """141 if not DOC_BUILDING:142 return143 seen_ids = set()144 145 def fix_one(qualname, name, obj):146 # avoid infinite recursion (relevant when using147 # typing.Generic, for example)148 if id(obj) in seen_ids:149 return150 seen_ids.add(id(obj))151 152 mod = getattr(obj, "__module__", None)153 if mod is not None and (mod.startswith(module_name) or mod.startswith("fvcore.")):154 obj.__module__ = module_name155 # Modules, unlike everything else in Python, put fully-qualitied156 # names into their __name__ attribute. We check for "." to avoid157 # rewriting these.158 if hasattr(obj, "__name__") and "." not in obj.__name__:159 obj.__name__ = name160 obj.__qualname__ = qualname161 if isinstance(obj, type):162 for attr_name, attr_value in obj.__dict__.items():163 fix_one(objname + "." + attr_name, attr_name, attr_value)164 165 if keys is None:166 keys = namespace.keys()167 for objname in keys:168 if not objname.startswith("_"):169 obj = namespace[objname]170 fix_one(objname, objname, obj)171 