Team Ai
Apppublic

Arulkumar03/Wheat_HEAD_Detection_Counting_ComputerVision_Model

sourceHugging Facemitupdated 3y agoView on Hugging Face
0likes
setup.py216 linesDownload Raw Back to detectron2
1#!/usr/bin/env python2# Copyright (c) Facebook, Inc. and its affiliates.3 4import glob5import os6import shutil7from os import path8from setuptools import find_packages, setup9from typing import List10import torch11from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension12 13torch_ver = [int(x) for x in torch.__version__.split(".")[:2]]14assert torch_ver >= [1, 8], "Requires PyTorch >= 1.8"15 16 17def get_version():18    init_py_path = path.join(path.abspath(path.dirname(__file__)), "detectron2", "__init__.py")19    init_py = open(init_py_path, "r").readlines()20    version_line = [l.strip() for l in init_py if l.startswith("__version__")][0]21    version = version_line.split("=")[-1].strip().strip("'\"")22 23    # The following is used to build release packages.24    # Users should never use it.25    suffix = os.getenv("D2_VERSION_SUFFIX", "")26    version = version + suffix27    if os.getenv("BUILD_NIGHTLY", "0") == "1":28        from datetime import datetime29 30        date_str = datetime.today().strftime("%y%m%d")31        version = version + ".dev" + date_str32 33        new_init_py = [l for l in init_py if not l.startswith("__version__")]34        new_init_py.append('__version__ = "{}"\n'.format(version))35        with open(init_py_path, "w") as f:36            f.write("".join(new_init_py))37    return version38 39 40def get_extensions():41    this_dir = path.dirname(path.abspath(__file__))42    extensions_dir = path.join(this_dir, "detectron2", "layers", "csrc")43 44    main_source = path.join(extensions_dir, "vision.cpp")45    sources = glob.glob(path.join(extensions_dir, "**", "*.cpp"))46 47    from torch.utils.cpp_extension import ROCM_HOME48 49    is_rocm_pytorch = (50        True if ((torch.version.hip is not None) and (ROCM_HOME is not None)) else False51    )52    if is_rocm_pytorch:53        assert torch_ver >= [1, 8], "ROCM support requires PyTorch >= 1.8!"54 55    # common code between cuda and rocm platforms, for hipify version [1,0,0] and later.56    source_cuda = glob.glob(path.join(extensions_dir, "**", "*.cu")) + glob.glob(57        path.join(extensions_dir, "*.cu")58    )59    sources = [main_source] + sources60 61    extension = CppExtension62 63    extra_compile_args = {"cxx": []}64    define_macros = []65 66    if (torch.cuda.is_available() and ((CUDA_HOME is not None) or is_rocm_pytorch)) or os.getenv(67        "FORCE_CUDA", "0"68    ) == "1":69        extension = CUDAExtension70        sources += source_cuda71 72        if not is_rocm_pytorch:73            define_macros += [("WITH_CUDA", None)]74            extra_compile_args["nvcc"] = [75                "-O3",76                "-DCUDA_HAS_FP16=1",77                "-D__CUDA_NO_HALF_OPERATORS__",78                "-D__CUDA_NO_HALF_CONVERSIONS__",79                "-D__CUDA_NO_HALF2_OPERATORS__",80            ]81        else:82            define_macros += [("WITH_HIP", None)]83            extra_compile_args["nvcc"] = []84 85        if torch_ver < [1, 7]:86            # supported by https://github.com/pytorch/pytorch/pull/4393187            CC = os.environ.get("CC", None)88            if CC is not None:89                extra_compile_args["nvcc"].append("-ccbin={}".format(CC))90 91    include_dirs = [extensions_dir]92 93    ext_modules = [94        extension(95            "detectron2._C",96            sources,97            include_dirs=include_dirs,98            define_macros=define_macros,99            extra_compile_args=extra_compile_args,100        )101    ]102 103    return ext_modules104 105 106def get_model_zoo_configs() -> List[str]:107    """108    Return a list of configs to include in package for model zoo. Copy over these configs inside109    detectron2/model_zoo.110    """111 112    # Use absolute paths while symlinking.113    source_configs_dir = path.join(path.dirname(path.realpath(__file__)), "configs")114    destination = path.join(115        path.dirname(path.realpath(__file__)), "detectron2", "model_zoo", "configs"116    )117    # Symlink the config directory inside package to have a cleaner pip install.118 119    # Remove stale symlink/directory from a previous build.120    if path.exists(source_configs_dir):121        if path.islink(destination):122            os.unlink(destination)123        elif path.isdir(destination):124            shutil.rmtree(destination)125 126    if not path.exists(destination):127        try:128            os.symlink(source_configs_dir, destination)129        except OSError:130            # Fall back to copying if symlink fails: ex. on Windows.131            shutil.copytree(source_configs_dir, destination)132 133    config_paths = glob.glob("configs/**/*.yaml", recursive=True) + glob.glob(134        "configs/**/*.py", recursive=True135    )136    return config_paths137 138 139# For projects that are relative small and provide features that are very close140# to detectron2's core functionalities, we install them under detectron2.projects141PROJECTS = {142    "detectron2.projects.point_rend": "projects/PointRend/point_rend",143    "detectron2.projects.deeplab": "projects/DeepLab/deeplab",144    "detectron2.projects.panoptic_deeplab": "projects/Panoptic-DeepLab/panoptic_deeplab",145}146 147setup(148    name="detectron2",149    version=get_version(),150    author="FAIR",151    url="https://github.com/facebookresearch/detectron2",152    description="Detectron2 is FAIR's next-generation research "153    "platform for object detection and segmentation.",154    packages=find_packages(exclude=("configs", "tests*")) + list(PROJECTS.keys()),155    package_dir=PROJECTS,156    package_data={"detectron2.model_zoo": get_model_zoo_configs()},157    python_requires=">=3.7",158    install_requires=[159        # These dependencies are not pure-python.160        # In general, avoid adding dependencies that are not pure-python because they are not161        # guaranteed to be installable by `pip install` on all platforms.162        "Pillow>=7.1",  # or use pillow-simd for better performance163        "matplotlib",  # TODO move it to optional after we add opencv visualization164        "pycocotools>=2.0.2",  # corresponds to https://github.com/ppwwyyxx/cocoapi165        # Do not add opencv here. Just like pytorch, user should install166        # opencv themselves, preferrably by OS's package manager, or by167        # choosing the proper pypi package name at https://github.com/skvark/opencv-python168        # Also, avoid adding dependencies that transitively depend on pytorch or opencv.169        # ------------------------------------------------------------170        # The following are pure-python dependencies that should be easily installable.171        # But still be careful when adding more: fewer people are able to use the software172        # with every new dependency added.173        "termcolor>=1.1",174        "yacs>=0.1.8",175        "tabulate",176        "cloudpickle",177        "tqdm>4.29.0",178        "tensorboard",179        # Lock version of fvcore/iopath because they may have breaking changes180        # NOTE: when updating fvcore/iopath version, make sure fvcore depends181        # on compatible version of iopath.182        "fvcore>=0.1.5,<0.1.6",  # required like this to make it pip installable183        "iopath>=0.1.7,<0.1.10",184        "dataclasses; python_version<'3.7'",185        "omegaconf>=2.1",186        "hydra-core>=1.1",187        "black",188        "packaging",189        # NOTE: When adding new dependencies, if it is required at import time (in addition190        # to runtime), it probably needs to appear in docs/requirements.txt, or as a mock191        # in docs/conf.py192    ],193    extras_require={194        # optional dependencies, required by some features195        "all": [196            "fairscale",197            "timm",  # Used by a few ViT models.198            "scipy>1.5.1",199            "shapely",200            "pygments>=2.2",201            "psutil",202            "panopticapi @ https://github.com/cocodataset/panopticapi/archive/master.zip",203        ],204        # dev dependencies. Install them by `pip install 'detectron2[dev]'`205        "dev": [206            "flake8==3.8.1",207            "isort==4.3.21",208            "flake8-bugbear",209            "flake8-comprehensions",210            "black==22.3.0",211        ],212    },213    ext_modules=get_extensions(),214    cmdclass={"build_ext": torch.utils.cpp_extension.BuildExtension},215)216