├── .github └── workflows │ ├── build.yml │ └── lint.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .pre-commit-hooks.yaml ├── LICENSE ├── README.md ├── pre_commit_hooks ├── __init__.py ├── check_algo_readme.py ├── check_copyright.py ├── check_ecosystem_validity.py ├── remove_eol_characters.py └── say_hello.py ├── setup.cfg ├── setup.py └── tests ├── __init__.py ├── data ├── contain_copyright │ ├── test-cpp.cpp │ └── test-py.py ├── exclude │ └── test-exclude.py ├── test-cpp.cpp ├── test-cu.cu ├── test-cuh.cuh ├── test-h.h ├── test-hpp.hpp └── test-py.py ├── test-ecosystem-validity.yaml ├── test_copyright.py ├── test_ecosystem_validity.py └── test_remove_eol_characters.py /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: [push, pull_request] 4 | 5 | concurrency: 6 | group: ${{ github.workflow }}-${{ github.ref }} 7 | cancel-in-progress: true 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | - name: Set up Python 3.7 15 | uses: actions/setup-python@v2 16 | with: 17 | python-version: 3.7 18 | - name: unit-test 19 | run: | 20 | pip install cerberus pytest PyYAML 21 | pytest tests/ 22 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: lint 2 | 3 | on: [push, pull_request] 4 | 5 | concurrency: 6 | group: ${{ github.workflow }}-${{ github.ref }} 7 | cancel-in-progress: true 8 | 9 | jobs: 10 | lint: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | - name: Set up Python 3.7 15 | uses: actions/setup-python@v2 16 | with: 17 | python-version: 3.7 18 | - name: Install pre-commit hook 19 | run: | 20 | pip install pre-commit 21 | pre-commit install 22 | - name: Linting 23 | run: pre-commit run --all-files 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 98 | __pypackages__/ 99 | 100 | # Celery stuff 101 | celerybeat-schedule 102 | celerybeat.pid 103 | 104 | # SageMath parsed files 105 | *.sage.py 106 | 107 | # Environments 108 | .env 109 | .venv 110 | env/ 111 | venv/ 112 | ENV/ 113 | env.bak/ 114 | venv.bak/ 115 | 116 | # Spyder project settings 117 | .spyderproject 118 | .spyproject 119 | 120 | # Rope project settings 121 | .ropeproject 122 | 123 | # mkdocs documentation 124 | /site 125 | 126 | # mypy 127 | .mypy_cache/ 128 | .dmypy.json 129 | dmypy.json 130 | 131 | # Pyre type checker 132 | .pyre/ 133 | 134 | # pytype static type analyzer 135 | .pytype/ 136 | 137 | # Cython debug symbols 138 | cython_debug/ 139 | 140 | # 141 | .vscode 142 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/PyCQA/flake8 3 | rev: 5.0.4 4 | hooks: 5 | - id: flake8 6 | - repo: https://github.com/PyCQA/isort 7 | rev: 5.11.5 8 | hooks: 9 | - id: isort 10 | - repo: https://github.com/pre-commit/mirrors-yapf 11 | rev: v0.32.0 12 | hooks: 13 | - id: yapf 14 | - repo: https://github.com/pre-commit/pre-commit-hooks 15 | rev: v4.3.0 16 | hooks: 17 | - id: trailing-whitespace 18 | - id: check-yaml 19 | - id: end-of-file-fixer 20 | - id: requirements-txt-fixer 21 | - id: double-quote-string-fixer 22 | - id: check-merge-conflict 23 | - id: fix-encoding-pragma 24 | args: ["--remove"] 25 | - id: mixed-line-ending 26 | args: ["--fix=lf"] 27 | - repo: https://github.com/codespell-project/codespell 28 | rev: v2.2.1 29 | hooks: 30 | - id: codespell 31 | - repo: https://github.com/executablebooks/mdformat 32 | rev: 0.7.9 33 | hooks: 34 | - id: mdformat 35 | args: ["--number"] 36 | additional_dependencies: 37 | - mdformat-openmmlab 38 | - mdformat_frontmatter 39 | - linkify-it-py 40 | - repo: https://github.com/myint/docformatter 41 | rev: v1.3.1 42 | hooks: 43 | - id: docformatter 44 | args: ["--in-place", "--wrap-descriptions", "79"] 45 | - repo: https://github.com/asottile/pyupgrade 46 | rev: v2.32.1 47 | hooks: 48 | - id: pyupgrade 49 | args: ["--py36-plus"] 50 | -------------------------------------------------------------------------------- /.pre-commit-hooks.yaml: -------------------------------------------------------------------------------- 1 | # a git repo containing pre-commit plugins must contain a 2 | # .pre-commit-hooks.yaml file that tells pre-commit which hooks are provided 3 | # more details at https://pre-commit.com/#creating-new-hooks 4 | 5 | - id: say-hello 6 | name: say hello 7 | description: a template to show how to implement a pre-commit hook 8 | language: python 9 | entry: say-hello 10 | require_serial: true 11 | pass_filenames: false 12 | args: ['OpenMMLab'] 13 | 14 | - id: check-algo-readme 15 | name: check algorithm readme 16 | description: check whether the abstract and icon exist in the algorithm readme 17 | language: python 18 | entry: check-algo-readme 19 | require_serial: true 20 | pass_filenames: false 21 | 22 | - id: check-copyright 23 | name: check copyright 24 | description: check whether the code contains copyright 25 | language: python 26 | entry: check-copyright 27 | require_serial: true 28 | pass_filenames: false 29 | 30 | - id: check-ecosystem-validity 31 | name: check ecosystem validity 32 | description: check validity of yaml 33 | language: python 34 | entry: check-ecosystem-validity 35 | types: [yaml] 36 | require_serial: false 37 | pass_filenames: false 38 | additional_dependencies: 39 | - cerberus 40 | 41 | - id: remove-improper-eol-in-cn-docs 42 | name: remove improper eol in cn docs 43 | description: Remove the end_of_line characters that split natural paragraphs in Chinese docs 44 | entry: remove-eol-characters 45 | language: python 46 | files: .*\.md$ 47 | pass_filenames: true 48 | require_serial: true 49 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) OpenMMLab. All rights reserved 2 | 3 | Apache License 4 | Version 2.0, January 2004 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, 12 | and distribution as defined by Sections 1 through 9 of this document. 13 | 14 | "Licensor" shall mean the copyright owner or entity authorized by 15 | the copyright owner that is granting the License. 16 | 17 | "Legal Entity" shall mean the union of the acting entity and all 18 | other entities that control, are controlled by, or are under common 19 | control with that entity. For the purposes of this definition, 20 | "control" means (i) the power, direct or indirect, to cause the 21 | direction or management of such entity, whether by contract or 22 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 23 | outstanding shares, or (iii) beneficial ownership of such entity. 24 | 25 | "You" (or "Your") shall mean an individual or Legal Entity 26 | exercising permissions granted by this License. 27 | 28 | "Source" form shall mean the preferred form for making modifications, 29 | including but not limited to software source code, documentation 30 | source, and configuration files. 31 | 32 | "Object" form shall mean any form resulting from mechanical 33 | transformation or translation of a Source form, including but 34 | not limited to compiled object code, generated documentation, 35 | and conversions to other media types. 36 | 37 | "Work" shall mean the work of authorship, whether in Source or 38 | Object form, made available under the License, as indicated by a 39 | copyright notice that is included in or attached to the work 40 | (an example is provided in the Appendix below). 41 | 42 | "Derivative Works" shall mean any work, whether in Source or Object 43 | form, that is based on (or derived from) the Work and for which the 44 | editorial revisions, annotations, elaborations, or other modifications 45 | represent, as a whole, an original work of authorship. For the purposes 46 | of this License, Derivative Works shall not include works that remain 47 | separable from, or merely link (or bind by name) to the interfaces of, 48 | the Work and Derivative Works thereof. 49 | 50 | "Contribution" shall mean any work of authorship, including 51 | the original version of the Work and any modifications or additions 52 | to that Work or Derivative Works thereof, that is intentionally 53 | submitted to Licensor for inclusion in the Work by the copyright owner 54 | or by an individual or Legal Entity authorized to submit on behalf of 55 | the copyright owner. For the purposes of this definition, "submitted" 56 | means any form of electronic, verbal, or written communication sent 57 | to the Licensor or its representatives, including but not limited to 58 | communication on electronic mailing lists, source code control systems, 59 | and issue tracking systems that are managed by, or on behalf of, the 60 | Licensor for the purpose of discussing and improving the Work, but 61 | excluding communication that is conspicuously marked or otherwise 62 | designated in writing by the copyright owner as "Not a Contribution." 63 | 64 | "Contributor" shall mean Licensor and any individual or Legal Entity 65 | on behalf of whom a Contribution has been received by Licensor and 66 | subsequently incorporated within the Work. 67 | 68 | 2. Grant of Copyright License. Subject to the terms and conditions of 69 | this License, each Contributor hereby grants to You a perpetual, 70 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 71 | copyright license to reproduce, prepare Derivative Works of, 72 | publicly display, publicly perform, sublicense, and distribute the 73 | Work and such Derivative Works in Source or Object form. 74 | 75 | 3. Grant of Patent License. Subject to the terms and conditions of 76 | this License, each Contributor hereby grants to You a perpetual, 77 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 78 | (except as stated in this section) patent license to make, have made, 79 | use, offer to sell, sell, import, and otherwise transfer the Work, 80 | where such license applies only to those patent claims licensable 81 | by such Contributor that are necessarily infringed by their 82 | Contribution(s) alone or by combination of their Contribution(s) 83 | with the Work to which such Contribution(s) was submitted. If You 84 | institute patent litigation against any entity (including a 85 | cross-claim or counterclaim in a lawsuit) alleging that the Work 86 | or a Contribution incorporated within the Work constitutes direct 87 | or contributory patent infringement, then any patent licenses 88 | granted to You under this License for that Work shall terminate 89 | as of the date such litigation is filed. 90 | 91 | 4. Redistribution. You may reproduce and distribute copies of the 92 | Work or Derivative Works thereof in any medium, with or without 93 | modifications, and in Source or Object form, provided that You 94 | meet the following conditions: 95 | 96 | (a) You must give any other recipients of the Work or 97 | Derivative Works a copy of this License; and 98 | 99 | (b) You must cause any modified files to carry prominent notices 100 | stating that You changed the files; and 101 | 102 | (c) You must retain, in the Source form of any Derivative Works 103 | that You distribute, all copyright, patent, trademark, and 104 | attribution notices from the Source form of the Work, 105 | excluding those notices that do not pertain to any part of 106 | the Derivative Works; and 107 | 108 | (d) If the Work includes a "NOTICE" text file as part of its 109 | distribution, then any Derivative Works that You distribute must 110 | include a readable copy of the attribution notices contained 111 | within such NOTICE file, excluding those notices that do not 112 | pertain to any part of the Derivative Works, in at least one 113 | of the following places: within a NOTICE text file distributed 114 | as part of the Derivative Works; within the Source form or 115 | documentation, if provided along with the Derivative Works; or, 116 | within a display generated by the Derivative Works, if and 117 | wherever such third-party notices normally appear. The contents 118 | of the NOTICE file are for informational purposes only and 119 | do not modify the License. You may add Your own attribution 120 | notices within Derivative Works that You distribute, alongside 121 | or as an addendum to the NOTICE text from the Work, provided 122 | that such additional attribution notices cannot be construed 123 | as modifying the License. 124 | 125 | You may add Your own copyright statement to Your modifications and 126 | may provide additional or different license terms and conditions 127 | for use, reproduction, or distribution of Your modifications, or 128 | for any such Derivative Works as a whole, provided Your use, 129 | reproduction, and distribution of the Work otherwise complies with 130 | the conditions stated in this License. 131 | 132 | 5. Submission of Contributions. Unless You explicitly state otherwise, 133 | any Contribution intentionally submitted for inclusion in the Work 134 | by You to the Licensor shall be under the terms and conditions of 135 | this License, without any additional terms or conditions. 136 | Notwithstanding the above, nothing herein shall supersede or modify 137 | the terms of any separate license agreement you may have executed 138 | with Licensor regarding such Contributions. 139 | 140 | 6. Trademarks. This License does not grant permission to use the trade 141 | names, trademarks, service marks, or product names of the Licensor, 142 | except as required for reasonable and customary use in describing the 143 | origin of the Work and reproducing the content of the NOTICE file. 144 | 145 | 7. Disclaimer of Warranty. Unless required by applicable law or 146 | agreed to in writing, Licensor provides the Work (and each 147 | Contributor provides its Contributions) on an "AS IS" BASIS, 148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 149 | implied, including, without limitation, any warranties or conditions 150 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 151 | PARTICULAR PURPOSE. You are solely responsible for determining the 152 | appropriateness of using or redistributing the Work and assume any 153 | risks associated with Your exercise of permissions under this License. 154 | 155 | 8. Limitation of Liability. In no event and under no legal theory, 156 | whether in tort (including negligence), contract, or otherwise, 157 | unless required by applicable law (such as deliberate and grossly 158 | negligent acts) or agreed to in writing, shall any Contributor be 159 | liable to You for damages, including any direct, indirect, special, 160 | incidental, or consequential damages of any character arising as a 161 | result of this License or out of the use or inability to use the 162 | Work (including but not limited to damages for loss of goodwill, 163 | work stoppage, computer failure or malfunction, or any and all 164 | other commercial damages or losses), even if such Contributor 165 | has been advised of the possibility of such damages. 166 | 167 | 9. Accepting Warranty or Additional Liability. While redistributing 168 | the Work or Derivative Works thereof, You may choose to offer, 169 | and charge a fee for, acceptance of support, warranty, indemnity, 170 | or other liability obligations and/or rights consistent with this 171 | License. However, in accepting such obligations, You may act only 172 | on Your own behalf and on Your sole responsibility, not on behalf 173 | of any other Contributor, and only if You agree to indemnify, 174 | defend, and hold each Contributor harmless for any liability 175 | incurred by, or claims asserted against, such Contributor by reason 176 | of your accepting any such warranty or additional liability. 177 | 178 | END OF TERMS AND CONDITIONS 179 | 180 | APPENDIX: How to apply the Apache License to your work. 181 | 182 | To apply the Apache License to your work, attach the following 183 | boilerplate notice, with the fields enclosed by brackets "[]" 184 | replaced with your own identifying information. (Don't include 185 | the brackets!) The text should be enclosed in the appropriate 186 | comment syntax for the file format. We also recommend that a 187 | file or class name and description of purpose be included on the 188 | same "printed page" as the copyright notice for easier 189 | identification within third-party archives. 190 | 191 | Copyright 2018-2020 Open-MMLab. All rights reserved. 192 | 193 | Licensed under the Apache License, Version 2.0 (the "License"); 194 | you may not use this file except in compliance with the License. 195 | You may obtain a copy of the License at 196 | 197 | http://www.apache.org/licenses/LICENSE-2.0 198 | 199 | Unless required by applicable law or agreed to in writing, software 200 | distributed under the License is distributed on an "AS IS" BASIS, 201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 202 | See the License for the specific language governing permissions and 203 | limitations under the License. 204 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pre-commit-hooks 2 | 3 | Some pre-commit hooks for OpenMMLab projects. 4 | 5 | ## Using pre-commit-hooks with pre-commit 6 | 7 | Add this to your `.pre-commit-config.yaml` 8 | 9 | ```yaml 10 | - repo: https://github.com/open-mmlab/pre-commit-hooks 11 | rev: v0.4.1 # Use the ref you want to point at 12 | hooks: 13 | - id: check-algo-readme 14 | - id: check-copyright 15 | args: ["dir_to_check"] # replace the dir_to_check with your expected directory to check 16 | - id: check-ecosystem-validity 17 | args: [projects_index.yaml] 18 | additional_dependencies: 19 | - cerberus 20 | - id: remove-improper-eol-in-cn-docs 21 | ``` 22 | 23 | ## Hooks available 24 | 25 | ### say-hello 26 | 27 | A template to show how to implement a pre-commit hook 28 | 29 | ### check-algo-readme 30 | 31 | Check whether the abstract and icon exist in the algorithm readme. 32 | 33 | - `--debug` - print details of abstract and icon in dict format. 34 | - `--dry-run` - just dry run, igonre failed use case. 35 | - `--model-index ${MODEL_INDEX}` - custom model-index file path. 36 | 37 | ### check-copyright 38 | 39 | Check whether the code contains copyright 40 | 41 | - `includes` - directory to add copyright. 42 | - `--excludes` - exclude directory. 43 | - `--suffixes` - copyright will be added to files with suffix. 44 | - `--ignore-file-not-found-error` - Whether to ignore `FileNotFoundError` when some directories are specified to add copyright but they are not found. 45 | 46 | ### check-ecosystem-validity 47 | 48 | Check the validity of the ecosystem yaml file 49 | 50 | - `filename` - path of the project yaml 51 | 52 | ```yaml 53 | - repo: https://github.com/open-mmlab/pre-commit-hooks 54 | rev: v0.4.1 55 | hooks: 56 | - id: check-ecosystem-validity 57 | args: [projects_index.yaml] 58 | additional_dependencies: 59 | - cerberus 60 | ``` 61 | 62 | ### remove-improper-eol-in-cn-docs 63 | 64 | Remove end-of-line characters that split natural paragraphs in Chinese docs. 65 | 66 | This helps resolve extra whitespaces in Chinese Markdown docs described [here](https://stackoverflow.com/questions/8550112/prevent-workaround-browser-converting-n-between-lines-into-space-for-chinese/8551033#8551033), as a long-standing HTML rendering issue. For example, 67 | 68 | > 这是一个, 69 | > 像诗一样的 70 | > 测试 71 | 72 | will be changed to: 73 | 74 | > 这是一个,像诗一样的测试 75 | 76 | Usage: 77 | 78 | ```yaml 79 | - repo: https://github.com/open-mmlab/pre-commit-hooks 80 | rev: v0.4.1 81 | hooks: 82 | - id: remove-improper-eol-in-cn-docs 83 | ``` 84 | -------------------------------------------------------------------------------- /pre_commit_hooks/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/open-mmlab/pre-commit-hooks/a6b12ce1472d34b72a8b269f6aed7744c7d30375/pre_commit_hooks/__init__.py -------------------------------------------------------------------------------- /pre_commit_hooks/check_algo_readme.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os.path as osp 3 | import pprint 4 | import re 5 | from typing import Tuple 6 | 7 | import yaml 8 | 9 | type_matcher = r'.*.*' 10 | type_pattern = re.compile(type_matcher) 11 | 12 | abstract_start_matcher = r'^## Abstract$' 13 | abstract_start_pattern = re.compile(abstract_start_matcher) 14 | 15 | skip_matcher = r'^## .*' 16 | skip_pattern = re.compile(skip_matcher) 17 | 18 | 19 | def extract_abstract(readme_path: str) -> Tuple[str, str]: 20 | """Check algorithm type and abstract. 21 | 22 | It will traverse the readme document and match by line. If all matched, it 23 | will jump out of traversal. 24 | """ 25 | 26 | algorithm_type = False 27 | abstract = '' 28 | 29 | abstract_found = False 30 | # only search abstract under the heading of `## Abstract`, 31 | # ignore other headings. 32 | skip_abstract_search = False 33 | if osp.exists(readme_path): 34 | with open(readme_path, encoding='utf-8') as f: 35 | for line in f: 36 | if line.strip() == '': 37 | continue 38 | 39 | if algorithm_type and (abstract or skip_abstract_search): 40 | break 41 | 42 | if not algorithm_type and type_pattern.match(line): 43 | algorithm_type = True 44 | 45 | if skip_abstract_search: 46 | continue 47 | 48 | if abstract_found: 49 | if skip_pattern.match(line): 50 | skip_abstract_search = True 51 | # filter out comment line 52 | elif not abstract and not line.startswith('" flag from readme, ' 59 | f'please check {readme_path} again.') 60 | 61 | if not abstract: 62 | print('Failed to extract abstract field from readme, ' 63 | f'please check {readme_path} again.') 64 | 65 | return abstract, algorithm_type 66 | 67 | 68 | def handle_collection_name(name: str) -> str: 69 | # handler for mmpose 70 | display_name_pattern = re.compile(r'\[(.*?)\]') 71 | display_name = re.findall(display_name_pattern, name) 72 | if display_name: 73 | name = display_name[0] 74 | 75 | return name 76 | 77 | 78 | def full_filepath(path: str, cur_filepath: str = None) -> str: 79 | if cur_filepath is not None: 80 | dirname = osp.dirname(cur_filepath) 81 | if dirname: 82 | path = osp.join(dirname, path) 83 | 84 | return path 85 | 86 | 87 | def load_any_file(path: str): 88 | 89 | if not osp.exists(path): 90 | print(f'File "{path}" does not exist.') 91 | return None 92 | 93 | with open(path) as f: 94 | raw = yaml.load(f, Loader=yaml.SafeLoader) 95 | 96 | return raw 97 | 98 | 99 | def check_algorithm(model_index_path: str = 'model-index.yml', 100 | debug: bool = False) -> int: 101 | 102 | retv = 0 103 | 104 | # load collections 105 | model_index_data = load_any_file(model_index_path) 106 | 107 | # make sure the input is a dict 108 | if model_index_data is None or not isinstance(model_index_data, dict): 109 | print(f"Expected the file '{model_index_path}' to contain a dict, " 110 | "but it doesn't.") 111 | collections = [] 112 | retv = 1 113 | else: 114 | import_files = model_index_data.get('Import') 115 | 116 | collections = [] 117 | for import_file in import_files: 118 | import_file = full_filepath(import_file, model_index_path) 119 | meta_file_data = load_any_file(import_file) 120 | if meta_file_data: 121 | collection = meta_file_data.get('Collections') 122 | if collection: 123 | collections.extend(collection) 124 | 125 | # set return code 126 | if meta_file_data is None: 127 | retv = 1 128 | 129 | for collection in collections: 130 | name = collection.get('Name') 131 | display_name = handle_collection_name(name) 132 | 133 | readme_path = full_filepath(collection.get('README'), model_index_path) 134 | abstract, algorithm_type = extract_abstract(readme_path) 135 | 136 | if not abstract or not algorithm_type: 137 | retv = 1 138 | 139 | if debug: 140 | pprint.pprint({ 141 | 'name': display_name, 142 | 'readmePath': readme_path, 143 | 'abstract': abstract, 144 | }) 145 | 146 | return retv 147 | 148 | 149 | def main(): 150 | parser = argparse.ArgumentParser(description='Check algorithm readme') 151 | parser.add_argument( 152 | '--model-index', 153 | default='model-index.yml', 154 | help='model-index file path') 155 | parser.add_argument('--dry-run', action='store_true', help='Just dry run') 156 | parser.add_argument( 157 | '--debug', action='store_true', help='Print debug info') 158 | args = parser.parse_args() 159 | 160 | retv = check_algorithm(args.model_index, args.debug) 161 | 162 | if args.dry_run: 163 | return 0 164 | 165 | return retv 166 | 167 | 168 | if __name__ == '__main__': 169 | raise SystemExit(main()) 170 | -------------------------------------------------------------------------------- /pre_commit_hooks/check_copyright.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import os.path as osp 4 | from typing import List 5 | 6 | HEADER = 'Copyright (c) OpenMMLab. All rights reserved.\n' 7 | 8 | HEADER_KEYWORDS = {'Copyright', 'License'} 9 | 10 | 11 | def has_copyright(lines: List[str]) -> bool: 12 | for line in lines: 13 | if not HEADER_KEYWORDS.isdisjoint(set(line.split(' '))): 14 | return True 15 | return False 16 | 17 | 18 | def parse_args(): 19 | parser = argparse.ArgumentParser(description='Add copyright to files') 20 | parser.add_argument( 21 | 'includes', type=str, nargs='+', help='directory to add copyright') 22 | parser.add_argument( 23 | '--excludes', 24 | nargs='*', 25 | type=str, 26 | default=[], 27 | help='excludes directory') 28 | parser.add_argument( 29 | '--suffixes', 30 | nargs='*', 31 | type=str, 32 | default=['.py'], 33 | help='copyright will be added to files with suffixes') 34 | parser.add_argument('--ignore-file-not-found-error', action='store_true') 35 | args = parser.parse_args() 36 | return args 37 | 38 | 39 | def check_args(includes: List[str], 40 | excludes: List[str], 41 | suffixes: List[str], 42 | ignore_file_not_found_error: bool = False): 43 | """Check the correctness of args and format them.""" 44 | 45 | valid_suffixes = {'.py', '.h', '.cpp', '.cu', '.cuh', '.hpp'} 46 | 47 | # remove possible duplication 48 | includes = list(set(includes)) 49 | excludes = list(set(excludes)) 50 | suffixes = list(set(suffixes)) 51 | 52 | # check the correctness and format args 53 | for i, dir in enumerate(includes): 54 | if not osp.exists(dir): 55 | if not ignore_file_not_found_error: 56 | raise FileNotFoundError(f'{dir} can not be found') 57 | else: 58 | includes[i] = osp.abspath(dir) 59 | 60 | for i, dir in enumerate(excludes): 61 | if not osp.exists(dir): 62 | if not ignore_file_not_found_error: 63 | raise FileNotFoundError(f'{dir} can not be found') 64 | else: 65 | excludes[i] = osp.abspath(dir) 66 | 67 | for suffix in suffixes: 68 | if suffix not in valid_suffixes: 69 | raise ValueError( 70 | f'Expected suffixes are {valid_suffixes}, but got {suffix}') 71 | 72 | return includes, excludes, suffixes 73 | 74 | 75 | def get_filepaths(includes: List[str], excludes: List[str], 76 | suffixes: List[str]) -> List[str]: 77 | """Get all file paths that match the args.""" 78 | 79 | filepaths = [] 80 | for include in includes: 81 | for root, _, files in os.walk(include): 82 | is_exclude = False 83 | for exclude in excludes: 84 | if root.startswith(exclude): 85 | is_exclude = True 86 | break 87 | if is_exclude: 88 | continue 89 | else: 90 | for file in files: 91 | _, ext = osp.splitext(file) 92 | if ext in suffixes: 93 | filepath = osp.join(root, file) 94 | filepaths.append(filepath) 95 | return filepaths 96 | 97 | 98 | def check_copyright(includes: List[str], 99 | excludes: List[str], 100 | suffixes: List[str], 101 | ignore_file_not_found_error: bool = False) -> int: 102 | """Add copyright for those files which lack copyright. 103 | 104 | Args: 105 | includes: Directory to add copyright. 106 | excludes: Exclude directory. 107 | suffixes: Copyright will be added to files with suffixes. 108 | ignore_file_not_found_error: Whether to ignore `FileNotFoundError` when 109 | some directories are specified to add copyright but they are not 110 | found. 111 | 112 | returns: 113 | Returns 0 if no file is missing copyright, otherwise returns 1. 114 | """ 115 | rev = 0 116 | fixed_filepaths = [] 117 | try: 118 | includes, excludes, suffixes = check_args(includes, excludes, suffixes, 119 | ignore_file_not_found_error) 120 | except (FileNotFoundError, ValueError) as e: 121 | print(repr(e)) 122 | return 1 123 | else: 124 | filepaths = get_filepaths(includes, excludes, suffixes) 125 | for filepath in filepaths: 126 | with open(filepath, encoding='utf-8') as f: 127 | lines = f.readlines() 128 | if not has_copyright(lines): 129 | fixed_filepaths.append(filepath) 130 | with open(filepath, 'w', encoding='utf-8') as f: 131 | prefix = '# ' if osp.splitext( 132 | filepath)[1] == '.py' else '// ' 133 | f.writelines([prefix + HEADER] + lines) 134 | rev = 1 135 | for filepath in fixed_filepaths: 136 | print(f'Fixed {filepath}') 137 | return rev 138 | 139 | 140 | def main(): 141 | args = parse_args() 142 | return check_copyright(args.includes, args.excludes, args.suffixes, 143 | args.ignore_file_not_found_error) 144 | 145 | 146 | if __name__ == '__main__': 147 | raise SystemExit(main()) 148 | -------------------------------------------------------------------------------- /pre_commit_hooks/check_ecosystem_validity.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import pprint 3 | 4 | import cerberus 5 | import yaml 6 | 7 | VALID_TYPES = [ 8 | 'Official Implementation', 9 | 'Community Implementation', 10 | 'Competition', 11 | 'Library', 12 | 'Service', 13 | 'Tutorial', 14 | 'Demo', 15 | 'Others', 16 | ] 17 | 18 | VALID_MMREPOS = [ 19 | 'MMCV', 'MMClassification', 'MMDetection', 'MMDetection3D', 'MMRotate', 20 | 'MMSegmentation', 'MMOCR', 'MMPose', 'MMHuman3D', 'MMSelfSup', 'MMRazor', 21 | 'MMFewShot', 'MMAction2', 'MMTracking', 'MMFlow', 'MMEditing', 22 | 'MMGeneration', 'MMDeploy', 'MMEngine', 'MMEval', 'MMYOLO' 23 | ] 24 | 25 | 26 | def check_repo_url(field, value, error): 27 | """Check the validity of repo_url.""" 28 | valid_urls = ('https://github.com/', 'https://gitee.com/', 29 | 'https://gitlab.com/') 30 | valid_flag = value.startswith(valid_urls) 31 | if not valid_flag: 32 | error(field, 33 | f'repo_url is invalid, must start with one of {valid_urls}') 34 | 35 | 36 | def check_paper_url(field, value, error): 37 | """Check the validity of paper_url.""" 38 | valid_flag = True if not value else value.startswith('https://') or \ 39 | value.startswith('http://') 40 | if not valid_flag: 41 | error( 42 | field, 'paper_url is invalid, must starts ' 43 | 'with https:// or http://, or leave for empty') 44 | 45 | 46 | def check_tag(field, value, error): 47 | """Check the validity of tag.""" 48 | # check number of tags 49 | if len(value) > 5: 50 | error( 51 | field, 'Please use no more than 5 tags,' 52 | f'current number: {len(value)}') 53 | # check string validity 54 | valid_flag = True 55 | for tag in value: 56 | if ',' in tag: 57 | valid_flag = False 58 | if not valid_flag: 59 | error(field, "',' is not allowed used in tag") 60 | 61 | 62 | def check_project_validity(project_info: dict) -> int: 63 | """Check the validity of one project.""" 64 | ecosystem_schema = { 65 | 'repo_url': { 66 | 'type': 'string', 67 | 'required': True, 68 | 'check_with': check_repo_url 69 | }, 70 | 'paper_url': { 71 | 'type': 'string', 72 | 'required': True, 73 | 'empty': True, # allow to be '' 74 | 'check_with': check_paper_url 75 | }, 76 | 'type': { 77 | 'type': 'string', 78 | 'allowed': VALID_TYPES, 79 | 'required': True, 80 | }, 81 | 'mmrepos': { 82 | 'type': 'list', 83 | 'allowed': VALID_MMREPOS, 84 | 'required': True, 85 | }, 86 | 'tags': { 87 | 'type': 'list', 88 | 'required': True, 89 | 'check_with': check_tag 90 | }, 91 | 'summary': { 92 | 'type': 'dict', 93 | 'required': True, 94 | 'schema': { 95 | 'zh': { 96 | 'type': 'string', 97 | 'required': True 98 | }, 99 | 'en': { 100 | 'type': 'string', 101 | 'required': True 102 | } 103 | } 104 | } 105 | } 106 | validator = cerberus.Validator() 107 | retv = validator.validate(project_info, ecosystem_schema) 108 | if not retv: 109 | prrint_handle = pprint.PrettyPrinter() 110 | prrint_handle.pprint(project_info) 111 | for error in validator._errors: 112 | print(f'Value of {error.document_path} is {error.value}' 113 | f'\n\tconstraint: {error.constraint}\n\trule:{error.info}') 114 | return retv 115 | 116 | 117 | def check_ecosystem_validity(filename: str) -> int: 118 | """Check the validity of the key-value in the ecosystem project yaml. 119 | 120 | Args: 121 | filename: Path of the ecoystem project information 122 | 123 | Returns: 124 | Return 0 if all key and value are valid, otherwise return 1. 125 | """ 126 | retv = 0 127 | 128 | # read the data in yaml 129 | f = open(filename) 130 | projects = yaml.safe_load(f) 131 | # check validity of each project 132 | for project in projects: 133 | if not check_project_validity(project): 134 | retv = 1 135 | 136 | # check with/without repeated projects 137 | projects_dict = {} 138 | for idx, project in enumerate(projects): 139 | curr_repo_url = project['repo_url'] 140 | if not curr_repo_url not in projects_dict.keys(): 141 | retv = 1 142 | print(f"'{curr_repo_url}' is repeated," 143 | ' please search it and remove the repeated items') 144 | projects_dict[curr_repo_url] = {'idx': idx} 145 | 146 | return retv 147 | 148 | 149 | def main(): 150 | parser = argparse.ArgumentParser( 151 | description='Check the validity of the key in ecosystem information') 152 | parser.add_argument('filename', type=str, help='path of the yaml file') 153 | args = parser.parse_args() 154 | 155 | return check_ecosystem_validity(args.filename) 156 | 157 | 158 | if __name__ == '__main__': 159 | raise SystemExit(main()) 160 | -------------------------------------------------------------------------------- /pre_commit_hooks/remove_eol_characters.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | import re 4 | import sys 5 | from typing import List, Tuple 6 | 7 | 8 | def remove_eol() -> Tuple[str, str]: 9 | eol_character = r'\n' 10 | # \u4e00-\u9fff contains all chinese characters 11 | characters = r'\u4e00-\u9fff' 12 | # Unicode halfwidth and fullwidth forms, refer to 13 | # https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_(Unicode_block) 14 | punctuations = r'\uff01-\uff9f' 15 | # Find natural Chinese paragraphs that are split by end_of_line characters. 16 | # The pattern is: Chinese characters/punctuations with one and only one 17 | # end_of_line in between. 18 | pattern = fr'([{characters}{punctuations}]){eol_character}([{characters}])' 19 | # This replacement will remove the end_of_line character in between 20 | repl = r'\1\2' 21 | return pattern, repl 22 | 23 | 24 | def rewrite_file(filename: str, strategies: List[Tuple[str, str]]) -> bool: 25 | with open(filename, encoding='utf-8') as f: 26 | contents = f.read() 27 | changed = False 28 | for pattern, repl in strategies: 29 | if re.search(pattern, contents) is None: 30 | continue 31 | contents = re.sub(pattern, repl, contents) 32 | changed = True 33 | if changed: 34 | with open(filename, mode='w', encoding='utf-8') as f: 35 | f.write(contents) 36 | return changed 37 | 38 | 39 | def main(): 40 | strategies = [remove_eol()] 41 | changed = False 42 | for file in sys.argv[1:]: 43 | changed = changed | rewrite_file(file, strategies) 44 | return changed 45 | 46 | 47 | if __name__ == '__main__': 48 | raise SystemExit(main()) 49 | -------------------------------------------------------------------------------- /pre_commit_hooks/say_hello.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | 4 | def say_hello(username: str) -> int: 5 | """Say hello to username. 6 | 7 | Args: 8 | username (str): Say hello to ``username``. 9 | 10 | Returns: 11 | int: Return the status of the function. 12 | """ 13 | retv = 0 14 | if isinstance(username, str): 15 | print(f'Hello {username}') 16 | else: 17 | retv = 1 18 | 19 | return retv 20 | 21 | 22 | def main(): 23 | parser = argparse.ArgumentParser(description='say hello to user') 24 | parser.add_argument('username', type=str) 25 | args = parser.parse_args() 26 | return say_hello(args.username) 27 | 28 | 29 | if __name__ == '__main__': 30 | raise SystemExit(main()) 31 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 3 | 4 | [aliases] 5 | test=pytest 6 | 7 | [yapf] 8 | based_on_style = pep8 9 | blank_line_before_nested_class_or_def = true 10 | split_before_expression_after_opening_paren = true 11 | 12 | [isort] 13 | line_length = 79 14 | multi_line_output = 0 15 | extra_standard_library = pkg_resources,setuptools,logging,os,warnings,abc 16 | known_third_party = yaml 17 | no_lines_before = STDLIB,LOCALFOLDER 18 | default_section = THIRDPARTY 19 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup # type: ignore 2 | 3 | 4 | def readme(): 5 | with open('./README.md', encoding='utf-8') as f: 6 | content = f.read() 7 | return content 8 | 9 | 10 | setup( 11 | name='pre_commit_hooks', 12 | version='0.4.1', 13 | description='A pre-commit hook for OpenMMLab projects', 14 | long_description=readme(), 15 | long_description_content_type='text/markdown', 16 | url='https://github.com/open-mmlab/pre-commit-hooks', 17 | author='OpenMMLab Authors', 18 | author_email='openmmlab@gmail.com', 19 | packages=find_packages(), 20 | python_requires='>=3.6', 21 | install_requires=['PyYAML'], 22 | entry_points={ 23 | 'console_scripts': [ 24 | 'say-hello=pre_commit_hooks.say_hello:main', 25 | 'check-algo-readme=pre_commit_hooks.check_algo_readme:main', 26 | 'check-copyright=pre_commit_hooks.check_copyright:main', 27 | 'check-ecosystem-validity=pre_commit_hooks.check_ecosystem_validity:main', # noqa: E501 28 | 'remove-eol-characters=pre_commit_hooks.remove_eol_characters:main' 29 | ], 30 | }, 31 | ) 32 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/open-mmlab/pre-commit-hooks/a6b12ce1472d34b72a8b269f6aed7744c7d30375/tests/__init__.py -------------------------------------------------------------------------------- /tests/data/contain_copyright/test-cpp.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) OpenMMLab. All rights reserved. 2 | #include "test-h.h" 3 | 4 | // function to add the elements of two arrays 5 | void add(int n, float *x, float *y) { 6 | for (int i = 0; i < n; i++) y[i] = x[i] + y[i]; 7 | } 8 | 9 | int main() { 10 | int N = 1 << 20; // 1M elements 11 | 12 | float *x = new float[N]; 13 | float *y = new float[N]; 14 | 15 | // initialize x and y arrays on the host 16 | for (int i = 0; i < N; i++) { 17 | x[i] = 1.0f; 18 | y[i] = 2.0f; 19 | } 20 | 21 | // Run kernel on 1M elements on the CPU 22 | add(N, x, y); 23 | 24 | // Check for errors (all values should be 3.0f) 25 | float maxError = 0.0f; 26 | for (int i = 0; i < N; i++) maxError = fmax(maxError, fabs(y[i] - 3.0f)); 27 | std::cout << "Max error: " << maxError << std::endl; 28 | 29 | // Free memory 30 | delete[] x; 31 | delete[] y; 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /tests/data/contain_copyright/test-py.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) OpenMMLab. All rights reserved. 2 | import os 3 | 4 | if __name__ == '__main__': 5 | print(os.environ) 6 | -------------------------------------------------------------------------------- /tests/data/exclude/test-exclude.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | if __name__ == '__main__': 4 | print(os.environ) 5 | -------------------------------------------------------------------------------- /tests/data/test-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include "test-h.h" 2 | 3 | // function to add the elements of two arrays 4 | void add(int n, float *x, float *y) { 5 | for (int i = 0; i < n; i++) y[i] = x[i] + y[i]; 6 | } 7 | 8 | int main() { 9 | int N = 1 << 20; // 1M elements 10 | 11 | float *x = new float[N]; 12 | float *y = new float[N]; 13 | 14 | // initialize x and y arrays on the host 15 | for (int i = 0; i < N; i++) { 16 | x[i] = 1.0f; 17 | y[i] = 2.0f; 18 | } 19 | 20 | // Run kernel on 1M elements on the CPU 21 | add(N, x, y); 22 | 23 | // Check for errors (all values should be 3.0f) 24 | float maxError = 0.0f; 25 | for (int i = 0; i < N; i++) maxError = fmax(maxError, fabs(y[i] - 3.0f)); 26 | std::cout << "Max error: " << maxError << std::endl; 27 | 28 | // Free memory 29 | delete[] x; 30 | delete[] y; 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /tests/data/test-cu.cu: -------------------------------------------------------------------------------- 1 | #include "test-cuh.cuh" 2 | 3 | int main(void) { 4 | int N = 1 << 20; 5 | float *x, *y; 6 | 7 | // Allocate Unified Memory – accessible from CPU or GPU 8 | cudaMallocManaged(&x, N * sizeof(float)); 9 | cudaMallocManaged(&y, N * sizeof(float)); 10 | 11 | // initialize x and y arrays on the host 12 | for (int i = 0; i < N; i++) { 13 | x[i] = 1.0f; 14 | y[i] = 2.0f; 15 | } 16 | 17 | // Run kernel on 1M elements on the GPU 18 | add<<<1, 1>>>(N, x, y); 19 | 20 | // Wait for GPU to finish before accessing on host 21 | cudaDeviceSynchronize(); 22 | 23 | // Check for errors (all values should be 3.0f) 24 | float maxError = 0.0f; 25 | for (int i = 0; i < N; i++) maxError = fmax(maxError, fabs(y[i] - 3.0f)); 26 | std::cout << "Max error: " << maxError << std::endl; 27 | 28 | // Free memory 29 | cudaFree(x); 30 | cudaFree(y); 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /tests/data/test-cuh.cuh: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | // Kernel function to add the elements of two arrays 5 | __global__ void add(int n, float *x, float *y) { 6 | for (int i = 0; i < n; i++) y[i] = x[i] + y[i]; 7 | } 8 | -------------------------------------------------------------------------------- /tests/data/test-h.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | // function to add the elements of two arrays 6 | void add(int n, float *x, float *y){}; 7 | -------------------------------------------------------------------------------- /tests/data/test-hpp.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define DIVUP(m, n) ((m) / (n) + ((m) % (n) > 0)) 4 | -------------------------------------------------------------------------------- /tests/data/test-py.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | if __name__ == '__main__': 4 | print(os.environ) 5 | -------------------------------------------------------------------------------- /tests/test-ecosystem-validity.yaml: -------------------------------------------------------------------------------- 1 | # Example-1 2 | - repo_url: https://githubbb.com/NVlabs/FAN # repo 路径 3 | paper_url: https://arxiv.org/abs/2204.12451 # paper 链接 4 | type: Official Implementation # 项目类型 5 | mmrepos: # 使用了那些openmmlab工具(mmcv/mmengine是否要加入可选项) 6 | - MMDetections 7 | - MMSegmentation 8 | tags: 9 | - ICML, 10 | - Vision Transformer 11 | summary: 12 | en: Official PyTorch implementation of Fully Attentional Networks 13 | zh: 基于PyTorch的Fully Attentional Networks官方实现 14 | 15 | 16 | - repo_url: https://githubbb.com/NVlabs/FAN # repo 路径 17 | paper_url: https://arxiv.org/abs/2204.12451 # paper 链接 18 | type: Official Implementation # 项目类型 19 | mmrepos: # 使用了那些openmmlab工具(mmcv/mmengine是否要加入可选项) 20 | - MMDetections 21 | - MMSegmentation 22 | tags: 23 | - ICML, 24 | - Vision Transformer 25 | summary: 26 | en: Official PyTorch implementation of Fully Attentional Networks 27 | zh: 基于PyTorch的Fully Attentional Networks官方实现 28 | 29 | # Example-2 30 | - repo_url: https://github.com/Ascend/ModelZoo-PyTorch 31 | paper_url: '' 32 | type: Others 33 | mmrepos: 34 | - MMDetection 35 | - MMSegmentation 36 | - MMPose 37 | tags: 38 | - model zoo 39 | - Ascend 40 | summary: 41 | en: A collection of typical networks and related pre-trained models 42 | zh: 典型网络结构和预训练模型合集 43 | 44 | # Example-3 45 | - repo_url: https://github.com/takedarts/skipresnet 46 | paper_url: '' 47 | type: Official Implementation 48 | mmrepos: 49 | - MMClassification 50 | tags: 51 | - SkipResNets 52 | summary: 53 | en: An implementation of SkipResNets for performance evaluation 54 | zh: SkipResNets的实现 55 | 56 | # Example-4 57 | - repo_url: https://github.com/7eu7d7/genshin_voice_play 58 | paper_url: '' 59 | type: Demo 60 | mmrepos: 61 | - MMTracking 62 | - MMClassification 63 | tags: 64 | - Genshin 65 | - Game 66 | summary: 67 | en: Playing Genshin via voice. 68 | zh: 用语音控制玩原神,只需要动嘴就可以玩原神 69 | 70 | # Example-5 71 | - repo_url: https://github.com/hunto/MasKD 72 | paper_url: https://arxiv.org/abs/2205.14589 73 | type: Official Implementation 74 | mmrepos: 75 | - MMClassification 76 | - MMDetection 77 | - MMRazor 78 | tags: 79 | - Distillation 80 | - Detection 81 | summary: 82 | en: Official implementation of paper "Masked Distillation with Receptive Tokens" 83 | zh: Masked Distillation with Receptive Tokens官方实现 84 | 85 | # Example-6 86 | - repo_url: https://github.com/dineshreddy91/WALT 87 | paper_url: https://openaccess.thecvf.com/content/CVPR2022/papers/Reddy_WALT_Watch_and_Learn_2D_Amodal_Representation_From_Time-Lapse_Imagery_CVPR_2022_paper.pdf 88 | type: Official Implementation 89 | mmrepos: 90 | - MMDetection 91 | tags: 92 | - Amodal 93 | summary: 94 | en: Official implementation of "WALT:Watch and Learn 2D Amodal Representation using time-lapse imagery" 95 | zh: WALT:Watch and Learn 2D Amodal Representation using time-lapse imagery官方实现 96 | -------------------------------------------------------------------------------- /tests/test_copyright.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path as osp 3 | 4 | from pre_commit_hooks.check_copyright import check_copyright 5 | 6 | 7 | def test_copyright(): 8 | includes = ['./tests/data'] 9 | excludes = ['./tests/data/exclude'] 10 | suffixes = ['.py', '.cpp', '.h', '.cu', '.cuh', '.hpp'] 11 | contain_copyright = ['./tests/data/contain_copyright'] 12 | assert check_copyright(includes, excludes, suffixes) == 1 13 | 14 | for dir in includes: 15 | for root, dirs, files in os.walk(dir): 16 | for file in files: 17 | filepath = osp.join(root, file) 18 | with open(filepath, encoding='utf-8') as f: 19 | lines = f.readlines() 20 | if root not in excludes: 21 | assert lines[0].split(' ').count('Copyright') > 0 22 | else: 23 | assert lines[0].split(' ').count('Copyright') == 0 24 | with open(filepath, 'w', encoding='utf-8') as f: 25 | if root not in excludes and root not in contain_copyright: 26 | f.writelines(lines[1:]) 27 | else: 28 | f.writelines(lines) 29 | 30 | for dir in contain_copyright: 31 | for root, dirs, files in os.walk(dir): 32 | for file in files: 33 | filepath = osp.join(root, file) 34 | with open(filepath, encoding='utf-8') as f: 35 | line = f.readline() 36 | assert line.split(' ').count('OpenMMLab.') > 0 37 | -------------------------------------------------------------------------------- /tests/test_ecosystem_validity.py: -------------------------------------------------------------------------------- 1 | from pre_commit_hooks.check_ecosystem_validity import check_ecosystem_validity 2 | 3 | 4 | def test_ecosystem_validity(): 5 | filenames = './tests/test-ecosystem-validity.yaml' 6 | assert check_ecosystem_validity(filenames) == 1 7 | -------------------------------------------------------------------------------- /tests/test_remove_eol_characters.py: -------------------------------------------------------------------------------- 1 | from pre_commit_hooks.remove_eol_characters import remove_eol, rewrite_file 2 | 3 | original_text = """这是一个, 4 | 测试。 5 | This is a 6 | test 7 | """ 8 | rewrote_text = """这是一个,测试。 9 | This is a 10 | test 11 | """ 12 | 13 | 14 | def test_remove_eol_characters(tmp_path): 15 | file_path = str(tmp_path / 'test.md') 16 | with open(file_path, mode='w', encoding='utf-8') as f: 17 | f.write(original_text) 18 | strategies = [remove_eol()] 19 | assert rewrite_file(file_path, strategies) 20 | with open(file_path, encoding='utf-8') as f: 21 | contents = f.read() 22 | assert contents == rewrote_text 23 | --------------------------------------------------------------------------------