├── .Dockerfile ├── .dockerignore ├── .editorconfig ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── feature_request.md │ └── tutorial-or-example-request.md └── workflows │ ├── black.yml │ ├── ci-testing.yml │ ├── install-pkg.yml │ ├── mk-docs-build.yml │ ├── mk-docs-deploy.yml │ └── pypi-release.yml ├── .gitignore ├── .gitmodules ├── .nojekyll ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── MANIFEST.in ├── README.md ├── docs ├── mkdocs.yml ├── requirements.txt └── templates │ ├── contributing.md │ └── index.md ├── outputs ├── helmet.jpg └── mask.jpg ├── pytorch_fasterrcnn ├── __init__.py ├── config.py ├── crash_test.py ├── dataset.py ├── engine.py ├── inference.py ├── model.py ├── train.py └── utils.py ├── requirements-dev.txt ├── requirements.txt ├── settings.ini ├── setup.py ├── setup.sh └── tests ├── README.md └── test_hello.py /.Dockerfile: -------------------------------------------------------------------------------- 1 | # Choose the base image from to take. 2 | # Using slim images is best practice 3 | FROM ubuntu:latest 4 | 5 | ARG PYTHON_VERSION=3.6 6 | 7 | # This is one of the best practice. 8 | # This technique is known as “cache busting”. 9 | RUN apt-get update && apt-get install -y --no-install-recommends \ 10 | build-essential \ 11 | cmake \ 12 | git \ 13 | curl 14 | 15 | # add non-root user 16 | RUN useradd --create-home --shell /bin/bash containeruser 17 | USER containeruser 18 | WORKDIR /home/containeruser 19 | 20 | # install miniconda and python 21 | RUN curl -o ~/miniconda.sh https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh && \ 22 | chmod +x ~/miniconda.sh && \ 23 | ~/miniconda.sh -b -p /home/containeruser/conda && \ 24 | rm ~/miniconda.sh && \ 25 | /home/containeruser/conda/bin/conda clean -ya && \ 26 | /home/containeruser/conda/bin/conda install -y python=$PYTHON_VERSION 27 | 28 | # add conda to path 29 | ENV PATH /home/containeruser/conda/bin:$PATH 30 | 31 | # Now install this repo 32 | # We need only the master branch not all branches 33 | 34 | COPY requirements.txt requirements.txt 35 | COPY requirements-extra.txt requirements-extra.txt 36 | RUN pip install -r requirements.txt && \ 37 | pip install -r requirements-extra.txt && 38 | 39 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | # git 2 | .git 3 | .gitattributes 4 | .gitignore 5 | *.github 6 | 7 | # python 8 | **/__pycache__ 9 | 10 | # Common 11 | *.md 12 | docker-compose.yml 13 | Dockerfile 14 | 15 | # JetBrains 16 | .idea 17 | 18 | # Configutration files 19 | .editorconfig 20 | 21 | # Editor files 22 | *.vscode 23 | *.vs 24 | 25 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Inspired from https://github.com/seanfisk/python-project-template/blob/master/.editorconfig 2 | # More stuff taken from https://github.com/django/django/blob/master/.editorconfig 3 | # -*- mode: conf-unix; -*- 4 | 5 | # EditorConfig is awesome: http://EditorConfig.org 6 | 7 | # top-most EditorConfig file 8 | root = true 9 | 10 | # defaults 11 | [*] 12 | end_of_line = lf 13 | trim_trailing_whitespace = true 14 | insert_final_newline = true 15 | charset = utf-8 16 | 17 | # Use 2 spaces for the HTML files 18 | [*.html] 19 | indent_size = 2 20 | 21 | # The JSON files contain newlines inconsistently 22 | [*.json] 23 | indent_size = 2 24 | insert_final_newline = ignore 25 | 26 | # Minified JavaScript files shouldn't be changed 27 | [**.min.js] 28 | indent_style = ignore 29 | insert_final_newline = ignore 30 | 31 | # Makefiles always use tabs for indentation 32 | [Makefile] 33 | indent_style = tab 34 | 35 | # Batch files use tabs for indentation 36 | [*.bat] 37 | indent_style = tab 38 | 39 | # 4 space indentation 40 | [*.{ini,py,py.tpl,rst}] 41 | indent_style = space 42 | indent_size = 4 43 | 44 | # 4-width tabbed indentation 45 | [*.{sh,bat.tpl,Makefile.tpl}] 46 | indent_style = tab 47 | indent_size = 4 48 | 49 | # 2-width space indentation for GitHub / Travis actions and yml files. 50 | [*.{yml}] 51 | indent_style = space 52 | indent_size = 2 53 | 54 | # Markdown might need whitespaces 55 | [*.md] 56 | trim_trailing_whitespace = false 57 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Basic .gitattributes for a python repo. 2 | # Taken from https://github.com/alexkaratarakis/gitattributes 3 | 4 | # Source files 5 | # ============ 6 | # *.pxd text diff=python 7 | # *.py text diff=python 8 | # *.py3 text diff=python 9 | # *.pyw text diff=python 10 | # *.pyx text diff=python 11 | # *.pyz text diff=pythoncoun 12 | # *.pyi text diff=python 13 | 14 | # Binary files 15 | # ============ 16 | # *.db binary 17 | # *.p binary 18 | # *.pkl binary 19 | # *.pickle binary 20 | # *.pyc binary 21 | # *.pyd binary 22 | # *.pyo binary 23 | 24 | # Jupyter notebook 25 | 26 | # For text count 27 | # *.ipynb text 28 | 29 | # To ignore it use below 30 | *.ipynb linguist-documentation 31 | 32 | # Note: .db, .p, and .pkl files are associated 33 | # with the python modules ``pickle``, ``dbm.*``, 34 | # ``shelve``, ``marshal``, ``anydbm``, & ``bsddb`` 35 | # (among others). 36 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## 🐛 Bug 11 | **Describe the bug** 12 | A clear and concise description of what the bug is. 13 | 14 | **To Reproduce** 15 | Steps to reproduce the behavior: 16 | 1. Go to '...' 17 | 2. Click on '....' 18 | 3. Scroll down to '....' 19 | 4. See error 20 | 21 | **Expected behavior** 22 | A clear and concise description of what you expected to happen. 23 | 24 | **Screenshots** 25 | If applicable, add screenshots to help explain your problem. 26 | 27 | **Desktop (please complete the following information):** 28 | - OS: [e.g. ubuntu 18.04] 29 | 30 | **Additional context** 31 | Add any other context about the problem here. 32 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## 🚀 Feature 11 | **Is your feature request related to a problem? Please describe.** 12 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 13 | 14 | **Describe the solution you'd like** 15 | A clear and concise description of what you want to happen. 16 | 17 | **Describe alternatives you've considered** 18 | A clear and concise description of any alternative solutions or features you've considered. 19 | 20 | **Additional context** 21 | Add any other context or screenshots about the feature request here. 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/tutorial-or-example-request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Tutorial or Example request 3 | about: 'Suggest a new usage example ' 4 | title: '' 5 | labels: documentation, example request, good first issue, help wanted 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## 📓 New 11 | 12 | **Is this a request for a tutorial or for an example?** 13 | Tutorials are in `.ipynb` format, explaining each step of the process, really detailed, not production like. 14 | 15 | Examples are be in the `.py` format, more production oriented. Ready to be run with arguments from the command line and easy to integrate with wandb sweeps and alike. 16 | 17 | -------------------------------------------------------------------------------- /.github/workflows/black.yml: -------------------------------------------------------------------------------- 1 | name: Check Formatting 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it 15 | - uses: actions/checkout@v2 16 | 17 | # Runs black formatting 18 | - name: Black Code Formatter 19 | uses: lgeiger/black-action@v1.0.1 20 | with: 21 | args: ". --check" 22 | -------------------------------------------------------------------------------- /.github/workflows/ci-testing.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: CI Tests 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | fail-fast: false 17 | matrix: 18 | os: [ubuntu-latest] 19 | python-version: [3.6, 3.7, 3.8] 20 | 21 | steps: 22 | - uses: actions/checkout@v2 23 | - name: Set up Python ${{ matrix.python-version }} 24 | uses: actions/setup-python@v2 25 | with: 26 | python-version: ${{ matrix.python-version }} 27 | - name: Install dependencies 28 | run: | 29 | python -m pip install --upgrade pip 30 | pip install flake8 pytest pytest-cov 31 | pip install -r requirements.txt 32 | pip install -e . 33 | - name: Lint with flake8 34 | run: | 35 | # stop the build if there are Python syntax errors or undefined names 36 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 37 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 38 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 39 | - name: Test with pytest 40 | run: | 41 | pytest tests/ 42 | - name: Generate Coverage Report 43 | run: | 44 | pytest tests/ --cov=template_python --cov-report=xml 45 | - name: Upload Coverage to CodeCov 46 | uses: codecov/codecov-action@v1 47 | with: 48 | file: ./coverage.xml 49 | env_vars: OS,PYTHON 50 | name: codecov-umbrella 51 | fail_ci_if_error: false 52 | 53 | -------------------------------------------------------------------------------- /.github/workflows/install-pkg.yml: -------------------------------------------------------------------------------- 1 | name: Install Package 2 | 3 | # see: https://help.github.com/en/actions/reference/events-that-trigger-workflows 4 | on: 5 | # Trigger the workflow on push or pull request, 6 | # but only for the master branch 7 | push: 8 | branches: 9 | - master 10 | pull_request: 11 | branches: 12 | - master 13 | 14 | jobs: 15 | pkg-check: 16 | runs-on: ubuntu-latest 17 | 18 | steps: 19 | - uses: actions/checkout@master 20 | - uses: actions/setup-python@v2 21 | with: 22 | python-version: 3.7 23 | 24 | - name: Create package 25 | run: | 26 | python -m pip install --upgrade pip 27 | python -m pip install setuptools wheel 28 | python setup.py sdist bdist_wheel 29 | - name: Check package 30 | run: | 31 | pip install twine==1.13.0 32 | twine check dist/* 33 | python setup.py clean 34 | 35 | pkg-install: 36 | runs-on: ${{ matrix.os }} 37 | strategy: 38 | fail-fast: false 39 | # max-parallel: 6 40 | matrix: 41 | os: [ubuntu-latest, windows-2019, macOS-10.15] 42 | python-version: [3.6, 3.7, 3.8] 43 | 44 | steps: 45 | - uses: actions/checkout@master 46 | - uses: actions/setup-python@v2 47 | with: 48 | python-version: 3.7 49 | 50 | - name: Create and Install package on Ubuntu 51 | if: runner.os == 'Linux' 52 | run: | 53 | python -m pip install --upgrade pip 54 | python -m pip install setuptools wheel 55 | python setup.py sdist bdist_wheel 56 | pip install virtualenv 57 | virtualenv vEnv ; source vEnv/bin/activate 58 | pip install flake8 pytest pytest-cov 59 | pip install dist/* 60 | cd .. & python 61 | deactivate ; rm -rf vEnv 62 | 63 | - name: Install package on Mac 64 | if: runner.os == 'macOS' 65 | run: | 66 | python -m pip install --upgrade pip 67 | python -m pip install setuptools wheel 68 | python setup.py sdist bdist_wheel 69 | pip install virtualenv 70 | virtualenv vEnv ; source vEnv/bin/activate 71 | pip install flake8 pytest pytest-cov 72 | pip install dist/* 73 | cd .. & python 74 | deactivate ; rm -rf vEnv 75 | 76 | - name: Install package on Windows 77 | if: runner.os == 'windows' 78 | run: | 79 | python -m pip install --upgrade pip 80 | python -m pip install setuptools wheel 81 | python setup.py sdist bdist_wheel 82 | pip install virtualenv 83 | virtualenv vEnv ; venv\Scripts\activate.bat 84 | pip install flake8 pytest pytest-cov 85 | cd .. & python 86 | venv\Scripts\deactivate.bat ; rm -r vEnv 87 | 88 | # pip install dist/* Isn't working on windows, need a workaround. 89 | -------------------------------------------------------------------------------- /.github/workflows/mk-docs-build.yml: -------------------------------------------------------------------------------- 1 | name: Build mkdocs 2 | 3 | on: 4 | pull_request: 5 | branches: [ master ] 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-18.04 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Set up Python 3.6 14 | uses: actions/setup-python@v1 15 | with: 16 | python-version: 3.6 17 | - name: Install dependencies 18 | run: | 19 | python -m pip install --upgrade pip setuptools 20 | pip install git+git://github.com/oke-aditya/pytorch_fasterrcnn.git 21 | pip install -e . 22 | pip install -r docs/requirements.txt 23 | - name: Build the docs 24 | run: | 25 | cd docs 26 | mkdocs build 27 | -------------------------------------------------------------------------------- /.github/workflows/mk-docs-deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy mkdocs 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-18.04 12 | steps: 13 | - uses: actions/checkout@v2 14 | - name: Set up Python 3.6 15 | uses: actions/setup-python@v1 16 | with: 17 | python-version: 3.6 18 | - name: Install dependencies 19 | run: | 20 | python -m pip install --upgrade pip setuptools 21 | pip install git+git://github.com/oke-aditya/pytorch_fasterrcnn.git 22 | pip install -e . 23 | pip install -r docs/requirements.txt 24 | - name: Build the docs 25 | run: | 26 | cd docs 27 | mkdocs build 28 | mkdocs gh-deploy --force 29 | -------------------------------------------------------------------------------- /.github/workflows/pypi-release.yml: -------------------------------------------------------------------------------- 1 | name: PyPi Release 2 | 3 | # https://help.github.com/en/actions/reference/events-that-trigger-workflows 4 | on: 5 | # Trigger the workflow on push or pull request, 6 | # but only for the master branch 7 | push: 8 | branches: 9 | - master 10 | release: 11 | types: 12 | - created 13 | 14 | # based on https://github.com/pypa/gh-action-pypi-publish 15 | 16 | jobs: 17 | build: 18 | runs-on: ubuntu-latest 19 | 20 | steps: 21 | - uses: actions/checkout@v2 22 | - uses: actions/setup-python@v2 23 | with: 24 | python-version: 3.7 25 | 26 | - name: Install dependencies 27 | run: >- 28 | python -m pip install --user --upgrade setuptools wheel 29 | - name: Build 30 | run: >- 31 | python setup.py sdist bdist_wheel 32 | # We do this, since failures on test.pypi aren't that bad 33 | - name: Publish to Test PyPI 34 | if: startsWith(github.event.ref, 'refs/tags') || github.event_name == 'release' 35 | uses: pypa/gh-action-pypi-publish@master 36 | with: 37 | user: __token__ 38 | password: ${{ secrets.test_pypi_password }} 39 | repository_url: https://test.pypi.org/legacy/ 40 | 41 | - name: Publish distribution 📦 to PyPI 42 | if: startsWith(github.event.ref, 'refs/tags') || github.event_name == 'release' 43 | uses: pypa/gh-action-pypi-publish@master 44 | with: 45 | user: __token__ 46 | password: ${{ secrets.pypi_password }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ipython notebooks won't make a package proper 2 | *.ipynb 3 | #data_files 4 | 5 | data/ 6 | src/data_proc.py 7 | 8 | # Byte-compiled / optimized / DLL files 9 | __pycache__/ 10 | *.py[cod] 11 | *$py.class 12 | 13 | # C extensions 14 | *.so 15 | 16 | # Distribution / packaging 17 | .Python 18 | build/ 19 | develop-eggs/ 20 | dist/ 21 | downloads/ 22 | eggs/ 23 | .eggs/ 24 | lib/ 25 | lib64/ 26 | parts/ 27 | sdist/ 28 | var/ 29 | wheels/ 30 | pip-wheel-metadata/ 31 | share/python-wheels/ 32 | *.egg-info/ 33 | .installed.cfg 34 | *.egg 35 | MANIFEST 36 | 37 | # PyInstaller 38 | # Usually these files are written by a python script from a template 39 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 40 | *.manifest 41 | *.spec 42 | 43 | # Installer logs 44 | pip-log.txt 45 | pip-delete-this-directory.txt 46 | 47 | # Unit test / coverage reports 48 | htmlcov/ 49 | .tox/ 50 | .nox/ 51 | .coverage 52 | .coverage.* 53 | .cache 54 | nosetests.xml 55 | coverage.xml 56 | *.cover 57 | *.py,cover 58 | .hypothesis/ 59 | .pytest_cache/ 60 | 61 | # Translations 62 | *.mo 63 | *.pot 64 | 65 | # Django stuff: 66 | *.log 67 | local_settings.py 68 | db.sqlite3 69 | db.sqlite3-journal 70 | 71 | # Flask stuff: 72 | instance/ 73 | .webassets-cache 74 | 75 | # Scrapy stuff: 76 | .scrapy 77 | 78 | # Sphinx documentation 79 | docs/_build/ 80 | 81 | # PyBuilder 82 | target/ 83 | 84 | # Jupyter Notebook 85 | .ipynb_checkpoints 86 | 87 | # IPython 88 | profile_default/ 89 | ipython_config.py 90 | 91 | # pyenv 92 | .python-version 93 | 94 | # pipenv 95 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 96 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 97 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 98 | # install all needed dependencies. 99 | #Pipfile.lock 100 | 101 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 102 | __pypackages__/ 103 | 104 | # Celery stuff 105 | celerybeat-schedule 106 | celerybeat.pid 107 | 108 | # SageMath parsed files 109 | *.sage.py 110 | 111 | # Environments 112 | .env 113 | .venv 114 | env/ 115 | venv/ 116 | ENV/ 117 | env.bak/ 118 | venv.bak/ 119 | 120 | # Spyder project settings 121 | .spyderproject 122 | .spyproject 123 | 124 | # Rope project settings 125 | .ropeproject 126 | 127 | # mkdocs documentation 128 | /site 129 | 130 | # mypy 131 | .mypy_cache/ 132 | .dmypy.json 133 | dmypy.json 134 | 135 | # Pyre type checker 136 | .pyre/ 137 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/pytorch_fasterrcnn/bd1bec1ddad605d500406b15e76864e10a91062b/.gitmodules -------------------------------------------------------------------------------- /.nojekyll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/pytorch_fasterrcnn/bd1bec1ddad605d500406b15e76864e10a91062b/.nojekyll -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting Made With ML at hello@madewithml.com . All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html), version 1.4. 71 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guide 2 | 3 | **Please, follow these steps** 4 | 5 | ## Step 1: Forking and Installing template_python 6 | 7 | ​1. Fork the repo to your own github account. click the Fork button to 8 | create your own repo copy under your GitHub account. Once forked, you're 9 | responsible for keeping your repo copy up-to-date with the upstream 10 | template_python repo. 11 | 12 | ​2. Download a copy of your remote username/template_python repo to your 13 | local machine. This is the working directory where you will make 14 | changes: 15 | 16 | ```bash 17 | $ git clone https://github.com/oke-aditya/template_python.git 18 | ``` 19 | 20 | 3. Install the requirments. You many use miniconda or conda as well. 21 | 22 | ```bash 23 | $ pip install -r requirements.txt 24 | ``` 25 | 26 | ## Step 2: Stay in Sync with the original (upstream) repo 27 | 28 | 1. Set the upstream to sync with this repo. This will keep you in sync 29 | with template_python easily. 30 | 31 | ```bash 32 | $ git remote add upstream https://github.com/oke-aditya/template_python.git 33 | ``` 34 | 35 | 2. Updating your local repo: Pull the upstream (original) repo. 36 | 37 | ```bash 38 | $ git checkout master 39 | $ git pull upstream master 40 | ``` 41 | 42 | ## Step 3: Creating a new branch 43 | 44 | ```bash 45 | $ git checkout -b feature-name 46 | $ git branch 47 | master 48 | * feature_name: 49 | ``` 50 | 51 | ## Step 4: Make changes, and commit your file changes 52 | 53 | Edit files in your favorite editor, and format the code with 54 | [black](https://black.readthedocs.io/en/stable/) 55 | 56 | ```bash 57 | # View changes 58 | git status # See which files have changed 59 | git diff # See changes within files 60 | 61 | git add path/to/file.md 62 | git commit -m "Your meaningful commit message for the change." 63 | ``` 64 | 65 | Add more commits, if necessary. 66 | 67 | ## Step 5: Submitting a Pull Request 68 | 69 | ### A. Method 1: Using GitHub CLI 70 | 71 | Preliminary step (done only once): Install gh by following the 72 | instructions in [docs](https://cli.github.com/manual/installation) . 73 | 74 | #### 1. Create a pull request using GitHub CLI 75 | 76 | ```bash 77 | # Fill up the PR title and the body 78 | gh pr create -B master -b "enter body of PR here" -t "enter title" 79 | ``` 80 | 81 | #### 2. Confirm PR was created 82 | 83 | You can confirm that your PR has been created by running the following 84 | command, from the template_python folder: 85 | 86 | ```bash 87 | gh pr list 88 | ``` 89 | 90 | You can also check the status of your PR by running: 91 | 92 | ```bash 93 | gh pr status 94 | ``` 95 | 96 | More detailed documentation can be found 97 | . 98 | 99 | #### 3. Updating a PR 100 | 101 | If you want to change your code after a PR has been created, you can do 102 | it by sending more commits to the same remote branch. For example: 103 | 104 | ```bash 105 | git commit -m "updated the feature" 106 | git push origin 107 | ``` 108 | 109 | It will automatically show up in the PR on the github page. If these are 110 | small changes they can be squashed together by the reviewer at the merge 111 | time and appear as a single commit in the repository. 112 | 113 | ### B. Method 2: Using Git 114 | 115 | #### 1. Create a pull request git 116 | 117 | Upload your local branch to your remote GitHub repo 118 | (github.com/username/template_python) 119 | 120 | ```bash 121 | git push 122 | ``` 123 | 124 | After the push completes, a message may display a URL to automatically 125 | submit a pull request to the upstream repo. If not, go to the 126 | template_python main repo and GitHub will prompt you to create a pull 127 | request. 128 | 129 | #### 2. Confirm PR was created: 130 | 131 | Ensure your pr is listed 132 | [here](https://github.com/oke-aditya/template_python/pulls) 133 | 134 | 3. Updating a PR: 135 | 136 | Same as before, normally push changes to your branch and the PR will get 137 | automatically updated. 138 | 139 | ```bash 140 | git commit -m "updated the feature" 141 | git push origin 142 | ``` 143 | 144 | * * * * * 145 | 146 | ## Reviewing Your PR 147 | 148 | Maintainers and other contributors will review your pull request. Please 149 | participate in the discussion and make the requested changes. When your 150 | pull request is approved, it will be merged into the upstream 151 | template_python repo. 152 | 153 | > **note** 154 | > 155 | > template_python repository has CI checking. It will automatically check your code 156 | > for build as well. 157 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Pytorch FasterRCNN Copyright (C) 2020 Aditya Oke 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include CONTRIBUTING.md 2 | include LICENSE 3 | include README.md 4 | include settings.ini 5 | include CODE_OF_CONDUCT.md 6 | recursive-exclude * __pycache_ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pytorch Faster RCNN 2 | 3 | - Note that this PyPi package is no longer maintained. It will work fine upto this release, but I won't do bug fixes. 4 | - The entire code and API is migrated to [Quickvison](https://github.com/Quick-AI/quickvision), it has similar API and is maintained actively. 5 | 6 | ![CI Tests](https://github.com/oke-aditya/pytorch_fasterrcnn/workflows/CI%20Tests/badge.svg) 7 | ![Check Formatting](https://github.com/oke-aditya/pytorch_fasterrcnn/workflows/Check%20Formatting/badge.svg) 8 | ![Build mkdocs](https://github.com/oke-aditya/pytorch_fasterrcnn/workflows/Build%20mkdocs/badge.svg) 9 | ![Deploy mkdocs](https://github.com/oke-aditya/pytorch_fasterrcnn/workflows/Deploy%20mkdocs/badge.svg) 10 | ![PyPi Release](https://github.com/oke-aditya/pytorch_fasterrcnn/workflows/PyPi%20Release/badge.svg) 11 | ![Install Package](https://github.com/oke-aditya/pytorch_fasterrcnn/workflows/Install%20Package/badge.svg) 12 | 13 | Faster RCNN Fine-Tune Implementation in Pytorch. 14 | 15 | ## How to use ? 16 | 1. git clone the repo 17 | ``` 18 | git clone https://github.com/oke-aditya/pytorch_fasterrcnn.git 19 | ``` 20 | 2. Install PyTorch and torchvision for your system. 21 | 22 | Simply edit the config file to set your hyper parameters. 23 | 24 | 3. Keep the training and validation csv file as follows 25 | 26 | NOTE 27 | 28 | Do not use target as 0 class. It is reserved as background. 29 | 30 | 31 | ``` 32 | image_id xtl ytl xbr ybr target 33 | 1 xmin ymin xmax ymax 1 34 | 1 xmin ymin xmax ymax 2 35 | 2 xmin ymin xmax ymax 3 36 | ``` 37 | 38 | 4. Simply edit the config file to set your hyper parameters 39 | 40 | 5. Run the train.py file 41 | 42 | # Features: - 43 | 44 | - It works for multiple class object detection. 45 | 46 | ## Backbones Supported: - 47 | 48 | 49 | - Note that backbones are pretrained on imagenet. 50 | 51 | - Following backbones are supported 52 | 53 | 1. vgg11, vgg13, vgg16, vgg19 54 | 2. resnet18, resnet34, resnet50, resnet101, resnet152 55 | 3. renext101 56 | 4. mobilenet_v2 57 | 58 | 59 | Sample Outputs 60 | 61 | # Helmet Detector 62 | ![Helmet Detection](outputs/helmet.jpg) 63 | 64 | # Mask Detector 65 | ![Mask Detection](outputs/mask.jpg) 66 | 67 | 68 | 69 | If you like the implemenation or have taken an inspiration do give a star :-) 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /docs/mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: PyTorch Faster RCNN Docs 2 | theme: 3 | name: "material" 4 | palette: 5 | primary: "dark-blue" 6 | accent: "dark-blue" 7 | # scheme: slate Use this for dark mode 8 | # scheme: slate 9 | scheme: default 10 | # Use this for light mode 11 | 12 | docs_dir: templates 13 | repo_url: https://github.com/oke-aditya/pytorch_fasterrcnn 14 | markdown_extensions: 15 | - codehilite 16 | - pymdownx.superfences: 17 | custom_fences: 18 | - name: mermaid 19 | class: mermaid 20 | format: !!python/name:pymdownx.superfences.fence_div_format 21 | - pymdownx.emoji: 22 | emoji_index: !!python/name:materialx.emoji.twemoji 23 | emoji_generator: !!python/name:materialx.emoji.to_svg 24 | - admonition 25 | extra_javascript: 26 | - https://unpkg.com/mermaid@8.4.4/dist/mermaid.min.js 27 | 28 | nav: 29 | - Home: index.md 30 | - Contributing: contributing.md 31 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | mkdocs 2 | mkdocs-material 3 | pygments 4 | jupyter 5 | pymdown-extensions 6 | Sphinx 7 | -------------------------------------------------------------------------------- /docs/templates/contributing.md: -------------------------------------------------------------------------------- 1 | # Contribution Guide 2 | 3 | **Please, follow these steps** 4 | 5 | ## Step 1: Forking and Installing pytorch_fasterrcnn 6 | 7 | ​1. Fork the repo to your own github account. click the Fork button to 8 | create your own repo copy under your GitHub account. Once forked, you're 9 | responsible for keeping your repo copy up-to-date with the upstream 10 | pytorch_fasterrcnn repo. 11 | 12 | ​2. Download a copy of your remote username/pytorch_fasterrcnn repo to your 13 | local machine. This is the working directory where you will make 14 | changes: 15 | 16 | ```bash 17 | $ git clone https://github.com/oke-aditya/pytorch_fasterrcnn.git 18 | ``` 19 | 20 | 3. Install the requirments. You many use miniconda or conda as well. 21 | 22 | ```bash 23 | $ pip install -r requirements.txt 24 | ``` 25 | 26 | ## Step 2: Stay in Sync with the original (upstream) repo 27 | 28 | 1. Set the upstream to sync with this repo. This will keep you in sync 29 | with pytorch_fasterrcnn easily. 30 | 31 | ```bash 32 | $ git remote add upstream https://github.com/oke-aditya/pytorch_fasterrcnn.git 33 | ``` 34 | 35 | 2. Updating your local repo: Pull the upstream (original) repo. 36 | 37 | ```bash 38 | $ git checkout master 39 | $ git pull upstream master 40 | ``` 41 | 42 | ## Step 3: Creating a new branch 43 | 44 | ```bash 45 | $ git checkout -b feature-name 46 | $ git branch 47 | master 48 | * feature_name: 49 | ``` 50 | 51 | ## Step 4: Make changes, and commit your file changes 52 | 53 | Edit files in your favorite editor, and format the code with 54 | [black](https://black.readthedocs.io/en/stable/) 55 | 56 | ```bash 57 | # View changes 58 | git status # See which files have changed 59 | git diff # See changes within files 60 | 61 | git add path/to/file.md 62 | git commit -m "Your meaningful commit message for the change." 63 | ``` 64 | 65 | Add more commits, if necessary. 66 | 67 | ## Step 5: Submitting a Pull Request 68 | 69 | ### A. Method 1: Using GitHub CLI 70 | 71 | Preliminary step (done only once): Install gh by following the 72 | instructions in [docs](https://cli.github.com/manual/installation) . 73 | 74 | #### 1. Create a pull request using GitHub CLI 75 | 76 | ```bash 77 | # Fill up the PR title and the body 78 | gh pr create -B master -b "enter body of PR here" -t "enter title" 79 | ``` 80 | 81 | #### 2. Confirm PR was created 82 | 83 | You can confirm that your PR has been created by running the following 84 | command, from the pytorch_fasterrcnn folder: 85 | 86 | ```bash 87 | gh pr list 88 | ``` 89 | 90 | You can also check the status of your PR by running: 91 | 92 | ```bash 93 | gh pr status 94 | ``` 95 | 96 | More detailed documentation can be found 97 | . 98 | 99 | #### 3. Updating a PR 100 | 101 | If you want to change your code after a PR has been created, you can do 102 | it by sending more commits to the same remote branch. For example: 103 | 104 | ```bash 105 | git commit -m "updated the feature" 106 | git push origin 107 | ``` 108 | 109 | It will automatically show up in the PR on the github page. If these are 110 | small changes they can be squashed together by the reviewer at the merge 111 | time and appear as a single commit in the repository. 112 | 113 | ### B. Method 2: Using Git 114 | 115 | #### 1. Create a pull request git 116 | 117 | Upload your local branch to your remote GitHub repo 118 | (github.com/username/pytorch_fasterrcnn) 119 | 120 | ```bash 121 | git push 122 | ``` 123 | 124 | After the push completes, a message may display a URL to automatically 125 | submit a pull request to the upstream repo. If not, go to the 126 | pytorch_fasterrcnn main repo and GitHub will prompt you to create a pull 127 | request. 128 | 129 | #### 2. Confirm PR was created: 130 | 131 | Ensure your pr is listed 132 | [here](https://github.com/oke-aditya/pytorch_fasterrcnn/pulls) 133 | 134 | 3. Updating a PR: 135 | 136 | Same as before, normally push changes to your branch and the PR will get 137 | automatically updated. 138 | 139 | ```bash 140 | git commit -m "updated the feature" 141 | git push origin 142 | ``` 143 | 144 | * * * * * 145 | 146 | ## Reviewing Your PR 147 | 148 | Maintainers and other contributors will review your pull request. Please 149 | participate in the discussion and make the requested changes. When your 150 | pull request is approved, it will be merged into the upstream 151 | pytorch_fasterrcnn repo. 152 | 153 | > **note** 154 | > 155 | > pytorch_fasterrcnn repository has CI checking. It will automatically check your code 156 | > for build as well. 157 | -------------------------------------------------------------------------------- /docs/templates/index.md: -------------------------------------------------------------------------------- 1 | # Pytorch Faster RCNN 2 | 3 | Faster RCNN Fine-Tune Implementation in Pytorch. 4 | 5 | ## How to use ? 6 | 1. git clone the repo 7 | ``` 8 | git clone https://github.com/oke-aditya/pytorch_fasterrcnn.git 9 | ``` 10 | 2. Install PyTorch and torchvision for your system. 11 | 12 | Simply edit the config file to set your hyper parameters. 13 | 14 | 3. Keep the training and validation csv file as follows 15 | 16 | NOTE 17 | 18 | Do not use target as 0 class. It is reserved as background. 19 | 20 | 21 | ``` 22 | image_id xtl ytl xbr ybr target 23 | 1 xmin ymin xmax ymax 1 24 | 1 xmin ymin xmax ymax 2 25 | 2 xmin ymin xmax ymax 3 26 | ``` 27 | 28 | 4. Simply edit the config file to set your hyper parameters 29 | 30 | 5. Run the train.py file 31 | 32 | # Features: - 33 | 34 | - It works for multiple class object detection. 35 | 36 | ## Backbones Supported: - 37 | 38 | 39 | - Note that backbones are pretrained on imagenet. 40 | 41 | - Following backbones are supported 42 | 43 | 1. vgg11, vgg13, vgg16, vgg19 44 | 2. resnet18, resnet34, resnet50, resnet101, resnet152 45 | 3. renext101 46 | 4. mobilenet_v2 47 | 48 | 49 | Sample Outputs 50 | 51 | # Helmet Detector 52 | ![Helmet Detection](outputs/helmet.jpg) 53 | 54 | # Mask Detector 55 | ![Mask Detection](outputs/mask.jpg) 56 | 57 | If you like the implemenation or have taken an inspiration do give a star :-) 58 | 59 | -------------------------------------------------------------------------------- /outputs/helmet.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/pytorch_fasterrcnn/bd1bec1ddad605d500406b15e76864e10a91062b/outputs/helmet.jpg -------------------------------------------------------------------------------- /outputs/mask.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/pytorch_fasterrcnn/bd1bec1ddad605d500406b15e76864e10a91062b/outputs/mask.jpg -------------------------------------------------------------------------------- /pytorch_fasterrcnn/__init__.py: -------------------------------------------------------------------------------- 1 | from dataset import * 2 | from engine import * 3 | from inference import * 4 | from model import * 5 | -------------------------------------------------------------------------------- /pytorch_fasterrcnn/config.py: -------------------------------------------------------------------------------- 1 | # Contains the configuration files for training and dataloader 2 | # Edit the configuration file as per your needs 3 | 4 | 5 | TRAIN_CSV_PATH = "df_train.csv" 6 | VALIDATION_CSV_PATH = "df_val.csv" 7 | IMAGE_DIR = "images/" 8 | TARGET_COL = "has_helmet" 9 | TRAIN_BATCH_SIZE = 2 10 | VALID_BATCH_SIZE = 2 11 | TRAIN_WORKERS = 4 12 | LEARNING_RATE = 1e-3 13 | EPOCHS = 10 14 | NUM_CLASSES = 5 15 | DETECTION_THRESHOLD = 0.25 16 | 17 | BACKBONE = "vgg_16" 18 | MODEL_SAVE_PATH = "models/faster_rcnn_{}.pt".format(BACKBONE) 19 | # valid_batch_size = 4 20 | # valid_workers = 2 21 | 22 | OUTPUT_PATH = "outputs/" 23 | 24 | PREDICT_IMAGE = None 25 | SAVE_IMAGE = None 26 | SAVE_DIR = "outputs/" 27 | -------------------------------------------------------------------------------- /pytorch_fasterrcnn/crash_test.py: -------------------------------------------------------------------------------- 1 | # import joblib 2 | 3 | # helm_dict = joblib.load('data\models\helm_dict.pkl') 4 | # mask_dict = joblib.load('data\models\mask_dict.pkl') 5 | 6 | # print(helm_dict) 7 | 8 | # print(mask_dict) 9 | 10 | # import os 11 | 12 | # import pandas as pd 13 | # import torch 14 | 15 | # df = pd.read_csv("data\df_train.csv") 16 | # # print(df.head()) 17 | # # image_id = 0 18 | # image_id = 3 19 | # records = df[df['image_id'] == image_id] 20 | # print(records) 21 | # boxes = records[['xtl', 'ytl', 'xbr', 'ybr']].values 22 | # print(boxes) 23 | # # # # We already have xtl ytl xbr ybr. We don't need to do this 24 | # # # # We can do this for x y w h format of boxes. 25 | # # # # boxes[:, 2] = boxes[:, 0] + boxes[:, 2] 26 | # # # # boxes[:, 3] = boxes[:, 1] + boxes[:, 3] 27 | # boxes = torch.as_tensor(boxes, dtype=torch.float32) 28 | # # # area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]) 29 | # # # area = torch.as_tensor(area, dtype=torch.float32) 30 | 31 | # # # print(boxes) 32 | 33 | # # # For the labels for has_helmet 34 | # # labels_act = torch.ones((records.shape[0],), dtype=torch.int64) 35 | # # print(labels_act) 36 | 37 | # # # For has helmet 38 | # # labels_helmet = records['has_helmet'].values 39 | # # labels_helmet = torch.tensor(labels_helmet, dtype=torch.int64) 40 | # # print(labels_helmet) 41 | 42 | # # For has_mask 43 | # labels_mask = records["has_mask"].values 44 | # labels_mask = torch.tensor(labels_mask, dtype=torch.int64) 45 | # print(labels_mask) 46 | 47 | # # print(os.listdir('data/images/')) 48 | 49 | # # image_ids = df['image_id'].unique() 50 | # # index = 12 51 | # # image_id = image_ids[index] 52 | # # print(image_id) 53 | # # print(df.shape) 54 | -------------------------------------------------------------------------------- /pytorch_fasterrcnn/dataset.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | import cv2 4 | import torch 5 | from torch.utils.data import DataLoader, Dataset 6 | 7 | __all__ = ["detection_dataset"] 8 | 9 | 10 | class detection_dataset(Dataset): 11 | def __init__(self, dataframe, image_dir, target, transforms=None, train=True): 12 | super().__init__() 13 | 14 | self.image_ids = dataframe["image_id"].unique() 15 | self.image_dir = image_dir 16 | self.transforms = transforms 17 | self.df = dataframe 18 | self.train = train 19 | self.target = target 20 | 21 | def __len__(self): 22 | return self.image_ids.shape[0] 23 | 24 | def __getitem__(self, index): 25 | image_id = self.image_ids[index] 26 | image_src = os.path.join(self.image_dir, str(image_id)) + ".jpg" 27 | image = cv2.imread(image_src, cv2.IMREAD_COLOR) 28 | image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32) 29 | 30 | # Scale down the pixel values of image 31 | image /= 255.0 32 | 33 | if self.transforms is not None: # Apply transformation 34 | image = self.transforms(image) 35 | 36 | if self.train is False: # For test data 37 | return image, image_id 38 | 39 | # Else for train and validation data 40 | records = self.df[self.df["image_id"] == image_id] 41 | boxes = records[["xtl", "ytl", "xbr", "ybr"]].values 42 | boxes = torch.as_tensor(boxes, dtype=torch.float32) 43 | 44 | area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]) 45 | area = torch.as_tensor(area, dtype=torch.float32) 46 | 47 | # For has helmet 48 | # labels_helmet = records['has_helmet'].values 49 | # labels_helmet = torch.as_tensor(labels_helmet, dtype=torch.int64) 50 | # print(labels_helmet) 51 | 52 | # labels_mask = torch.ones((records.shape[0],), dtype=torch.int64) 53 | 54 | # For has_mask 55 | labels = records[self.target].values 56 | labels = torch.as_tensor(labels, dtype=torch.int64) 57 | # print(labels) 58 | 59 | target = {} 60 | target["boxes"] = boxes 61 | target["labels"] = labels 62 | target["image_id"] = torch.tensor([index]) 63 | target["area"] = area 64 | 65 | return image, target, image_id 66 | -------------------------------------------------------------------------------- /pytorch_fasterrcnn/engine.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torchvision 3 | import torchvision.transforms as T 4 | import model 5 | import config 6 | import dataset 7 | import numpy as np 8 | import time 9 | from tqdm import tqdm 10 | 11 | __all__ = ["train_fn", "eval_fn"] 12 | 13 | 14 | def train_fn(train_dataloader, detector, optimizer, device, scheduler=None): 15 | detector.train() 16 | for images, targets, image_ids in tqdm(train_dataloader): 17 | images = list(image.to(device) for image in images) 18 | # it's key:value for t in targets.items 19 | # This is the format the fasterrcnn expects for targets 20 | targets = [{k: v.to(device) for k, v in t.items()} for t in targets] 21 | 22 | loss_dict = detector(images, targets) 23 | losses = sum(loss for loss in loss_dict.values()) 24 | loss_value = losses.item() 25 | 26 | optimizer.zero_grad() 27 | losses.backward() 28 | optimizer.step() 29 | 30 | if scheduler is not None: 31 | scheduler.step() 32 | 33 | return loss_value 34 | 35 | 36 | def eval_fn(val_dataloader, detector, device, detection_threshold=0.45): 37 | results = [] 38 | detector.eval() 39 | with torch.no_grad(): 40 | for images, targets, image_ids in tqdm(val_dataloader): 41 | images = list(image.to(device) for image in images) 42 | 43 | model_time = time.time() 44 | outputs = detector(images) 45 | model_time = time.time() - model_time 46 | # print("Inference time taken on image_batch = {}".format(model_time)) 47 | 48 | # outputs = [{k: v.to(device) for k, v in t.items()} for t in outputs] 49 | # res = {target["image_id"].item(): output for target, output in zip(targets, outputs)} 50 | 51 | for i, image in enumerate(images): 52 | boxes = ( 53 | outputs[i]["boxes"].data.cpu().numpy() 54 | ) # Format of the output's box is [Xmin,Ymin,Xmax,Ymax] 55 | scores = outputs[i]["scores"].data.cpu().numpy() 56 | labels = outputs[i]["labels"].data.cpu().numpy() 57 | # boxes = boxes[scores >= detection_threshold].astype(np.float) 58 | # Compare the score of output with the threshold and 59 | # select only those boxes whose score is greater 60 | # scores = scores[scores >= detection_threshold] 61 | # labels = labels[scores >= detection_threshold] 62 | image_id = image_ids[i] 63 | result = { # Store the image id and boxes and scores in result dict. 64 | "image_id": image_id, 65 | "boxes": boxes, 66 | "scores": scores, 67 | "labels": labels, 68 | } 69 | results.append(result) 70 | 71 | return results 72 | -------------------------------------------------------------------------------- /pytorch_fasterrcnn/inference.py: -------------------------------------------------------------------------------- 1 | # This script does only inference from the loaded model 2 | import cv2 3 | import matplotlib.pyplot as plt 4 | import torch 5 | import model 6 | import os 7 | from PIL import Image 8 | import torchvision.transforms as T 9 | import config 10 | 11 | device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") 12 | 13 | __all__ = [ 14 | "load_model", 15 | "load_image_tensor", 16 | "get_prediction", 17 | "draw_box", 18 | "load_image_to_plot", 19 | "save_prediction", 20 | "get_folder_results", 21 | ] 22 | 23 | 24 | def load_model(): 25 | detector = model.create_model(num_classes=config.NUM_CLASSES) 26 | # print(detector) 27 | detector.load_state_dict(torch.load(config.MODEL_SAVE_PATH, map_location=device)) 28 | # print(detector) 29 | detector.eval() 30 | detector.to(device) 31 | return detector 32 | 33 | 34 | # Load the detector for inference 35 | 36 | 37 | def load_image_tensor(image_path, device): 38 | image_tensor = T.ToTensor()(Image.open(image_path)) 39 | input_images = [image_tensor.to(device)] 40 | return input_images 41 | 42 | 43 | def get_prediction(detector, images): 44 | # We can do a batch prediction as well but right now I'm doing on single image 45 | # Batch prediction can improve time but let's keep it simple for now. 46 | with torch.no_grad(): 47 | prediction = detector(images) 48 | return prediction 49 | 50 | 51 | def draw_box(image, box, label_id, score): 52 | xtl = int(box[0]) 53 | ytl = int(box[1]) 54 | xbr = int(box[2]) 55 | ybr = int(box[3]) 56 | # Some hard coding for label 57 | if label_id == 1: 58 | label = "yes" 59 | cv2.rectangle(image, (xtl, ytl), (xbr, ybr), color=(0, 255, 0)) 60 | elif label_id == 2: 61 | label = "no" 62 | cv2.rectangle(image, (xtl, ytl), (xbr, ybr), color=(0, 0, 255)) 63 | elif label_id == 3: 64 | label = "invisible" 65 | cv2.rectangle(image, (xtl, ytl), (xbr, ybr), color=(0, 0, 255)) 66 | elif label_id == 4: 67 | label = "wrong" 68 | cv2.rectangle(image, (xtl, ytl), (xbr, ybr), color=(0, 0, 255)) 69 | 70 | print("label = {}".format(label)) 71 | cv2.putText( 72 | image, label, (xtl, ytl), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (36, 255, 12), 2 73 | ) 74 | # cv2.putText(image, label, (xbr, ybr), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (36,255,12), 2) 75 | 76 | 77 | def load_image_to_plot(image_dir): 78 | image = cv2.imread(image_dir, cv2.IMREAD_COLOR) 79 | image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 80 | return image 81 | 82 | 83 | def save_prediction(prediction, image_name, image): 84 | for pred in prediction: 85 | boxes = pred["boxes"].data.cpu().numpy() 86 | labels = pred["labels"].data.cpu().numpy() 87 | scores = pred["scores"].data.cpu().numpy() 88 | 89 | for i in range(len(labels)): 90 | if scores[i] > config.DETECTION_THRESHOLD: 91 | box_draw = boxes[i] 92 | label_draw = labels[i] 93 | score = scores[i] 94 | print(score) 95 | print(box_draw) 96 | print(label_draw) 97 | draw_box(image, box_draw, label_draw, score) 98 | 99 | # plt.imshow(image) 100 | # plt.show() 101 | 102 | # image_name = config.OUTPUT_PATH + image_name 103 | cv2.imwrite(image_name, image) 104 | 105 | 106 | def get_folder_results(detector, image_dir, device): 107 | for image in os.listdir(image_dir): 108 | image_path = os.path.join(image_dir, image) 109 | input_images = load_image_tensor(image_path, device) 110 | prediction = get_prediction(detector, input_images) 111 | image_loaded = load_image_to_plot(image_path) 112 | save_path = os.path.join(config.SAVE_DIR, image) 113 | save_prediction(prediction, save_path, image_loaded) 114 | 115 | 116 | if __name__ == "__main__": 117 | detector = load_model() 118 | print("---------- Model succesfully loaded -------- ") 119 | # print(detector) 120 | 121 | input_images = load_image_tensor(config.PREDICT_IMAGE, device) 122 | prediction = get_prediction(detector, input_images) 123 | # print(prediction) 124 | image = load_image_to_plot(config.PREDICT_IMAGE) 125 | # save_prediction(prediction, config.SAVE_IMAGE, image) 126 | get_folder_results(detector, config.IMAGE_DIR, device) 127 | # print(prediction) 128 | -------------------------------------------------------------------------------- /pytorch_fasterrcnn/model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torchvision 4 | import torchvision.transforms as T 5 | from torchvision.models.detection.rpn import AnchorGenerator 6 | from torchvision.models.detection import FasterRCNN 7 | 8 | device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") 9 | 10 | __all__ = ["create_model"] 11 | 12 | 13 | def create_model(num_classes, min_size=300, max_size=500, backbone="mobile_net"): 14 | # note num_classes = total_classes + 1 for background. 15 | 16 | # Adding multiple backbones We don't need the built in Fasterrcnn 17 | # This is the default backbone rcnn. We can change it. 18 | 19 | # This model was trained on COCO 20 | # model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True) 21 | # model = model.to(device) 22 | 23 | # get number of input features for the classifier 24 | # in_features = model.roi_heads.box_predictor.cls_score.in_features 25 | 26 | # ft_min_size = min_size 27 | # ft_max_size = max_size 28 | 29 | # These backbones are trained on ImageNet not on COCO 30 | # Please train them on COCO and provide model_dict I would use them instead. 31 | if backbone == "mobile_net": 32 | mobile_net = torchvision.models.mobilenet_v2(pretrained=True) 33 | # print(mobile_net.features) # From that I got the output channels for mobilenet 34 | ft_backbone = mobile_net.features 35 | ft_backbone.out_channels = 1280 36 | 37 | elif backbone == "vgg_11": 38 | vgg_net = torchvision.models.vgg11(pretrained=True) 39 | ft_backbone = vgg_net.features 40 | ft_backbone.out_channels = 512 41 | 42 | elif backbone == "vgg_13": 43 | vgg_net = torchvision.models.vgg13(pretrained=True) 44 | ft_backbone = vgg_net.features 45 | ft_backbone.out_channels = 512 46 | 47 | elif backbone == "vgg_16": 48 | vgg_net = torchvision.models.vgg13(pretrained=True) 49 | ft_backbone = vgg_net.features 50 | ft_backbone.out_channels = 512 51 | 52 | elif backbone == "vgg_19": 53 | vgg_net = torchvision.models.vgg19(pretrained=True) 54 | ft_backbone = vgg_net.features 55 | ft_backbone.out_channels = 512 56 | 57 | elif backbone == "resnet_18": 58 | resnet_net = torchvision.models.resnet18(pretrained=True) 59 | modules = list(resnet_net.children())[:-1] 60 | ft_backbone = nn.Sequential(*modules) 61 | ft_backbone.out_channels = 512 62 | 63 | elif backbone == "resnet_34": 64 | resnet_net = torchvision.models.resnet34(pretrained=True) 65 | modules = list(resnet_net.children())[:-1] 66 | ft_backbone = nn.Sequential(*modules) 67 | ft_backbone.out_channels = 512 68 | 69 | elif backbone == "resnet_50": 70 | resnet_net = torchvision.models.resnet50(pretrained=True) 71 | modules = list(resnet_net.children())[:-1] 72 | ft_backbone = nn.Sequential(*modules) 73 | ft_backbone.out_channels = 2048 74 | 75 | elif backbone == "resnet_101": 76 | resnet_net = torchvision.models.resnet101(pretrained=True) 77 | modules = list(resnet_net.children())[:-1] 78 | ft_backbone = nn.Sequential(*modules) 79 | ft_backbone.out_channels = 2048 80 | 81 | elif backbone == "resnet_152": 82 | resnet_net = torchvision.models.resnet152(pretrained=True) 83 | modules = list(resnet_net.children())[:-1] 84 | ft_backbone = nn.Sequential(*modules) 85 | ft_backbone.out_channels = 2048 86 | 87 | elif backbone == "resnext101_32x8d": 88 | resnet_net = torchvision.models.resnext101_32x8d(pretrained=True) 89 | modules = list(resnet_net.children())[:-1] 90 | ft_backbone = nn.Sequential(*modules) 91 | ft_backbone.out_channels = 2048 92 | # print(ft_model) 93 | 94 | else: 95 | print("Error Wrong unsupported Backbone") 96 | return 97 | 98 | ft_mean = [0.485, 0.456, 0.406] 99 | ft_std = [0.229, 0.224, 0.225] 100 | 101 | ft_anchor_generator = AnchorGenerator( 102 | sizes=((32, 64, 128)), aspect_ratios=((0.5, 1.0, 2.0)) 103 | ) 104 | ft_roi_pooler = torchvision.ops.MultiScaleRoIAlign( 105 | featmap_names=[0], output_size=7, sampling_ratio=2 106 | ) 107 | 108 | ft_model = FasterRCNN( 109 | backbone=ft_backbone, 110 | num_classes=num_classes, 111 | # min_size=ft_min_size, 112 | # max_size=ft_max_size, 113 | image_mean=ft_mean, 114 | image_std=ft_std, 115 | ) 116 | # rpn_anchor_generator=ft_anchor_generator, 117 | # box_roi_pool=ft_roi_pooler) 118 | 119 | return ft_model 120 | -------------------------------------------------------------------------------- /pytorch_fasterrcnn/train.py: -------------------------------------------------------------------------------- 1 | import dataset 2 | import utils 3 | from pprint import pprint 4 | import config 5 | from torchvision import transforms as T 6 | import pandas as pd 7 | import model 8 | import engine 9 | import numpy as np 10 | import torch 11 | import torch.optim as optim 12 | from torch.utils.data import DataLoader, Dataset 13 | 14 | 15 | def run(): 16 | device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") 17 | 18 | train_df = pd.read_csv(config.TRAIN_CSV_PATH) 19 | valid_df = pd.read_csv(config.VALIDATION_CSV_PATH) 20 | 21 | train_dataset = dataset.detection_dataset( 22 | train_df, 23 | config.IMAGE_DIR, 24 | target=config.TARGET_COL, 25 | train=True, 26 | transforms=T.Compose([T.ToTensor()]), 27 | ) 28 | 29 | valid_dataset = dataset.detection_dataset( 30 | valid_df, 31 | config.IMAGE_DIR, 32 | target=config.TARGET_COL, 33 | train=True, 34 | transforms=T.Compose([T.ToTensor()]), 35 | ) 36 | 37 | # print(train_dataset) 38 | 39 | train_dataloader = DataLoader( 40 | train_dataset, 41 | batch_size=config.TRAIN_BATCH_SIZE, 42 | shuffle=False, 43 | collate_fn=utils.collate_fn, 44 | ) 45 | 46 | valid_dataloader = DataLoader( 47 | valid_dataset, 48 | batch_size=config.VALID_BATCH_SIZE, 49 | shuffle=False, 50 | collate_fn=utils.collate_fn, 51 | ) 52 | 53 | print("Data Loaders created") 54 | 55 | detector = model.create_model(config.NUM_CLASSES, backbone=config.BACKBONE) 56 | 57 | params = [p for p in detector.parameters() if p.requires_grad] 58 | optimizer = optim.Adam(params, lr=config.LEARNING_RATE) 59 | # lr_scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.5) 60 | detector.to(device) 61 | 62 | print("Model loaded to device") 63 | 64 | print("---------------- Training Started --------------") 65 | 66 | for epoch in range(config.EPOCHS): 67 | loss_value = engine.train_fn(train_dataloader, detector, optimizer, device) 68 | print("epoch = {}, Training_loss = {}".format(epoch, loss_value)) 69 | # Set the threshold as per needs 70 | results = engine.eval_fn( 71 | valid_dataloader, 72 | detector, 73 | device, 74 | detection_threshold=config.DETECTION_THRESHOLD, 75 | ) 76 | # Pretty printing the results 77 | pprint(results) 78 | 79 | # For now just saving one model. I haven't build evaluation metrics which I will use to save best model. 80 | 81 | # torch.save({ 82 | # 'epoch': epoch, 83 | # 'model_state_dict': detector.state_dict(), 84 | # 'optimizer_state_dict': optimizer.state_dict(), 85 | # 'loss': loss_value, 86 | # }, config.MODEL_SAVE_PATH) 87 | 88 | torch.save(detector.state_dict(), config.MODEL_SAVE_PATH) 89 | print("-" * 25) 90 | print("Model Trained and Saved to Disk") 91 | 92 | # print(train_dataloader) 93 | # images, targets, image_ids = next(iter(train_dataloader)) 94 | # print(images) 95 | 96 | # print(targets) 97 | # print(image_ids) 98 | 99 | 100 | if __name__ == "__main__": 101 | run() 102 | -------------------------------------------------------------------------------- /pytorch_fasterrcnn/utils.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | import torch 4 | import cv2 5 | from collections import defaultdict, deque 6 | import datetime 7 | import pickle 8 | import time 9 | import matplotlib.pyplot as plt 10 | import torch.distributed as dist 11 | import random 12 | import errno 13 | import os 14 | 15 | # My utils 16 | class AverageMeter: 17 | """Computes and stores the average and current value""" 18 | 19 | def __init__(self): 20 | self.reset() 21 | 22 | def reset(self): 23 | self.val = 0 24 | self.avg = 0 25 | self.sum = 0 26 | self.count = 0 27 | 28 | def update(self, val, n=1): 29 | self.val = val 30 | self.sum += val * n 31 | self.count += n 32 | self.avg = self.sum / self.count 33 | 34 | 35 | def show_loader_images(images, targets, device): 36 | images = list(image for image in images) 37 | targets = [{k: v.to(device) for k, v in t.items()} for t in targets] 38 | 39 | boxes = targets[4]["boxes"].cpu().numpy().astype(np.int32) 40 | # Torch takes channels first format we need to change to channels last 41 | sample = images[4].permute(1, 2, 0).cpu().numpy() 42 | 43 | fig, ax = plt.subplots(1, 1, figsize=(16, 8)) 44 | 45 | for box in boxes: 46 | cv2.rectangle(sample, (box[0], box[1]), (box[2], box[3]), (220, 0, 0), 3) 47 | 48 | ax.set_axis_off() 49 | ax.imshow(sample) 50 | 51 | 52 | def random_show_images(root_dir, df, no_images=5, fmt=".jpg"): 53 | 54 | random_image_l = random.sample(range(0, 500), no_images) 55 | # random_image_l = [1, 2, 3] 56 | 57 | for image_id in random_image_l: 58 | 59 | img_path = os.path.join(root_dir, str(image_id)) 60 | img_path += fmt 61 | # print(img_path) 62 | image = cv2.imread(img_path, cv2.IMREAD_COLOR) 63 | image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 64 | print("image no {}".format(image_id)) 65 | # plt.imshow(image) 66 | plt.figure() 67 | plt.axis("off") 68 | 69 | for i, image_name in enumerate(df["image_id"]): 70 | # print(image_name) 71 | if str(image_name) == str(image_id): 72 | # print("yes") 73 | xtl = int(df["xtl"].iloc[i]) 74 | ytl = int(df["ytl"].iloc[i]) 75 | xbr = int(df["xbr"].iloc[i]) 76 | ybr = int(df["ybr"].iloc[i]) 77 | # print(xtl, ytl, xbr, ybr) 78 | has_helmet = str(df["has_helmet"].iloc[i]) + " helmet" 79 | has_mask = str(df["has_mask"].iloc[i]) + " mask" 80 | cv2.rectangle(image, (xtl, ytl), (xbr, ybr), color=(0, 255, 0)) 81 | cv2.putText( 82 | image, 83 | has_helmet, 84 | (xtl, ytl), 85 | cv2.FONT_HERSHEY_SIMPLEX, 86 | 0.5, 87 | (36, 255, 12), 88 | 2, 89 | ) 90 | cv2.putText( 91 | image, 92 | has_mask, 93 | (xbr, ybr), 94 | cv2.FONT_HERSHEY_SIMPLEX, 95 | 0.5, 96 | (36, 255, 12), 97 | 2, 98 | ) 99 | 100 | plt.imshow(image) 101 | 102 | 103 | # Let's get distrigbution stats for our labeled data 104 | def get_distribution_column(df, column): 105 | print(df[column].value_counts()) 106 | df[column].value_counts().sort_values().plot(kind="bar") 107 | 108 | 109 | # Note these utils are taken from 110 | # They are standard boiler plate code that I can use. 111 | # https://github.com/pytorch/vision.git 112 | 113 | 114 | class SmoothedValue(object): 115 | """Track a series of values and provide access to smoothed values over a 116 | window or the global series average. 117 | """ 118 | 119 | def __init__(self, window_size=20, fmt=None): 120 | if fmt is None: 121 | fmt = "{median:.4f} ({global_avg:.4f})" 122 | self.deque = deque(maxlen=window_size) 123 | self.total = 0.0 124 | self.count = 0 125 | self.fmt = fmt 126 | 127 | def update(self, value, n=1): 128 | self.deque.append(value) 129 | self.count += n 130 | self.total += value * n 131 | 132 | def synchronize_between_processes(self): 133 | """ 134 | Warning: does not synchronize the deque! 135 | """ 136 | if not is_dist_avail_and_initialized(): 137 | return 138 | t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda") 139 | dist.barrier() 140 | dist.all_reduce(t) 141 | t = t.tolist() 142 | self.count = int(t[0]) 143 | self.total = t[1] 144 | 145 | @property 146 | def median(self): 147 | d = torch.tensor(list(self.deque)) 148 | return d.median().item() 149 | 150 | @property 151 | def avg(self): 152 | d = torch.tensor(list(self.deque), dtype=torch.float32) 153 | return d.mean().item() 154 | 155 | @property 156 | def global_avg(self): 157 | return self.total / self.count 158 | 159 | @property 160 | def max(self): 161 | return max(self.deque) 162 | 163 | @property 164 | def value(self): 165 | return self.deque[-1] 166 | 167 | def __str__(self): 168 | return self.fmt.format( 169 | median=self.median, 170 | avg=self.avg, 171 | global_avg=self.global_avg, 172 | max=self.max, 173 | value=self.value, 174 | ) 175 | 176 | 177 | def all_gather(data): 178 | """ 179 | Run all_gather on arbitrary picklable data (not necessarily tensors) 180 | Args: 181 | data: any picklable object 182 | Returns: 183 | list[data]: list of data gathered from each rank 184 | """ 185 | world_size = get_world_size() 186 | if world_size == 1: 187 | return [data] 188 | 189 | # serialized to a Tensor 190 | buffer = pickle.dumps(data) 191 | storage = torch.ByteStorage.from_buffer(buffer) 192 | tensor = torch.ByteTensor(storage).to("cuda") 193 | 194 | # obtain Tensor size of each rank 195 | local_size = torch.tensor([tensor.numel()], device="cuda") 196 | size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)] 197 | dist.all_gather(size_list, local_size) 198 | size_list = [int(size.item()) for size in size_list] 199 | max_size = max(size_list) 200 | 201 | # receiving Tensor from all ranks 202 | # we pad the tensor because torch all_gather does not support 203 | # gathering tensors of different shapes 204 | tensor_list = [] 205 | for _ in size_list: 206 | tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device="cuda")) 207 | if local_size != max_size: 208 | padding = torch.empty( 209 | size=(max_size - local_size,), dtype=torch.uint8, device="cuda" 210 | ) 211 | tensor = torch.cat((tensor, padding), dim=0) 212 | dist.all_gather(tensor_list, tensor) 213 | 214 | data_list = [] 215 | for size, tensor in zip(size_list, tensor_list): 216 | buffer = tensor.cpu().numpy().tobytes()[:size] 217 | data_list.append(pickle.loads(buffer)) 218 | 219 | return data_list 220 | 221 | 222 | def reduce_dict(input_dict, average=True): 223 | """ 224 | Args: 225 | input_dict (dict): all the values will be reduced 226 | average (bool): whether to do average or sum 227 | Reduce the values in the dictionary from all processes so that all processes 228 | have the averaged results. Returns a dict with the same fields as 229 | input_dict, after reduction. 230 | """ 231 | world_size = get_world_size() 232 | if world_size < 2: 233 | return input_dict 234 | with torch.no_grad(): 235 | names = [] 236 | values = [] 237 | # sort the keys so that they are consistent across processes 238 | for k in sorted(input_dict.keys()): 239 | names.append(k) 240 | values.append(input_dict[k]) 241 | values = torch.stack(values, dim=0) 242 | dist.all_reduce(values) 243 | if average: 244 | values /= world_size 245 | reduced_dict = {k: v for k, v in zip(names, values)} 246 | return reduced_dict 247 | 248 | 249 | class MetricLogger(object): 250 | def __init__(self, delimiter="\t"): 251 | self.meters = defaultdict(SmoothedValue) 252 | self.delimiter = delimiter 253 | 254 | def update(self, **kwargs): 255 | for k, v in kwargs.items(): 256 | if isinstance(v, torch.Tensor): 257 | v = v.item() 258 | assert isinstance(v, (float, int)) 259 | self.meters[k].update(v) 260 | 261 | def __getattr__(self, attr): 262 | if attr in self.meters: 263 | return self.meters[attr] 264 | if attr in self.__dict__: 265 | return self.__dict__[attr] 266 | raise AttributeError( 267 | "'{}' object has no attribute '{}'".format(type(self).__name__, attr) 268 | ) 269 | 270 | def __str__(self): 271 | loss_str = [] 272 | for name, meter in self.meters.items(): 273 | loss_str.append("{}: {}".format(name, str(meter))) 274 | return self.delimiter.join(loss_str) 275 | 276 | def synchronize_between_processes(self): 277 | for meter in self.meters.values(): 278 | meter.synchronize_between_processes() 279 | 280 | def add_meter(self, name, meter): 281 | self.meters[name] = meter 282 | 283 | def log_every(self, iterable, print_freq, header=None): 284 | i = 0 285 | if not header: 286 | header = "" 287 | start_time = time.time() 288 | end = time.time() 289 | iter_time = SmoothedValue(fmt="{avg:.4f}") 290 | data_time = SmoothedValue(fmt="{avg:.4f}") 291 | space_fmt = ":" + str(len(str(len(iterable)))) + "d" 292 | log_msg = self.delimiter.join( 293 | [ 294 | header, 295 | "[{0" + space_fmt + "}/{1}]", 296 | "eta: {eta}", 297 | "{meters}", 298 | "time: {time}", 299 | "data: {data}", 300 | "max mem: {memory:.0f}", 301 | ] 302 | ) 303 | MB = 1024.0 * 1024.0 304 | for obj in iterable: 305 | data_time.update(time.time() - end) 306 | yield obj 307 | iter_time.update(time.time() - end) 308 | if i % print_freq == 0 or i == len(iterable) - 1: 309 | eta_seconds = iter_time.global_avg * (len(iterable) - i) 310 | eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) 311 | print( 312 | log_msg.format( 313 | i, 314 | len(iterable), 315 | eta=eta_string, 316 | meters=str(self), 317 | time=str(iter_time), 318 | data=str(data_time), 319 | memory=torch.cuda.max_memory_allocated() / MB, 320 | ) 321 | ) 322 | i += 1 323 | end = time.time() 324 | total_time = time.time() - start_time 325 | total_time_str = str(datetime.timedelta(seconds=int(total_time))) 326 | print( 327 | "{} Total time: {} ({:.4f} s / it)".format( 328 | header, total_time_str, total_time / len(iterable) 329 | ) 330 | ) 331 | 332 | 333 | def collate_fn(batch): 334 | return tuple(zip(*batch)) 335 | 336 | 337 | def warmup_lr_scheduler(optimizer, warmup_iters, warmup_factor): 338 | def f(x): 339 | if x >= warmup_iters: 340 | return 1 341 | alpha = float(x) / warmup_iters 342 | return warmup_factor * (1 - alpha) + alpha 343 | 344 | return torch.optim.lr_scheduler.LambdaLR(optimizer, f) 345 | 346 | 347 | def mkdir(path): 348 | try: 349 | os.makedirs(path) 350 | except OSError as e: 351 | if e.errno != errno.EEXIST: 352 | raise 353 | 354 | 355 | def setup_for_distributed(is_master): 356 | """ 357 | This function disables printing when not in master process 358 | """ 359 | import builtins as __builtin__ 360 | 361 | builtin_print = __builtin__.print 362 | 363 | def print(*args, **kwargs): 364 | force = kwargs.pop("force", False) 365 | if is_master or force: 366 | builtin_print(*args, **kwargs) 367 | 368 | __builtin__.print = print 369 | 370 | 371 | def is_dist_avail_and_initialized(): 372 | if not dist.is_available(): 373 | return False 374 | if not dist.is_initialized(): 375 | return False 376 | return True 377 | 378 | 379 | def get_world_size(): 380 | if not is_dist_avail_and_initialized(): 381 | return 1 382 | return dist.get_world_size() 383 | 384 | 385 | def get_rank(): 386 | if not is_dist_avail_and_initialized(): 387 | return 0 388 | return dist.get_rank() 389 | 390 | 391 | def is_main_process(): 392 | return get_rank() == 0 393 | 394 | 395 | def save_on_master(*args, **kwargs): 396 | if is_main_process(): 397 | torch.save(*args, **kwargs) 398 | 399 | 400 | def init_distributed_mode(args): 401 | if "RANK" in os.environ and "WORLD_SIZE" in os.environ: 402 | args.rank = int(os.environ["RANK"]) 403 | args.world_size = int(os.environ["WORLD_SIZE"]) 404 | args.gpu = int(os.environ["LOCAL_RANK"]) 405 | elif "SLURM_PROCID" in os.environ: 406 | args.rank = int(os.environ["SLURM_PROCID"]) 407 | args.gpu = args.rank % torch.cuda.device_count() 408 | else: 409 | print("Not using distributed mode") 410 | args.distributed = False 411 | return 412 | 413 | args.distributed = True 414 | 415 | torch.cuda.set_device(args.gpu) 416 | args.dist_backend = "nccl" 417 | print( 418 | "| distributed init (rank {}): {}".format(args.rank, args.dist_url), flush=True 419 | ) 420 | torch.distributed.init_process_group( 421 | backend=args.dist_backend, 422 | init_method=args.dist_url, 423 | world_size=args.world_size, 424 | rank=args.rank, 425 | ) 426 | torch.distributed.barrier() 427 | setup_for_distributed(args.rank == 0) 428 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/pytorch_fasterrcnn/bd1bec1ddad605d500406b15e76864e10a91062b/requirements-dev.txt -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/pytorch_fasterrcnn/bd1bec1ddad605d500406b15e76864e10a91062b/requirements.txt -------------------------------------------------------------------------------- /settings.ini: -------------------------------------------------------------------------------- 1 | [DEFAULT] 2 | # All sections below are required unless otherwise specified 3 | host = github 4 | lib_name = pytorch_fasterrcnn 5 | # For Enterprise Git add variable repo_name and company name 6 | # repo_name = analytics 7 | # company_name = nike 8 | 9 | user = oke-aditya 10 | description = Torchvision Faster RCNN Fine Tuner 11 | keywords = Python 12 | author = Aditya Oke 13 | author_email = okeaditya315@gmail.com 14 | copyright = Aditya Oke 15 | branch = master 16 | version = 0.2.1 17 | min_python = 3.6 18 | audience = Developers 19 | language = English 20 | # Set to True if you want to create a more fancy sidebar.json than the default 21 | custom_sidebar = False 22 | # Add licenses and see current list in `setup.py` 23 | license = apache2 24 | # From 1-7: Planning Pre-Alpha Alpha Beta Production Mature Inactive 25 | status = 4 26 | 27 | # Optional. Same format as setuptools requirements 28 | requirements = numpy 29 | # Optional. Same format as setuptools console_scripts 30 | # console_scripts = 31 | # Optional. Same format as setuptools dependency-links 32 | # dep_links = 33 | 34 | ### 35 | # You probably won't need to change anything under here, 36 | # unless you have some special requirements 37 | ### 38 | 39 | # Change to, e.g. "nbs", to put your notebooks in nbs dir instead of repo root 40 | ; nbs_path = nbs 41 | ; doc_path = docs 42 | 43 | # Anything shown as '%(...)s' is substituted with that setting automatically 44 | ; doc_host = https://%(user)s.github.io 45 | #For Enterprise Git pages use: 46 | #doc_host = https://pages.github.%(company_name)s.com. 47 | 48 | 49 | ; doc_baseurl = /%(lib_name)s/ 50 | # For Enterprise Github pages docs use: 51 | # doc_baseurl = /%(repo_name)s/%(lib_name)s/ 52 | 53 | git_url = https://github.com/%(user)s/%(lib_name)s/tree/%(branch)s/ 54 | # For Enterprise Github use: 55 | #git_url = https://github.%(company_name)s.com/%(repo_name)s/%(lib_name)s/tree/%(branch)s/ 56 | 57 | 58 | 59 | lib_path = %(lib_name)s 60 | title = %(lib_name)s 61 | 62 | #Optional advanced parameters 63 | #Monospace docstings: adds
 tags around the doc strings, preserving newlines/indentation.
64 | #monospace_docstrings = False
65 | #Test flags: introduce here the test flags you want to use separated by |
66 | #tst_flags =
67 | #Custom sidebar: customize sidebar.json yourself for advanced sidebars (False/True)
68 | #custom_sidebar =
69 | #Cell spacing: if you want cell blocks in code separated by more than one new line
70 | #cell_spacing =
71 | #Custom jekyll styles: if you want more jekyll styles than tip/important/warning, set them here
72 | #jekyll_styles = note,warning,tip,important
73 | 


--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
 1 | from pkg_resources import parse_version
 2 | from configparser import ConfigParser
 3 | import setuptools
 4 | 
 5 | assert parse_version(setuptools.__version__) >= parse_version("36.2")
 6 | 
 7 | # note: all settings are in settings.ini; edit there, not here
 8 | config = ConfigParser(delimiters=["="])
 9 | config.read("settings.ini")
10 | cfg = config["DEFAULT"]
11 | 
12 | cfg_keys = "version description keywords author author_email".split()
13 | expected = (
14 |     cfg_keys
15 |     + "lib_name user branch license status min_python audience language".split()
16 | )
17 | for o in expected:
18 |     assert o in cfg, "missing expected setting: {}".format(o)
19 | setup_cfg = {o: cfg[o] for o in cfg_keys}
20 | 
21 | licenses = {
22 |     "apache2": (
23 |         "Apache Software License 2.0",
24 |         "OSI Approved :: Apache Software License",
25 |     ),
26 | }
27 | statuses = [
28 |     "1 - Planning",
29 |     "2 - Pre-Alpha",
30 |     "3 - Alpha",
31 |     "4 - Beta",
32 |     "5 - Production/Stable",
33 |     "6 - Mature",
34 |     "7 - Inactive",
35 | ]
36 | py_versions = (
37 |     "2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 3.0 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8".split()
38 | )
39 | 
40 | requirements = cfg.get("requirements", "").split()
41 | lic = licenses[cfg["license"]]
42 | min_python = cfg["min_python"]
43 | 
44 | setuptools.setup(
45 |     name=cfg["lib_name"],
46 |     license=lic[0],
47 |     classifiers=[
48 |         "Development Status :: " + statuses[int(cfg["status"])],
49 |         "Intended Audience :: " + cfg["audience"].title(),
50 |         "License :: " + lic[1],
51 |         "Natural Language :: " + cfg["language"].title(),
52 |     ]
53 |     + [
54 |         "Programming Language :: Python :: " + o
55 |         for o in py_versions[py_versions.index(min_python) :]
56 |     ],
57 |     url=cfg["git_url"],
58 |     packages=setuptools.find_packages(),
59 |     include_package_data=True,
60 |     install_requires=requirements,
61 |     dependency_links=cfg.get("dep_links", "").split(),
62 |     python_requires=">=" + cfg["min_python"],
63 |     long_description=open("README.md", encoding="utf-8", errors="ignore").read(),
64 |     long_description_content_type="text/markdown",
65 |     zip_safe=False,
66 |     entry_points={"console_scripts": cfg.get("console_scripts", "").split()},
67 |     **setup_cfg
68 | )
69 | 


--------------------------------------------------------------------------------
/setup.sh:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oke-aditya/pytorch_fasterrcnn/bd1bec1ddad605d500406b15e76864e10a91062b/setup.sh


--------------------------------------------------------------------------------
/tests/README.md:
--------------------------------------------------------------------------------
1 | # Tests
2 | 
3 | - These tests are automatically triggered by the CI
4 | 


--------------------------------------------------------------------------------
/tests/test_hello.py:
--------------------------------------------------------------------------------
1 | # Write your tests here
2 | 
3 | 
4 | def test_simple():
5 |     print("Hello World")
6 |     return 1
7 | 


--------------------------------------------------------------------------------