CoolFace
Apppublic

codelion/Grounding_DINO_demo

sourceHugging Faceapache-2.0updated 2y agoView on Hugging Face
15likes
setup.py209 linesDownload Raw Back to root
1# coding=utf-82# Copyright 2022 The IDEA Authors. All rights reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8#     http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15# ------------------------------------------------------------------------------------------------16# Modified from17# https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/setup.py18# https://github.com/facebookresearch/detectron2/blob/main/setup.py19# https://github.com/open-mmlab/mmdetection/blob/master/setup.py20# https://github.com/Oneflow-Inc/libai/blob/main/setup.py21# ------------------------------------------------------------------------------------------------22 23import glob24import os25import subprocess26 27import torch28from setuptools import find_packages, setup29from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension30 31# groundingdino version info32version = "0.1.0"33package_name = "groundingdino"34cwd = os.path.dirname(os.path.abspath(__file__))35 36 37sha = "Unknown"38try:39    sha = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=cwd).decode("ascii").strip()40except Exception:41    pass42 43 44def write_version_file():45    version_path = os.path.join(cwd, "groundingdino", "version.py")46    with open(version_path, "w") as f:47        f.write(f"__version__ = '{version}'\n")48        # f.write(f"git_version = {repr(sha)}\n")49 50 51requirements = ["torch", "torchvision"]52 53torch_ver = [int(x) for x in torch.__version__.split(".")[:2]]54 55 56def get_extensions():57    this_dir = os.path.dirname(os.path.abspath(__file__))58    extensions_dir = os.path.join(this_dir, "groundingdino", "models", "GroundingDINO", "csrc")59 60    main_source = os.path.join(extensions_dir, "vision.cpp")61    sources = glob.glob(os.path.join(extensions_dir, "**", "*.cpp"))62    source_cuda = glob.glob(os.path.join(extensions_dir, "**", "*.cu")) + glob.glob(63        os.path.join(extensions_dir, "*.cu")64    )65 66    sources = [main_source] + sources67 68    extension = CppExtension69 70    extra_compile_args = {"cxx": []}71    define_macros = []72 73    if torch.cuda.is_available() and CUDA_HOME is not None:74        print("Compiling with CUDA")75        extension = CUDAExtension76        sources += source_cuda77        define_macros += [("WITH_CUDA", None)]78        extra_compile_args["nvcc"] = [79            "-DCUDA_HAS_FP16=1",80            "-D__CUDA_NO_HALF_OPERATORS__",81            "-D__CUDA_NO_HALF_CONVERSIONS__",82            "-D__CUDA_NO_HALF2_OPERATORS__",83        ]84    else:85        print("Compiling without CUDA")86        define_macros += [("WITH_HIP", None)]87        extra_compile_args["nvcc"] = []88        return None89 90    sources = [os.path.join(extensions_dir, s) for s in sources]91    include_dirs = [extensions_dir]92 93    ext_modules = [94        extension(95            "groundingdino._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 parse_requirements(fname="requirements.txt", with_version=True):107    """Parse the package dependencies listed in a requirements file but strips108    specific versioning information.109 110    Args:111        fname (str): path to requirements file112        with_version (bool, default=False): if True include version specs113 114    Returns:115        List[str]: list of requirements items116 117    CommandLine:118        python -c "import setup; print(setup.parse_requirements())"119    """120    import re121    import sys122    from os.path import exists123 124    require_fpath = fname125 126    def parse_line(line):127        """Parse information from a line in a requirements text file."""128        if line.startswith("-r "):129            # Allow specifying requirements in other files130            target = line.split(" ")[1]131            for info in parse_require_file(target):132                yield info133        else:134            info = {"line": line}135            if line.startswith("-e "):136                info["package"] = line.split("#egg=")[1]137            elif "@git+" in line:138                info["package"] = line139            else:140                # Remove versioning from the package141                pat = "(" + "|".join([">=", "==", ">"]) + ")"142                parts = re.split(pat, line, maxsplit=1)143                parts = [p.strip() for p in parts]144 145                info["package"] = parts[0]146                if len(parts) > 1:147                    op, rest = parts[1:]148                    if ";" in rest:149                        # Handle platform specific dependencies150                        # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies151                        version, platform_deps = map(str.strip, rest.split(";"))152                        info["platform_deps"] = platform_deps153                    else:154                        version = rest  # NOQA155                    info["version"] = (op, version)156            yield info157 158    def parse_require_file(fpath):159        with open(fpath, "r") as f:160            for line in f.readlines():161                line = line.strip()162                if line and not line.startswith("#"):163                    for info in parse_line(line):164                        yield info165 166    def gen_packages_items():167        if exists(require_fpath):168            for info in parse_require_file(require_fpath):169                parts = [info["package"]]170                if with_version and "version" in info:171                    parts.extend(info["version"])172                if not sys.version.startswith("3.4"):173                    # apparently package_deps are broken in 3.4174                    platform_deps = info.get("platform_deps")175                    if platform_deps is not None:176                        parts.append(";" + platform_deps)177                item = "".join(parts)178                yield item179 180    packages = list(gen_packages_items())181    return packages182 183 184if __name__ == "__main__":185    print(f"Building wheel {package_name}-{version}")186 187    with open("LICENSE", "r", encoding="utf-8") as f:188        license = f.read()189 190    write_version_file()191 192    setup(193        name="groundingdino",194        version="0.1.0",195        author="International Digital Economy Academy, Shilong Liu",196        url="https://github.com/IDEA-Research/GroundingDINO",197        description="open-set object detector",198        license=license,199        install_requires=parse_requirements("requirements.txt"),200        packages=find_packages(201            exclude=(202                "configs",203                "tests",204            )205        ),206        ext_modules=get_extensions(),207        cmdclass={"build_ext": torch.utils.cpp_extension.BuildExtension},208    )209