打包个人项目成python算法包

*免责声明:
1\此方法仅提供参考
2\搬了其他博主的操作方法,以贴上路径.
3*

场景一: 使用conda pack进行打包个人项目

场景二:

场景一: 使用conda pack进行打包个人项目

1.1 导出包列表

请添加图片描述

activate  jiance

pip  list   --format=freeze >requirements.txt 

请添加图片描述

1.2 打包 yolo-smoke项目,支持pip install 的安装形式

  • requirements.txt 的同级目录下创建 setup.py , 根据需求修改对应的值,内容大致如下:
    请添加图片描述
#!/usr/bin/env python
# Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
import platform
import shutil
import sys
import warnings
from setuptools import find_packages, setup

import torch
from torch.utils.cpp_extension import (BuildExtension, CppExtension,
                                       CUDAExtension)


def readme():
    with open('README.md', encoding='utf-8') as f:
        content = f.read()
    return content


version_file = 'yolo-smoke/version.py'    # 可以参考 mmdetetction工程的下的version文件

# 获取代码的版本号
def get_version():
    with open(version_file, 'r') as f:
        exec(compile(f.read(), version_file, 'exec'))
    return locals()['__version__']


def make_cuda_ext(name, module, sources, sources_cuda=[]):

    define_macros = []
    extra_compile_args = {'cxx': []}

    if torch.cuda.is_available() or os.getenv('FORCE_CUDA', '0') == '1':
        define_macros += [('WITH_CUDA', None)]
        extension = CUDAExtension
        extra_compile_args['nvcc'] = [
            '-D__CUDA_NO_HALF_OPERATORS__',
            '-D__CUDA_NO_HALF_CONVERSIONS__',
            '-D__CUDA_NO_HALF2_OPERATORS__',
        ]
        sources += sources_cuda
    else:
        print(f'Compiling {name} without CUDA')
        extension = CppExtension

    return extension(
        name=f'{module}.{name}',
        sources=[os.path.join(*module.split('.'), p) for p in sources],
        define_macros=define_macros,
        extra_compile_args=extra_compile_args)


def parse_requirements(fname='requirements.txt', with_version=True):
    """Parse the package dependencies listed in a requirements file but strips
    specific versioning information.
    Args:
        fname (str): path to requirements file
        with_version (bool, default=False): if True include version specs
    Returns:
        List[str]: list of requirements items
    CommandLine:
        python -c "import setup; print(setup.parse_requirements())"
    """
    import re
    import sys
    from os.path import exists
    require_fpath = fname

    def parse_line(line):
        """Parse information from a line in a requirements text file."""
        if line.startswith('-r '):
            # Allow specifying requirements in other files
            target = line.split(' ')[1]
            for info in parse_require_file(target):
                yield info
        else:
            info = {'line': line}
            if line.startswith('-e '):
                info['package'] = line.split('#egg=')[1]
            elif '@git+' in line:
                info['package'] = line
            else:
                # Remove versioning from the package
                pat = '(' + '|'.join(['>=', '==', '>']) + ')'
                parts = re.split(pat, line, maxsplit=1)
                parts = [p.strip() for p in parts]

                info['package'] = parts[0]
                if len(parts) > 1:
                    op, rest = parts[1:]
                    if ';' in rest:
                        # Handle platform specific dependencies
                        # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
                        version, platform_deps = map(str.strip,
                                                     rest.split(';'))
                        info['platform_deps'] = platform_deps
                    else:
                        version = rest  # NOQA
                    info['version'] = (op, version)
            yield info

    def parse_require_file(fpath):
        with open(fpath, 'r') as f:
            for line in f.readlines():
                line = line.strip()
                if line and not line.startswith('#'):
                    for info in parse_line(line):
                        yield info

    def gen_packages_items():
        if exists(require_fpath):
            for info in parse_require_file(require_fpath):
                parts = [info['package']]
                if with_version and 'version' in info:
                    parts.extend(info['version'])
                if not sys.version.startswith('3.4'):
                    # apparently package_deps are broken in 3.4
                    platform_deps = info.get('platform_deps')
                    if platform_deps is not None:
                        parts.append(';' + platform_deps)
                item = ''.join(parts)
                yield item

    packages = list(gen_packages_items())
    return packages


def add_mim_extension():
    """Add extra files that are required to support MIM into the package.
    These files will be added by creating a symlink to the originals if the
    package is installed in `editable` mode (e.g. pip install -e .), or by
    copying from the originals otherwise.
    """

    # parse installment mode
    if 'develop' in sys.argv:
        # installed by `pip install -e .`
        if platform.system() == 'Windows':
            # set `copy` mode here since symlink fails on Windows.
            mode = 'copy'
        else:
            mode = 'symlink'
    elif 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
        # installed by `pip install .`
        # or create source distribution by `python setup.py sdist`
        mode = 'copy'
    else:
        return
        
    # filenames = ['tools', 'configs', 'demo', 'model-index.yml']
    filenames = ['tests', 'model-index.yml']
    repo_path = osp.dirname(__file__)
    mim_path = osp.join(repo_path, 'mmdet', '.mim')
    os.makedirs(mim_path, exist_ok=True)

    for filename in filenames:
        if osp.exists(filename):
            src_path = osp.join(repo_path, filename)
            tar_path = osp.join(mim_path, filename)

            if osp.isfile(tar_path) or osp.islink(tar_path):
                os.remove(tar_path)
            elif osp.isdir(tar_path):
                shutil.rmtree(tar_path)

            if mode == 'symlink':
                src_relpath = osp.relpath(src_path, osp.dirname(tar_path))
                os.symlink(src_relpath, tar_path)
            elif mode == 'copy':
                if osp.isfile(src_path):
                    shutil.copyfile(src_path, tar_path)
                elif osp.isdir(src_path):
                    shutil.copytree(src_path, tar_path)
                else:
                    warnings.warn(f'Cannot copy file {src_path}.')
            else:
                raise ValueError(f'Invalid mode {mode}')


if __name__ == '__main__':
    add_mim_extension()
    setup(
        name='yolo-smoke',   # 算法打包的名称
        version=get_version(), # 获取版本号
        description='OpenMMLab Detection Toolbox and Benchmark', # 算法的描述
        long_description=None,  # long_description=readme(),
        long_description_content_type='text/markdown',
        author='yourname',
        author_email='yourname@gmail.com',
        keywords='computer vision, object detection, smoke , yolo',
        url='none' , # 项目地址 'https://github.com/open-mmlab/mmdetection',
        packages=find_packages(exclude=('docs', 'tests', 'demo')),  # 打包需要略过的文件夹名称
        
         ![请添加图片描述](https://img-blog.csdnimg.cn/7a63c742e2a8437d9d6ce9dcc09bab3a.png)

                                      
                                        
        include_package_data=True,
        classifiers=[
            'Development Status :: 5 - Production/Stable',
            'License :: OSI Approved :: Apache Software License',
            'Operating System :: OS Independent',
            'Programming Language :: Python :: 3',
            'Programming Language :: Python :: 3.7',
            'Programming Language :: Python :: 3.8',
            'Programming Language :: Python :: 3.9',
        ],
        license='Apache License 2.0',
        install_requires=parse_requirements('requirements/runtime.txt'),
        
        # extras_require={
        #    'all': parse_requirements('requirements.txt'),
        #    'tests': parse_requirements('requirements/tests.txt'),
        #    'build': parse_requirements('requirements/build.txt'),
        #    'optional': parse_requirements('requirements/optional.txt'),
        #    'mim': parse_requirements('requirements/mminstall.txt'),
        #  },
        ext_modules=[],
        cmdclass={'build_ext': BuildExtension},
        zip_safe=False)

请添加图片描述
在这里插入图片描述

  • 如果有的文件夹想要参与打包却没有 init.py, 手动的创建该文件。

  • 运行 setup.py 文件

python  setup.py  bdist_wheel

请添加图片描述

  • yolo-smoke 打包测试,在 jiance 的环境下执行以下语句
python

import  yolo-smoke

1.3 使用conda pack 打包整个 jiance 环境

  • 打开jiance环境的物理位置,如 D:anaconda/envs/ jiance, 切换到上级目录,也就是D:anaconda/envscmd 打开,安装 conda-pack
 D:\Anaconda\envs>  pip  install  conda-pack
  • 执行打包语句:
conda  pack  -n  jiance  -o  yolo_smoke_algorithm.tar.gz  --ignore-editable-packages
  • 最中会在 anaconda/envs 下生成 yolo_smoke_algorithm.tar.gz 的压缩包。

1.4 项目移植到其他机器上(不想要安装conda/python环境)

  • 用 cmd 切换到d盘,创建 yolo_smoke_algorithm 文件夹,将 yolo_smoke_algorithm.tar.gz 复制到 yolo_smoke_algorithm 文件夹下 ,使用命令行的方式解压。
tar -zxvf  yolo_smoke_algorithm.tar.gz

方式一:pycharm中使用

  • 在pycharm的 File/Settings/project:xxx/Python Interpreter 选择 Add Interpreter,添加到 System Interpreter里面 选择 D:\yolo-smoke_algorithm\python.exe

方式二:anaconda管理

  • 命令行的方式解压 yolo_smoke_algorithm.tar.gz 包到 yolo_smoke_algorithm 文件夹下,将该 yolo_smoke_algorithm 文件夹拷贝到 anaconda/envs 下,作为anaconda的一个环境正常的 activate yolo_smoke_algorithm 激活环境。

方式三:命令行指定解释器的方式

D:\yolo_smoke_algorithm\python.exe  py文件路径

D:\yolo_smoke_algorithm\python.exe  D:\aa\1.py

方式四:

  • yolo_smoke_algorithm 文件夹下打开cmd窗口,激活环境 .\Scripts\activate.bat
# 激活环境
D:\yolo_smoke_algorithm> .\Scripts\activate.bat

# 退出环境
(yolo_smoke_algorith)D:\yolo_smoke_algorithm> .\Scripts\deactivate.bat

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/109850.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Transformers实战(二)快速入门文本相似度、检索式对话机器人

Transformers实战(二)快速入门文本相似度、检索式对话机器人 1、文本相似度 1.1 文本相似度简介 文本匹配是一个较为宽泛的概念,基本上只要涉及到两段文本之间关系的,都可以被看作是一种文本匹配的任务, 只是在具体…

【JavaEE】HTTP协议

HTTP协议 HTTP是什么?HTTP 协议格式HTTP 请求格式HTTP响应格式协议格式总结 HTTP 请求 (Request)认识 URLURL 基本格式 关于 URL encode认识 "方法" (method)1. GET 方法2. POST 方法 认识请求 "报头" (header) HTTP 响应详解认识 "状态码" (st…

Elasticsearch:使用 Open AI 和 Langchain 的 RAG - Retrieval Augmented Generation (二)

这是继上一篇文章 “Elasticsearch:使用 Open AI 和 Langchain 的 RAG - Retrieval Augmented Generation (一)” 的续篇。在这篇文章中,我主要来讲述 ElasticVectorSearch 的使用。 我们的设置和之前的那篇文章是一样的&#xff…

idea中Run/Debug Python项目报错 Argument for @NotNull parameter ‘module‘ of ...

idea中Run/Debug Python项目报错 Argument for NotNull parameter module of ... idea中运行Python项目main.py时报错: Error running main: Argument for NotNull parameter module of com/intellij/openapi/roots/ModuleRootManager.getInstance must not be nu…

Flash Attention 的优点以及Softmax 归一化系数解释

文章:FLASHATTENTION: Fast and Memory-Efficient Exact Attention with IO-Awareness 原始Attention 计算使用gpu存储标准流程 涉及两个gpu存储器: 1)SRAM(static Random Access Memory):静态随机存取存储器 2&…

管理类联考——数学——汇总篇——知识点突破——代数——整式分式——记忆

文章目录 考点记忆/考点汇总——按大纲 整体目录大纲法记忆宫殿法绘图记忆法 局部数字编码法归类记忆法重点记忆法歌决记忆法谐音记忆法理解记忆法比较记忆法转图像记忆法可视化法 本篇思路:根据各方的资料,比如名师的资料,按大纲或者其他方式…

什么是全排列?(算法实现)

全排列是什么? 全排列是指将一组元素按照一定顺序进行排列的所有可能结果。以一组数字为例,比如[1, 2, 3]的全排列结果为:[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]。 全排列有许多不同的计算方法,其中…

【电路笔记】-交流电感和感抗

交流电感和感抗 文章目录 交流电感和感抗1、概述1.1 电感1.2 电感器 2、频率特性2.1 电抗(Reactance)2.2 相移2.3 感应现象 3、RL滤波器4、总结 在之前有 交流电阻的文章中,我们已经看到电阻器在正常频率下的直流或交流状态下的行为是相同的。 然而,其他…

CN考研真题知识点二轮归纳(1)

本轮开始更新真题中涉及过的知识点,总共不到20年的真题,大致会出5-10期,尽可能详细的讲解并罗列不重复的知识点~ 目录 1.三类IP地址网络号的取值范围 2.Socket的内容 3.邮件系统中向服务器获取邮件所用到的协议 4.RIP 5.DNS 6.CSMA/CD…

Linux云服务器限制ip进行ssh远程连接

对Linux云服务器限制IP进行SSH远程连接的原因主要有以下几点: 增加安全性:SSH是一种加密的网络传输协议,可以保护数据的机密性和完整性。通过限制SSH连接的IP地址,可以防止未经授权的访问和数据泄露。只有拥有访问权限的IP地址才…

Vue 路由指南:畅游单页应用的地图(Vue Router 和 <router-view>)

🤍 前端开发工程师(主业)、技术博主(副业)、已过CET6 🍨 阿珊和她的猫_CSDN个人主页 🕠 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 🍚 蓝桥云课签约作者、已在蓝桥云…

【智能座舱系列】- 深度解密小米Hyper OS,华为HarmonyOS区别

上一篇文章《小米的澎湃OS到底牛不牛?与鸿蒙系统之间差距有多大》,从多个方面比较了小米Hyper OS 与 华为HarmonyOS的区别,本篇文章继续从架构层面深度解读两者本质的区别。 小米澎湃OS是“以人为中心,打造人车家全生态操作系统”,该系统基于深度进化的Android以及自研的V…

【JAVA学习笔记】52 - 本章作业

项目代码 https://github.com/yinhai1114/Java_Learning_Code/tree/main/IDEA_Chapter13/src/com/yinhai/wrapper_/homework_ 1.字符反转 注意String是final的不能改变需要toCharArray改成char数组 返回String需要将char改成valueOf改为String public class HomeWork01 {publ…

RabbitMQ学习01

四大核心概念 生产者 产生数据发送消息的程序是生产者 交换机 交换机是 RabbitMQ 非常重要的一个部件,一方面它接收来自生产者的消息,另一方面它将消息推送到队列中。交换机必须确切知道如何处理它接收到的消息,是将这些消息推送到特定队…

ZooKeeper中节点的操作命令(查看、创建、删除节点)

天行健,君子以自强不息;地势坤,君子以厚德载物。 每个人都有惰性,但不断学习是好好生活的根本,共勉! 文章均为学习整理笔记,分享记录为主,如有错误请指正,共同学习进步。…

分治法求解棋盘覆盖问题

分治法求解棋盘覆盖问题 如何应用分治法求解棋盘覆盖问题呢?分治的技巧在于如何划分棋盘,使划分后的子棋盘的大小相同,并且每个子棋盘均包含一个特殊方格,从而将原问题分解为规模较小的棋盘覆盖问题。 基本思路 棋盘覆盖问题是…

【音视频|wav】wav音频文件格式详解

😁博客主页😁:🚀https://blog.csdn.net/wkd_007🚀 🤑博客内容🤑:🍭嵌入式开发、Linux、C语言、C、数据结构、音视频🍭 🤣本文内容🤣&a…

BLIP2中Q-former详解

简介 Querying Transformer,在冻结的视觉模型和大语言模型间进行视觉-语言对齐。 为了使Q-Former的学习达到两个目标: 学习到和文本最相关的视觉表示。 这种表示能够为大语言模型所解释。 需要在Q-Former结构设计和训练策略上下功夫。具体来说&…

零资源的大语言模型幻觉预防

零资源的大语言模型幻觉预防 摘要1 引言2 相关工作2.1 幻觉检测和纠正方法2.2 幻觉检测数据集 3 方法论3.1 概念提取3.2 概念猜测3.2.1 概念解释3.2.2 概念推理 3.3 聚合3.3.1 概念频率分数3.3.2 加权聚合 4 实验5 总结 摘要 大语言模型(LLMs)在各个领域…

Redis(windows+Linux)安装及入门

一、概述 Redis是什么? Redis(Remote Dictionary Server),即远程字典服务 Redis(Remote Dictionary Server ),即远程字典服务,是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数…
最新文章