diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ee27b2679215341516327c9e01a7fdb6184e59fa --- /dev/null +++ b/Dockerfile @@ -0,0 +1,23 @@ +FROM public.ecr.aws/lambda/python:3.12 + +# Copy requirements.txt +COPY requirements.txt ${LAMBDA_TASK_ROOT} + +# Install the specified packages +RUN pip install -r requirements.txt + +# Install OpenCV dependencies +# RUN yum install -y libSM libXrender libXext + +# Copy function code +COPY main.py ${LAMBDA_TASK_ROOT}/ +COPY torch ${LAMBDA_TASK_ROOT}/torch/ +COPY local_test.py ${LAMBDA_TASK_ROOT}/ + +# Ensure the model files have correct permissions +RUN chmod -R 755 ${LAMBDA_TASK_ROOT}/torch/ +RUN chmod -R 755 ${LAMBDA_TASK_ROOT} +RUN chmod -R 755 ${LAMBDA_TASK_ROOT}/ + +# Set the CMD to run the test script +CMD [ "main.lambda_handler" ] diff --git a/local_test.py b/local_test.py new file mode 100644 index 0000000000000000000000000000000000000000..baebe3145130fb6e2f965363e9876e05fda3b1d9 --- /dev/null +++ b/local_test.py @@ -0,0 +1,21 @@ +import json +from main import lambda_handler + +event = { + "headers": { + "Content-Type": "application/json" + }, + "body": json.dumps({ + "imgUrl": "https://iduploadbucket.s3.ap-south-1.amazonaws.com/DFaqQf.png", + "brightness":1, + "contrast":4, + "saturation":4 + }), + "httpMethod": "POST", + "isBase64Encoded": False, + "path": "/captchaSolver" +} + +response = lambda_handler(event, None) +print(json.dumps(response, indent=4)) + diff --git a/main.py b/main.py new file mode 100644 index 0000000000000000000000000000000000000000..8103e2105d35db451bd15b48066c94990f9883c4 --- /dev/null +++ b/main.py @@ -0,0 +1,100 @@ +import io +import json +import requests +from io import BytesIO +from time import time +import base64 + +from torchOcr import OCRModel + +def validate_image_url(img_url): + response = requests.get(img_url) + if response.status_code != 200: + raise ValueError("Failed to retrieve image from URL") + if response.headers['Content-Type'] not in ['image/jpeg', 'image/jpg', 'image/png']: + raise ValueError("Invalid file type") + return response.content + +def lambda_handler(event, context): + http_method = event['httpMethod'] + path = event['path'] + start_time = time() + + ocr_model = OCRModel() + + try: + if http_method == 'GET' and path == '/': + return { + "statusCode": 200, + "body": json.dumps({"message": "Hello from CaptchaSolver v1.0!"}) + } + + if http_method != 'POST': + return { + "statusCode": 405, + "body": json.dumps({"error": "Method not allowed"}) + } + + content_type = event['headers'].get('Content-Type', '') + + if 'multipart/form-data' in content_type: + # Handle file upload via Postman + file_content = event['body'] + img_buffer = BytesIO(base64.b64decode(file_content)) + img_url = None # No URL provided in this case + brightness = body.get('brightness', 1.0) + contrast = body.get('contrast', 1.0) + sharpness = body.get('sharpness', 1.0) + else: + # Handle JSON input + body = json.loads(event.get('body', '{}')) + img_url = body.get('imgUrl') + img_buffer = None + brightness = body.get('brightness', 1.0) + contrast = body.get('contrast', 1.0) + sharpness = body.get('sharpness', 1.0) + + if not img_url and not img_buffer: + return { + "statusCode": 400, + "body": json.dumps({"error": "Either imgUrl or image buffer must be provided"}) + } + + if img_url: + img_content = validate_image_url(img_url) + image_buffer = io.BytesIO(img_content) + else: + image_buffer = img_buffer + + if path == '/captchaSolver': + detected_text = ocr_model.predict(image_buffer, brightness, contrast, sharpness) + result_message = "OCR Completed Successfully." + else: + return { + "statusCode": 404, + "body": json.dumps({"error": "Path not found"}) + } + + end_time = time() + execution_time = end_time - start_time + + return { + "statusCode": 200, + "body": json.dumps({ + "detected_text": detected_text, + "result": result_message, + "execution_time": f"{round(execution_time, 2)} sec", + }) + } + + except ValueError as ve: + return { + "statusCode": 400, + "body": json.dumps({"error": str(ve)}) + } + except Exception as e: + print(f"Error: {str(e)}") + return { + "statusCode": 500, + "body": json.dumps({"error": "Internal server error", "details": str(e)}) + } diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..289858950b2447ac41aea4f483508ebdfa475245 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +pillow +torchvision +pyyaml +pytorch_lightning +timm +nltk +requests \ No newline at end of file diff --git a/torch/.DS_Store b/torch/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..1e4dfce761d45ec2e19c83a62d12ca31c4780f00 Binary files /dev/null and b/torch/.DS_Store differ diff --git a/torch/hub/.DS_Store b/torch/hub/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..35104e00ba9e4bcb7635e1be7fe20dd531aca884 Binary files /dev/null and b/torch/hub/.DS_Store differ diff --git a/torch/hub/baudm_parseq_main/.DS_Store b/torch/hub/baudm_parseq_main/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..44952a35c7ad78bd6c856dae84179304bd890fbd Binary files /dev/null and b/torch/hub/baudm_parseq_main/.DS_Store differ diff --git a/torch/hub/baudm_parseq_main/.git-blame-ignore-revs b/torch/hub/baudm_parseq_main/.git-blame-ignore-revs new file mode 100644 index 0000000000000000000000000000000000000000..c0131fa70d50325138a556c2771b101c7ae00a4a --- /dev/null +++ b/torch/hub/baudm_parseq_main/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# Migrate code style to pyink +91f56d71736b77242f31dfb408f71d49fc0e3fcc diff --git a/torch/hub/baudm_parseq_main/.github/contexts-example.png b/torch/hub/baudm_parseq_main/.github/contexts-example.png new file mode 100644 index 0000000000000000000000000000000000000000..98990465f2483102dd36b10aa702c0aa6c502349 Binary files /dev/null and b/torch/hub/baudm_parseq_main/.github/contexts-example.png differ diff --git a/torch/hub/baudm_parseq_main/.github/gh-teaser.png b/torch/hub/baudm_parseq_main/.github/gh-teaser.png new file mode 100644 index 0000000000000000000000000000000000000000..ff4d839241b7898bb70a4a4198e7c0b0590c32c4 Binary files /dev/null and b/torch/hub/baudm_parseq_main/.github/gh-teaser.png differ diff --git a/torch/hub/baudm_parseq_main/.github/system.png b/torch/hub/baudm_parseq_main/.github/system.png new file mode 100644 index 0000000000000000000000000000000000000000..e313f7b5e3416d6c914e1c7d3e8fbfe6728dd335 Binary files /dev/null and b/torch/hub/baudm_parseq_main/.github/system.png differ diff --git a/torch/hub/baudm_parseq_main/.gitignore b/torch/hub/baudm_parseq_main/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..e4f55f143265ae8a0e4a4b060f922d531453ae3b --- /dev/null +++ b/torch/hub/baudm_parseq_main/.gitignore @@ -0,0 +1,148 @@ +# Output directories +outputs/ +multirun/ +ray_results/ + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +requirements/core.*.txt +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ +.python-version + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# IDE +.idea/ diff --git a/torch/hub/baudm_parseq_main/.pre-commit-config.yaml b/torch/hub/baudm_parseq_main/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ccf2dbb8eccfb2ca475032433b694a02816cf748 --- /dev/null +++ b/torch/hub/baudm_parseq_main/.pre-commit-config.yaml @@ -0,0 +1,18 @@ +exclude: '(abinet|crnn|trba|vitstr)/(?!system.py)' + +repos: +- repo: https://github.com/baudm/isort + rev: 5.13.2 + hooks: + - id: isort + +- repo: https://github.com/google/pyink + rev: 23.10.0 + hooks: + - id: pyink + +- repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.2.2 + hooks: + - id: ruff + args: [--exit-non-zero-on-fix] diff --git a/torch/hub/baudm_parseq_main/Datasets.md b/torch/hub/baudm_parseq_main/Datasets.md new file mode 100644 index 0000000000000000000000000000000000000000..f1cfd16d3a2f888a1cd1aa4e81faffd287092692 --- /dev/null +++ b/torch/hub/baudm_parseq_main/Datasets.md @@ -0,0 +1,92 @@ +We use various synthetic and real datasets. More info is in Appendix F of the supplementary material. Some preprocessing scripts are included in [`tools/`](tools). + +| Dataset | Type | Remarks | +|:-------:|:-----:|:--------| +| [MJSynth](https://www.robots.ox.ac.uk/~vgg/data/text/) | synthetic | Case-sensitive annotations were extracted from the image filenames | +| [SynthText](https://www.robots.ox.ac.uk/~vgg/data/scenetext/) | synthetic | Processed with [`crop_by_word_bb_syn90k.py`](https://github.com/FangShancheng/ABINet/blob/main/tools/crop_by_word_bb_syn90k.py) | +| [IC13](https://rrc.cvc.uab.es/?ch=2) | real | Three archives: 857, 1015, 1095 (full) | +| [IC15](https://rrc.cvc.uab.es/?ch=4) | real | Two archives: 1811, 2077 (full) | +| [CUTE80](http://cs-chan.com/downloads_cute80_dataset.html) | real | \[1\] | +| [IIIT5k](https://cvit.iiit.ac.in/research/projects/cvit-projects/the-iiit-5k-word-dataset) | real | \[1\] | +| [SVT](http://vision.ucsd.edu/~kai/svt/) | real | \[1\] | +| [SVTP](https://openaccess.thecvf.com/content_iccv_2013/html/Phan_Recognizing_Text_with_2013_ICCV_paper.html) | real | \[1\] | +| [ArT](https://rrc.cvc.uab.es/?ch=14) | real | \[2\] | +| [LSVT](https://rrc.cvc.uab.es/?ch=16) | real | \[2\] | +| [MLT19](https://rrc.cvc.uab.es/?ch=15) | real | \[2\] | +| [RCTW17](https://rctw.vlrlab.net/dataset.html) | real | \[2\] | +| [ReCTS](https://rrc.cvc.uab.es/?ch=12) | real | \[2\] | +| [Uber-Text](https://s3-us-west-2.amazonaws.com/uber-common-public/ubertext/index.html) | real | \[2\] | +| [COCO-Text v1.4](https://rrc.cvc.uab.es/?ch=5) | real | Processed with [`coco_text_converter.py`](tools/coco_text_converter.py) | +| [COCO-Text v2.0](https://bgshih.github.io/cocotext/) | real | Processed with [`coco_2_converter.py`](tools/coco_2_converter.py) | +| [OpenVINO](https://proceedings.mlr.press/v157/krylov21a.html) | real | [Annotations](https://storage.openvinotoolkit.org/repositories/openvino_training_extensions/datasets/open_images_v5_text/) for a subset of [Open Images](https://github.com/cvdfoundation/open-images-dataset). Processed with [`openvino_converter.py`](tools/openvino_converter.py). | +| [TextOCR](https://textvqa.org/textocr/) | real | Annotations for a subset of Open Images. Processed with [`textocr_converter.py`](tools/textocr_converter.py). A _horizontal_ version can be generated by passing `--rectify_pose`. | + +\[1\] Case-sensitive annotations from [Long and Yao](https://github.com/Jyouhou/Case-Sensitive-Scene-Text-Recognition-Datasets) + [our corrections](https://github.com/baudm/Case-Sensitive-Scene-Text-Recognition-Datasets). Processed with [case_sensitive_str_datasets_converter.py](tools/case_sensitive_str_datasets_converter.py)
+\[2\] Archives used as-is from [Baek et al.](https://github.com/ku21fan/STR-Fewer-Labels/blob/main/data.md) They are included in the dataset release for convenience. Please refer to their work for more info about the datasets. + +The preprocessed archives are available here: [val + test + most of train](https://drive.google.com/drive/folders/1NYuoi7dfJVgo-zUJogh8UQZgIMpLviOE), [TextOCR + OpenVINO](https://drive.google.com/drive/folders/1D9z_YJVa6f-O0juni-yG5jcwnhvYw-qC) + +The expected filesystem structure is as follows: +``` +data +├── test +│ ├── ArT +│ ├── COCOv1.4 +│ ├── CUTE80 +│ ├── IC13_1015 +│ ├── IC13_1095 # Full IC13 test set. Typically not used for benchmarking but provided here for convenience. +│ ├── IC13_857 +│ ├── IC15_1811 +│ ├── IC15_2077 +│ ├── IIIT5k +│ ├── SVT +│ ├── SVTP +│ └── Uber +├── train +│ ├── real +│ │ ├── ArT +│ │ │ ├── train +│ │ │ └── val +│ │ ├── COCOv2.0 +│ │ │ ├── train +│ │ │ └── val +│ │ ├── LSVT +│ │ │ ├── test +│ │ │ ├── train +│ │ │ └── val +│ │ ├── MLT19 +│ │ │ ├── test +│ │ │ ├── train +│ │ │ └── val +│ │ ├── OpenVINO +│ │ │ ├── train_1 +│ │ │ ├── train_2 +│ │ │ ├── train_5 +│ │ │ ├── train_f +│ │ │ └── validation +│ │ ├── RCTW17 +│ │ │ ├── test +│ │ │ ├── train +│ │ │ └── val +│ │ ├── ReCTS +│ │ │ ├── test +│ │ │ ├── train +│ │ │ └── val +│ │ ├── TextOCR +│ │ │ ├── train +│ │ │ └── val +│ │ └── Uber +│ │ ├── train +│ │ └── val +│ └── synth +│ ├── MJ +│ │ ├── test +│ │ ├── train +│ │ └── val +│ └── ST +└── val + ├── IC13 + ├── IC15 + ├── IIIT5k + └── SVT +``` diff --git a/torch/hub/baudm_parseq_main/LICENSE b/torch/hub/baudm_parseq_main/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/torch/hub/baudm_parseq_main/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/torch/hub/baudm_parseq_main/Makefile b/torch/hub/baudm_parseq_main/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..b138a02eb509e973c89279d99867905c7ccaec14 --- /dev/null +++ b/torch/hub/baudm_parseq_main/Makefile @@ -0,0 +1,30 @@ +# Reference: https://dida.do/blog/managing-layered-requirements-with-pip-tools + +REQUIREMENTS_TXT := $(addsuffix .txt, $(basename $(wildcard requirements/*.in))) +PIP_COMPILE := pip-compile --quiet --no-header --allow-unsafe --resolver=backtracking --strip-extras + +.DEFAULT_GOAL := help +.PHONY: reqs clean-reqs help + +requirements/constraints.txt: requirements/*.in + CONSTRAINTS=/dev/null $(PIP_COMPILE) --output-file $@ $^ --extra-index-url https://download.pytorch.org/whl/cpu + +requirements/%.txt: requirements/%.in requirements/constraints.txt + CONSTRAINTS=constraints.txt $(PIP_COMPILE) --no-annotate --output-file $@ $< + @# Remove --extra-index-url, blank lines, and torch dependency from non-core groups + @[ $* = core ] || sed '/^--/d; /^$$/d; /^torch==/d' -i $@ + +reqs: $(REQUIREMENTS_TXT) ## Generate the requirements files + +torch-%: requirements/core.txt ## Set PyTorch platform to use, e.g. cpu, cu117, rocm5.2 + @echo Generating requirements/core.$*.txt + @sed 's|cpu|$*|' $< >requirements/core.$*.txt + +clean-reqs: ## Delete the requirements files + rm -f requirements/constraints.txt requirements/core.*.txt $(REQUIREMENTS_TXT) + +git-config: ## Common Git configuration + git config blame.ignoreRevsFile .git-blame-ignore-revs + +help: ## Display this help + @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' diff --git a/torch/hub/baudm_parseq_main/NOTICE b/torch/hub/baudm_parseq_main/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..e5c7919c82a31048cf3fa681928dd21fd2cd96dd --- /dev/null +++ b/torch/hub/baudm_parseq_main/NOTICE @@ -0,0 +1,18 @@ +Scene Text Recognition Model Hub +Copyright 2022 Darwin Bautista + +The Initial Developer of strhub/models/abinet (sans system.py) is +Fang et al. (https://github.com/FangShancheng/ABINet). +Copyright 2021-2022 USTC + +The Initial Developer of strhub/models/crnn (sans system.py) is +Jieru Mei (https://github.com/meijieru/crnn.pytorch). +Copyright 2017-2022 Jieru Mei + +The Initial Developer of strhub/models/trba (sans system.py) is +Jeonghun Baek (https://github.com/clovaai/deep-text-recognition-benchmark). +Copyright 2019-2022 NAVER Corp. + +The Initial Developer of strhub/models/vitstr (sans system.py) is +Rowel Atienza (https://github.com/roatienza/deep-text-recognition-benchmark). +Copyright 2021-2022 Rowel Atienza diff --git a/torch/hub/baudm_parseq_main/README.md b/torch/hub/baudm_parseq_main/README.md new file mode 100644 index 0000000000000000000000000000000000000000..925555436d5f54441d00528c796b4954177a6dee --- /dev/null +++ b/torch/hub/baudm_parseq_main/README.md @@ -0,0 +1,280 @@ +## News +- **2024-02-22**: Updated for PyTorch 2.0 and Lightning 2.0 +- **2024-01-16**: Featured in the [NVIDIA Developer Blog](https://developer.nvidia.com/blog/robust-scene-text-detection-and-recognition-introduction/) +- **2023-11-18**: [Interview with Deci AI at ECCV 2022](https://deeplearningdaily.substack.com/p/exclusive-interview-with-a-researcher) published +- **2023-09-07**: [Added](https://github.com/PaddlePaddle/PaddleOCR/blob/main/doc/doc_en/algorithm_rec_parseq_en.md) to [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR), one of the most popular multilingual OCR toolkits +- **2023-06-15**: [Added](https://mindee.github.io/doctr/modules/models.html#doctr.models.recognition.parseq) to [docTR](https://github.com/mindee/doctr), a deep learning-based library for OCR +- **2022-07-14**: Initial public release (ranked #1 overall for STR on [Papers With Code](https://paperswithcode.com/paper/scene-text-recognition-with-permuted) at the time of release) +- **2022-07-04**: Accepted at ECCV 2022 + +
+ +# Scene Text Recognition with
Permuted Autoregressive Sequence Models +[![Apache License 2.0](https://img.shields.io/github/license/baudm/parseq)](https://github.com/baudm/parseq/blob/main/LICENSE) +[![arXiv preprint](http://img.shields.io/badge/arXiv-2207.06966-b31b1b)](https://arxiv.org/abs/2207.06966) +[![In Proc. ECCV 2022](http://img.shields.io/badge/ECCV-2022-6790ac)](https://www.ecva.net/papers/eccv_2022/papers_ECCV/html/556_ECCV_2022_paper.php) +[![Gradio demo](https://img.shields.io/badge/%F0%9F%A4%97%20demo-Gradio-ff7c00)](https://huggingface.co/spaces/baudm/PARSeq-OCR) + +[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/scene-text-recognition-with-permuted/scene-text-recognition-on-coco-text)](https://paperswithcode.com/sota/scene-text-recognition-on-coco-text?p=scene-text-recognition-with-permuted) +[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/scene-text-recognition-with-permuted/scene-text-recognition-on-ic19-art)](https://paperswithcode.com/sota/scene-text-recognition-on-ic19-art?p=scene-text-recognition-with-permuted) +[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/scene-text-recognition-with-permuted/scene-text-recognition-on-icdar2013)](https://paperswithcode.com/sota/scene-text-recognition-on-icdar2013?p=scene-text-recognition-with-permuted) +[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/scene-text-recognition-with-permuted/scene-text-recognition-on-iiit5k)](https://paperswithcode.com/sota/scene-text-recognition-on-iiit5k?p=scene-text-recognition-with-permuted) +[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/scene-text-recognition-with-permuted/scene-text-recognition-on-cute80)](https://paperswithcode.com/sota/scene-text-recognition-on-cute80?p=scene-text-recognition-with-permuted) +[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/scene-text-recognition-with-permuted/scene-text-recognition-on-icdar2015)](https://paperswithcode.com/sota/scene-text-recognition-on-icdar2015?p=scene-text-recognition-with-permuted) +[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/scene-text-recognition-with-permuted/scene-text-recognition-on-svt)](https://paperswithcode.com/sota/scene-text-recognition-on-svt?p=scene-text-recognition-with-permuted) +[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/scene-text-recognition-with-permuted/scene-text-recognition-on-svtp)](https://paperswithcode.com/sota/scene-text-recognition-on-svtp?p=scene-text-recognition-with-permuted) + +[**Darwin Bautista**](https://github.com/baudm) and [**Rowel Atienza**](https://github.com/roatienza) + +Electrical and Electronics Engineering Institute
+University of the Philippines, Diliman + +[Method](#method-tldr) | [Sample Results](#sample-results) | [Getting Started](#getting-started) | [FAQ](#frequently-asked-questions) | [Training](#training) | [Evaluation](#evaluation) | [Citation](#citation) + +
+ +Scene Text Recognition (STR) models use language context to be more robust against noisy or corrupted images. Recent approaches like ABINet use a standalone or external Language Model (LM) for prediction refinement. In this work, we show that the external LM—which requires upfront allocation of dedicated compute capacity—is inefficient for STR due to its poor performance vs cost characteristics. We propose a more efficient approach using **p**ermuted **a**uto**r**egressive **seq**uence (PARSeq) models. View our ECCV [poster](https://drive.google.com/file/d/19luOT_RMqmafLMhKQQHBnHNXV7fOCRfw/view) and [presentation](https://drive.google.com/file/d/11VoZW4QC5tbMwVIjKB44447uTiuCJAAD/view) for a brief overview. + +![PARSeq](.github/gh-teaser.png) + +**NOTE:** _P-S and P-Ti are shorthands for PARSeq-S and PARSeq-Ti, respectively._ + +### Method tl;dr + +Our main insight is that with an ensemble of autoregressive (AR) models, we could unify the current STR decoding methods (context-aware AR and context-free non-AR) and the bidirectional (cloze) refinement model: +
Unified STR model
+ +A single Transformer can realize different models by merely varying its attention mask. With the correct decoder parameterization, it can be trained with Permutation Language Modeling to enable inference for arbitrary output positions given arbitrary subsets of the input context. This *arbitrary decoding* characteristic results in a _unified_ STR model—PARSeq—capable of context-free and context-aware inference, as well as iterative prediction refinement using bidirectional context **without** requiring a standalone language model. PARSeq can be considered an ensemble of AR models with shared architecture and weights: + +![System](.github/system.png) +**NOTE:** _LayerNorm and Dropout layers are omitted. `[B]`, `[E]`, and `[P]` stand for beginning-of-sequence (BOS), end-of-sequence (EOS), and padding tokens, respectively. `T` = 25 results in 26 distinct position tokens. The position tokens both serve as query vectors and position embeddings for the input context. For `[B]`, no position embedding is added. Attention +masks are generated from the given permutations and are used only for the context-position attention. Lce pertains to the cross-entropy loss._ + +### Sample Results +
+ +| Input Image | PARSeq-SA | ABINet | TRBA | ViTSTR-S | CRNN | +|:--------------------------------------------------------------------------:|:--------------------:|:-----------------:|:-----------------:|:-----------------:|:-----------------:| +| CHEWBACCA | CHEWBACCA | CHEWBA**GG**A | CHEWBACCA | CHEWBACCA | CHEW**U**ACCA | +| Chevron | Chevro**l** | Chevro\_ | Chevro\_ | Chevr\_\_ | Chevr\_\_ | +| SALMON | SALMON | SALMON | SALMON | SALMON | SA\_MON | +| Verbandstoffe | Verbandst**e**ffe | Verbandst**e**ffe | Verbandst**ell**e | Verbandst**e**ffe | Verbands**le**ffe | +| Kappa | Kappa | Kappa | Ka**s**pa | Kappa | Ka**ad**a | +| 3rdAve | 3rdAve | 3=-Ave | 3rdAve | 3rdAve | **Coke** | + +**NOTE:** _Bold letters and underscores indicate wrong and missing character predictions, respectively._ +
+ +## Getting Started +This repository contains the reference implementation for PARSeq and reproduced models (collectively referred to as _Scene Text Recognition Model Hub_). See `NOTICE` for copyright information. +Majority of the code is licensed under the Apache License v2.0 (see `LICENSE`) while ABINet and CRNN sources are +released under the BSD and MIT licenses, respectively (see corresponding `LICENSE` files for details). + +### Demo +An [interactive Gradio demo](https://huggingface.co/spaces/baudm/PARSeq-OCR) hosted at Hugging Face is available. The pretrained weights released here are used for the demo. + +### Installation +Requires Python >= 3.9 and PyTorch >= 2.0. The default requirements files will install the latest versions of the dependencies (as of February 22, 2024). +```bash +# Use specific platform build. Other PyTorch 2.0 options: cu118, cu121, rocm5.7 +platform=cpu +# Generate requirements files for specified PyTorch platform +make torch-${platform} +# Install the project and core + train + test dependencies. Subsets: [dev,train,test,bench,tune] +pip install -r requirements/core.${platform}.txt -e .[train,test] + ``` +#### Updating dependency version pins +```bash +pip install pip-tools +make clean-reqs reqs # Regenerate all the requirements files + ``` +### Datasets +Download the [datasets](Datasets.md) from the following links: +1. [LMDB archives](https://drive.google.com/drive/folders/1NYuoi7dfJVgo-zUJogh8UQZgIMpLviOE) for MJSynth, SynthText, IIIT5k, SVT, SVTP, IC13, IC15, CUTE80, ArT, RCTW17, ReCTS, LSVT, MLT19, COCO-Text, and Uber-Text. +2. [LMDB archives](https://drive.google.com/drive/folders/1D9z_YJVa6f-O0juni-yG5jcwnhvYw-qC) for TextOCR and OpenVINO. + +### Pretrained Models via Torch Hub +Available models are: `abinet`, `crnn`, `trba`, `vitstr`, `parseq_tiny`, `parseq_patch16_224`, and `parseq`. +```python +import torch +from PIL import Image +from strhub.data.module import SceneTextDataModule + +# Load model and image transforms +parseq = torch.hub.load('baudm/parseq', 'parseq', pretrained=True).eval() +img_transform = SceneTextDataModule.get_transform(parseq.hparams.img_size) + +img = Image.open('/path/to/image.png').convert('RGB') +# Preprocess. Model expects a batch of images with shape: (B, C, H, W) +img = img_transform(img).unsqueeze(0) + +logits = parseq(img) +logits.shape # torch.Size([1, 26, 95]), 94 characters + [EOS] symbol + +# Greedy decoding +pred = logits.softmax(-1) +label, confidence = parseq.tokenizer.decode(pred) +print('Decoded label = {}'.format(label[0])) +``` + +## Frequently Asked Questions +- How do I train on a new language? See Issues [#5](https://github.com/baudm/parseq/issues/5) and [#9](https://github.com/baudm/parseq/issues/9). +- Can you export to TorchScript or ONNX? Yes, see Issue [#12](https://github.com/baudm/parseq/issues/12#issuecomment-1267842315). +- How do I test on my own dataset? See Issue [#27](https://github.com/baudm/parseq/issues/27). +- How do I finetune and/or create a custom dataset? See Issue [#7](https://github.com/baudm/parseq/issues/7). +- What is `val_NED`? See Issue [#10](https://github.com/baudm/parseq/issues/10). + +## Training +The training script can train any supported model. You can override any configuration using the command line. Please refer to [Hydra](https://hydra.cc) docs for more info about the syntax. Use `./train.py --help` to see the default configuration. + +
Sample commands for different training configurations

+ +### Finetune using pretrained weights +```bash +./train.py +experiment=parseq-tiny pretrained=parseq-tiny # Not all experiments have pretrained weights +``` + +### Train a model variant/preconfigured experiment +The base model configurations are in `configs/model/`, while variations are stored in `configs/experiment/`. +```bash +./train.py +experiment=parseq-tiny # Some examples: abinet-sv, trbc +``` + +### Specify the character set for training +```bash +./train.py charset=94_full # Other options: 36_lowercase or 62_mixed-case. See configs/charset/ +``` + +### Specify the training dataset +```bash +./train.py dataset=real # Other option: synth. See configs/dataset/ +``` + +### Change general model training parameters +```bash +./train.py model.img_size=[32, 128] model.max_label_length=25 model.batch_size=384 +``` + +### Change data-related training parameters +```bash +./train.py data.root_dir=data data.num_workers=2 data.augment=true +``` + +### Change `pytorch_lightning.Trainer` parameters +```bash +./train.py trainer.max_epochs=20 trainer.accelerator=gpu trainer.devices=2 +``` +Note that you can pass any [Trainer parameter](https://pytorch-lightning.readthedocs.io/en/stable/common/trainer.html), +you just need to prefix it with `+` if it is not originally specified in `configs/main.yaml`. + +### Resume training from checkpoint (experimental) +```bash +./train.py +experiment= ckpt_path=outputs///checkpoints/.ckpt +``` + +

+ +## Evaluation +The test script, ```test.py```, can be used to evaluate any model trained with this project. For more info, see ```./test.py --help```. + +PARSeq runtime parameters can be passed using the format `param:type=value`. For example, PARSeq NAR decoding can be invoked via `./test.py parseq.ckpt refine_iters:int=2 decode_ar:bool=false`. + +
Sample commands for reproducing results

+ +### Lowercase alphanumeric comparison on benchmark datasets (Table 6) +```bash +./test.py outputs///checkpoints/last.ckpt # or use the released weights: ./test.py pretrained=parseq +``` +**Sample output:** +| Dataset | # samples | Accuracy | 1 - NED | Confidence | Label Length | +|:---------:|----------:|---------:|--------:|-----------:|-------------:| +| IIIT5k | 3000 | 99.00 | 99.79 | 97.09 | 5.09 | +| SVT | 647 | 97.84 | 99.54 | 95.87 | 5.86 | +| IC13_1015 | 1015 | 98.13 | 99.43 | 97.19 | 5.31 | +| IC15_2077 | 2077 | 89.22 | 96.43 | 91.91 | 5.33 | +| SVTP | 645 | 96.90 | 99.36 | 94.37 | 5.86 | +| CUTE80 | 288 | 98.61 | 99.80 | 96.43 | 5.53 | +| **Combined** | **7672** | **95.95** | **98.78** | **95.34** | **5.33** | +-------------------------------------------------------------------------- + +### Benchmark using different evaluation character sets (Table 4) +```bash +./test.py outputs///checkpoints/last.ckpt # lowercase alphanumeric (36-character set) +./test.py outputs///checkpoints/last.ckpt --cased # mixed-case alphanumeric (62-character set) +./test.py outputs///checkpoints/last.ckpt --cased --punctuation # mixed-case alphanumeric + punctuation (94-character set) +``` + +### Lowercase alphanumeric comparison on more challenging datasets (Table 5) +```bash +./test.py outputs///checkpoints/last.ckpt --new +``` + +### Benchmark Model Compute Requirements (Figure 5) +```bash +./bench.py model=parseq model.decode_ar=false model.refine_iters=3 + +model(x) + Median: 14.87 ms + IQR: 0.33 ms (14.78 to 15.12) + 7 measurements, 10 runs per measurement, 1 thread +| module | #parameters | #flops | #activations | +|:----------------------|:--------------|:---------|:---------------| +| model | 23.833M | 3.255G | 8.214M | +| encoder | 21.381M | 2.88G | 7.127M | +| decoder | 2.368M | 0.371G | 1.078M | +| head | 36.575K | 3.794M | 9.88K | +| text_embed.embedding | 37.248K | 0 | 0 | +``` + +### Latency Measurements vs Output Label Length (Appendix I) +```bash +./bench.py model=parseq model.decode_ar=false model.refine_iters=3 +range=true +``` + +### Orientation robustness benchmark (Appendix J) +```bash +./test.py outputs///checkpoints/last.ckpt --cased --punctuation # no rotation +./test.py outputs///checkpoints/last.ckpt --cased --punctuation --rotation 90 +./test.py outputs///checkpoints/last.ckpt --cased --punctuation --rotation 180 +./test.py outputs///checkpoints/last.ckpt --cased --punctuation --rotation 270 +``` + +### Using trained models to read text from images (Appendix L) +```bash +./read.py outputs///checkpoints/last.ckpt --images demo_images/* # Or use ./read.py pretrained=parseq +Additional keyword arguments: {} +demo_images/art-01107.jpg: CHEWBACCA +demo_images/coco-1166773.jpg: Chevrol +demo_images/cute-184.jpg: SALMON +demo_images/ic13_word_256.png: Verbandsteffe +demo_images/ic15_word_26.png: Kaopa +demo_images/uber-27491.jpg: 3rdAve + +# use NAR decoding + 2 refinement iterations for PARSeq +./read.py pretrained=parseq refine_iters:int=2 decode_ar:bool=false --images demo_images/* +``` +

+ +## Tuning + +We use [Ray Tune](https://www.ray.io/ray-tune) for automated parameter tuning of the learning rate. See `./tune.py --help`. Extend `tune.py` to support tuning of other hyperparameters. +```bash +./tune.py tune.num_samples=20 # find optimum LR for PARSeq's default config using 20 trials +./tune.py +experiment=tune_abinet-lm # find the optimum learning rate for ABINet's language model +``` + +## Citation +```bibtex +@InProceedings{bautista2022parseq, + title={Scene Text Recognition with Permuted Autoregressive Sequence Models}, + author={Bautista, Darwin and Atienza, Rowel}, + booktitle={European Conference on Computer Vision}, + pages={178--196}, + month={10}, + year={2022}, + publisher={Springer Nature Switzerland}, + address={Cham}, + doi={10.1007/978-3-031-19815-1_11}, + url={https://doi.org/10.1007/978-3-031-19815-1_11} +} +``` diff --git a/torch/hub/baudm_parseq_main/bench.py b/torch/hub/baudm_parseq_main/bench.py new file mode 100644 index 0000000000000000000000000000000000000000..d3764abcc8833bdcdf802dd11b04318b9c822bec --- /dev/null +++ b/torch/hub/baudm_parseq_main/bench.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os + +import hydra +from fvcore.nn import ActivationCountAnalysis, FlopCountAnalysis, flop_count_table +from omegaconf import DictConfig + +import torch +from torch.utils import benchmark + + +@torch.inference_mode() +@hydra.main(config_path='configs', config_name='bench', version_base='1.2') +def main(config: DictConfig): + # For consistent behavior + os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8' + torch.backends.cudnn.benchmark = False + torch.use_deterministic_algorithms(True) + + device = config.get('device', 'cuda') + + h, w = config.data.img_size + x = torch.rand(1, 3, h, w, device=device) + model = hydra.utils.instantiate(config.model).eval().to(device) + + if config.get('range', False): + for i in range(1, 26, 4): + timer = benchmark.Timer(stmt='model(x, len)', globals={'model': model, 'x': x, 'len': i}) + print(timer.blocked_autorange(min_run_time=1)) + else: + timer = benchmark.Timer(stmt='model(x)', globals={'model': model, 'x': x}) + flops = FlopCountAnalysis(model, x) + acts = ActivationCountAnalysis(model, x) + print(timer.blocked_autorange(min_run_time=1)) + print(flop_count_table(flops, 1, acts, False)) + + +if __name__ == '__main__': + main() diff --git a/torch/hub/baudm_parseq_main/configs/.DS_Store b/torch/hub/baudm_parseq_main/configs/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..a1d1eea2ff40bbd148a3c69072d53e06424c872b Binary files /dev/null and b/torch/hub/baudm_parseq_main/configs/.DS_Store differ diff --git a/torch/hub/baudm_parseq_main/configs/bench.yaml b/torch/hub/baudm_parseq_main/configs/bench.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4b5872aae085ec525212cbb4a58982f9b721d854 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/bench.yaml @@ -0,0 +1,10 @@ +# Disable any logging or output +defaults: + - main + - _self_ + - override hydra/job_logging: disabled + +hydra: + output_subdir: null + run: + dir: . diff --git a/torch/hub/baudm_parseq_main/configs/charset/36_lowercase.yaml b/torch/hub/baudm_parseq_main/configs/charset/36_lowercase.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce2a5a08acd5aff59617d23ee38a97acd8d93758 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/charset/36_lowercase.yaml @@ -0,0 +1,3 @@ +# @package _global_ +model: + charset_train: "0123456789abcdefghijklmnopqrstuvwxyz" diff --git a/torch/hub/baudm_parseq_main/configs/charset/62_mixed-case.yaml b/torch/hub/baudm_parseq_main/configs/charset/62_mixed-case.yaml new file mode 100644 index 0000000000000000000000000000000000000000..07db844590844cae31a024f1c569bef9841dff06 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/charset/62_mixed-case.yaml @@ -0,0 +1,3 @@ +# @package _global_ +model: + charset_train: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" diff --git a/torch/hub/baudm_parseq_main/configs/charset/94_full.yaml b/torch/hub/baudm_parseq_main/configs/charset/94_full.yaml new file mode 100644 index 0000000000000000000000000000000000000000..186bf42e272036f3192c992cd23f715fcea17996 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/charset/94_full.yaml @@ -0,0 +1,3 @@ +# @package _global_ +model: + charset_train: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" diff --git a/torch/hub/baudm_parseq_main/configs/dataset/real.yaml b/torch/hub/baudm_parseq_main/configs/dataset/real.yaml new file mode 100644 index 0000000000000000000000000000000000000000..786042d196695b4734b89bf40966eeda297e93b2 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/dataset/real.yaml @@ -0,0 +1,3 @@ +# @package _global_ +data: + train_dir: real diff --git a/torch/hub/baudm_parseq_main/configs/dataset/synth.yaml b/torch/hub/baudm_parseq_main/configs/dataset/synth.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0a7f071902d8ea2d8a0370243c6a37442bc20486 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/dataset/synth.yaml @@ -0,0 +1,7 @@ +# @package _global_ +data: + train_dir: synth + num_workers: 3 + +trainer: + limit_train_batches: 0.20496 # to match the steps per epoch of `real` diff --git a/torch/hub/baudm_parseq_main/configs/experiment/abinet-sv.yaml b/torch/hub/baudm_parseq_main/configs/experiment/abinet-sv.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fa2b0118179a9058d7820139a036263413e8dbd5 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/experiment/abinet-sv.yaml @@ -0,0 +1,8 @@ +# @package _global_ +defaults: + - override /model: abinet + +model: + name: abinet-sv + v_num_layers: 2 + v_attention: attention diff --git a/torch/hub/baudm_parseq_main/configs/experiment/abinet.yaml b/torch/hub/baudm_parseq_main/configs/experiment/abinet.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6915e0ae0c6e23f16b19d977d685cac2e382fae --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/experiment/abinet.yaml @@ -0,0 +1,3 @@ +# @package _global_ +defaults: + - override /model: abinet diff --git a/torch/hub/baudm_parseq_main/configs/experiment/crnn.yaml b/torch/hub/baudm_parseq_main/configs/experiment/crnn.yaml new file mode 100644 index 0000000000000000000000000000000000000000..32e6c028d47e356e5688ae7ad9f6a372b60c0269 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/experiment/crnn.yaml @@ -0,0 +1,6 @@ +# @package _global_ +defaults: + - override /model: crnn + +data: + num_workers: 5 diff --git a/torch/hub/baudm_parseq_main/configs/experiment/parseq-patch16-224.yaml b/torch/hub/baudm_parseq_main/configs/experiment/parseq-patch16-224.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0113de35ff3473331b20578b2673c2d201ea478c --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/experiment/parseq-patch16-224.yaml @@ -0,0 +1,7 @@ +# @package _global_ +defaults: + - override /model: parseq + +model: + img_size: [ 224, 224 ] # [ height, width ] + patch_size: [ 16, 16 ] # [ height, width ] diff --git a/torch/hub/baudm_parseq_main/configs/experiment/parseq-tiny.yaml b/torch/hub/baudm_parseq_main/configs/experiment/parseq-tiny.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fed637935e61a54cbc02a76db25e3ce17afa4c68 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/experiment/parseq-tiny.yaml @@ -0,0 +1,9 @@ +# @package _global_ +defaults: + - override /model: parseq + +model: + name: parseq-tiny + embed_dim: 192 + enc_num_heads: 3 + dec_num_heads: 6 diff --git a/torch/hub/baudm_parseq_main/configs/experiment/parseq.yaml b/torch/hub/baudm_parseq_main/configs/experiment/parseq.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bfb8da134c8aae1875dac468bab15594877fb6fb --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/experiment/parseq.yaml @@ -0,0 +1,3 @@ +# @package _global_ +defaults: + - override /model: parseq diff --git a/torch/hub/baudm_parseq_main/configs/experiment/trba.yaml b/torch/hub/baudm_parseq_main/configs/experiment/trba.yaml new file mode 100644 index 0000000000000000000000000000000000000000..59907202fe3c8205ef79581bac8428c8310a77b4 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/experiment/trba.yaml @@ -0,0 +1,6 @@ +# @package _global_ +defaults: + - override /model: trba + +data: + num_workers: 3 diff --git a/torch/hub/baudm_parseq_main/configs/experiment/trbc.yaml b/torch/hub/baudm_parseq_main/configs/experiment/trbc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a66ba1da0251f86fde285bb88d3c68129157cbed --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/experiment/trbc.yaml @@ -0,0 +1,11 @@ +# @package _global_ +defaults: + - override /model: trba + +model: + name: trbc + _target_: strhub.models.trba.system.TRBC + lr: 1e-4 + +data: + num_workers: 3 diff --git a/torch/hub/baudm_parseq_main/configs/experiment/tune_abinet-lm.yaml b/torch/hub/baudm_parseq_main/configs/experiment/tune_abinet-lm.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6efa52830bbb8cb392617bf54f3c7b7d6a77ed18 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/experiment/tune_abinet-lm.yaml @@ -0,0 +1,17 @@ +# @package _global_ +defaults: + - override /model: abinet + +model: + name: abinet-lm + lm_only: true + +data: + augment: false + num_workers: 3 + +tune: + gpus_per_trial: 0.5 + lr: + min: 1e-5 + max: 1e-3 diff --git a/torch/hub/baudm_parseq_main/configs/experiment/vitstr.yaml b/torch/hub/baudm_parseq_main/configs/experiment/vitstr.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6a8111aecdc5817fe8d467a3f21c2d49b6de9f71 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/experiment/vitstr.yaml @@ -0,0 +1,7 @@ +# @package _global_ +defaults: + - override /model: vitstr + +model: + img_size: [ 32, 128 ] # [ height, width ] + patch_size: [ 4, 8 ] # [ height, width ] diff --git a/torch/hub/baudm_parseq_main/configs/main.yaml b/torch/hub/baudm_parseq_main/configs/main.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fe890d3458378d9f5a5671f7fe15757fe41fb49d --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/main.yaml @@ -0,0 +1,52 @@ +defaults: + - _self_ + - model: parseq + - charset: 94_full + - dataset: real + +model: + _convert_: all + img_size: [ 32, 128 ] # [ height, width ] + max_label_length: 25 + # The ordering in charset_train matters. It determines the token IDs assigned to each character. + charset_train: ??? + # For charset_test, ordering doesn't matter. + charset_test: "0123456789abcdefghijklmnopqrstuvwxyz" + batch_size: 384 + weight_decay: 0.0 + warmup_pct: 0.075 # equivalent to 1.5 epochs of warm up + +data: + _target_: strhub.data.module.SceneTextDataModule + root_dir: data + train_dir: ??? + batch_size: ${model.batch_size} + img_size: ${model.img_size} + charset_train: ${model.charset_train} + charset_test: ${model.charset_test} + max_label_length: ${model.max_label_length} + remove_whitespace: true + normalize_unicode: true + augment: true + num_workers: 2 + +trainer: + _target_: pytorch_lightning.Trainer + _convert_: all + val_check_interval: 1000 + #max_steps: 169680 # 20 epochs x 8484 steps (for batch size = 384, real data) + max_epochs: 20 + gradient_clip_val: 20 + accelerator: gpu + devices: 2 + +ckpt_path: null +pretrained: null + +hydra: + output_subdir: config + run: + dir: outputs/${model.name}/${now:%Y-%m-%d}_${now:%H-%M-%S} + sweep: + dir: multirun/${model.name}/${now:%Y-%m-%d}_${now:%H-%M-%S} + subdir: ${hydra.job.override_dirname} diff --git a/torch/hub/baudm_parseq_main/configs/model/abinet.yaml b/torch/hub/baudm_parseq_main/configs/model/abinet.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a19757adf3edc11da0755ebdbc56b5b58ff544fa --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/model/abinet.yaml @@ -0,0 +1,26 @@ +name: abinet +_target_: strhub.models.abinet.system.ABINet + +# Shared Transformer configuration +d_model: 512 +nhead: 8 +d_inner: 2048 +activation: relu +dropout: 0.1 + +# Architecture +v_backbone: transformer +v_num_layers: 3 +v_attention: position +v_attention_mode: nearest +l_num_layers: 4 +l_use_self_attn: false + +# Training +lr: 3.4e-4 +l_lr: 3e-4 +iter_size: 3 +a_loss_weight: 1. +v_loss_weight: 1. +l_loss_weight: 1. +l_detach: true diff --git a/torch/hub/baudm_parseq_main/configs/model/crnn.yaml b/torch/hub/baudm_parseq_main/configs/model/crnn.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9c109e4f4b66beed5c992268bbc8fa587d305fb6 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/model/crnn.yaml @@ -0,0 +1,9 @@ +name: crnn +_target_: strhub.models.crnn.system.CRNN + +# Architecture +hidden_size: 256 +leaky_relu: false + +# Training +lr: 5.1e-4 diff --git a/torch/hub/baudm_parseq_main/configs/model/parseq.yaml b/torch/hub/baudm_parseq_main/configs/model/parseq.yaml new file mode 100644 index 0000000000000000000000000000000000000000..16c9b09a336e014471876ca370225691db0f3eae --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/model/parseq.yaml @@ -0,0 +1,25 @@ +name: parseq +_target_: strhub.models.parseq.system.PARSeq + +# Data +patch_size: [ 4, 8 ] # [ height, width ] + +# Architecture +embed_dim: 384 +enc_num_heads: 6 +enc_mlp_ratio: 4 +enc_depth: 12 +dec_num_heads: 12 +dec_mlp_ratio: 4 +dec_depth: 1 + +# Training +lr: 7e-4 +perm_num: 6 +perm_forward: true +perm_mirrored: true +dropout: 0.1 + +# Decoding mode (test) +decode_ar: true +refine_iters: 1 diff --git a/torch/hub/baudm_parseq_main/configs/model/trba.yaml b/torch/hub/baudm_parseq_main/configs/model/trba.yaml new file mode 100644 index 0000000000000000000000000000000000000000..717e4642993de65717ae35240ac16bfe82d7f3a5 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/model/trba.yaml @@ -0,0 +1,10 @@ +name: trba +_target_: strhub.models.trba.system.TRBA + +# Architecture +num_fiducial: 20 +output_channel: 512 +hidden_size: 256 + +# Training +lr: 6.9e-4 diff --git a/torch/hub/baudm_parseq_main/configs/model/vitstr.yaml b/torch/hub/baudm_parseq_main/configs/model/vitstr.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a82074261546c574c7ff5d412e54391f7987a071 --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/model/vitstr.yaml @@ -0,0 +1,13 @@ +name: vitstr +_target_: strhub.models.vitstr.system.ViTSTR + +# Data +img_size: [ 224, 224 ] # [ height, width ] +patch_size: [ 16, 16 ] # [ height, width ] + +# Architecture +embed_dim: 384 +num_heads: 6 + +# Training +lr: 8.9e-4 diff --git a/torch/hub/baudm_parseq_main/configs/tune.yaml b/torch/hub/baudm_parseq_main/configs/tune.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6d0a22fded9efc06e0fc5646ce75f1ddeff448dc --- /dev/null +++ b/torch/hub/baudm_parseq_main/configs/tune.yaml @@ -0,0 +1,18 @@ +defaults: + - main + - _self_ + +trainer: + devices: 1 # tuning with DDP is not yet supported. + +tune: + num_samples: 10 + gpus_per_trial: 1 + lr: + min: 1e-4 + max: 2e-3 + resume_dir: null + +hydra: + run: + dir: ray_results/${model.name}/${now:%Y-%m-%d}_${now:%H-%M-%S} diff --git a/torch/hub/baudm_parseq_main/demo_images/art-01107.jpg b/torch/hub/baudm_parseq_main/demo_images/art-01107.jpg new file mode 100644 index 0000000000000000000000000000000000000000..157b4072f62ccee9ac1564d140b3b720975ffdf9 Binary files /dev/null and b/torch/hub/baudm_parseq_main/demo_images/art-01107.jpg differ diff --git a/torch/hub/baudm_parseq_main/demo_images/coco-1166773.jpg b/torch/hub/baudm_parseq_main/demo_images/coco-1166773.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ecfad882117f310e2cf3f9affc28e17a86e42d31 Binary files /dev/null and b/torch/hub/baudm_parseq_main/demo_images/coco-1166773.jpg differ diff --git a/torch/hub/baudm_parseq_main/demo_images/cute-184.jpg b/torch/hub/baudm_parseq_main/demo_images/cute-184.jpg new file mode 100644 index 0000000000000000000000000000000000000000..62e9de81211da6cb948c5b246aa18ce3689be122 Binary files /dev/null and b/torch/hub/baudm_parseq_main/demo_images/cute-184.jpg differ diff --git a/torch/hub/baudm_parseq_main/demo_images/ic13_word_256.png b/torch/hub/baudm_parseq_main/demo_images/ic13_word_256.png new file mode 100644 index 0000000000000000000000000000000000000000..381b841f8a65c3047878f2d02ab6960a13abe5e4 Binary files /dev/null and b/torch/hub/baudm_parseq_main/demo_images/ic13_word_256.png differ diff --git a/torch/hub/baudm_parseq_main/demo_images/ic15_word_26.png b/torch/hub/baudm_parseq_main/demo_images/ic15_word_26.png new file mode 100644 index 0000000000000000000000000000000000000000..a638fb30ea699922ecc2dd2a17a59770728cd236 Binary files /dev/null and b/torch/hub/baudm_parseq_main/demo_images/ic15_word_26.png differ diff --git a/torch/hub/baudm_parseq_main/demo_images/uber-27491.jpg b/torch/hub/baudm_parseq_main/demo_images/uber-27491.jpg new file mode 100644 index 0000000000000000000000000000000000000000..845f6c5b973c26527f91f29dc2f065ca850d59fc Binary files /dev/null and b/torch/hub/baudm_parseq_main/demo_images/uber-27491.jpg differ diff --git a/torch/hub/baudm_parseq_main/hubconf.py b/torch/hub/baudm_parseq_main/hubconf.py new file mode 100644 index 0000000000000000000000000000000000000000..143a8d6d69d3d439436ad22125d40aab478868ad --- /dev/null +++ b/torch/hub/baudm_parseq_main/hubconf.py @@ -0,0 +1,66 @@ +from strhub.models.utils import create_model + +dependencies = ['torch', 'pytorch_lightning', 'timm'] + + +def parseq_tiny(pretrained: bool = False, decode_ar: bool = True, refine_iters: int = 1, **kwargs): + """ + PARSeq tiny model (img_size=128x32, patch_size=8x4, d_model=192) + @param pretrained: (bool) Use pretrained weights + @param decode_ar: (bool) use AR decoding + @param refine_iters: (int) number of refinement iterations to use + """ + return create_model('parseq-tiny', pretrained, decode_ar=decode_ar, refine_iters=refine_iters, **kwargs) + + +def parseq(pretrained: bool = False, decode_ar: bool = True, refine_iters: int = 1, **kwargs): + """ + PARSeq base model (img_size=128x32, patch_size=8x4, d_model=384) + @param pretrained: (bool) Use pretrained weights + @param decode_ar: (bool) use AR decoding + @param refine_iters: (int) number of refinement iterations to use + """ + return create_model('parseq', pretrained, decode_ar=decode_ar, refine_iters=refine_iters, **kwargs) + + +def parseq_patch16_224(pretrained: bool = False, decode_ar: bool = True, refine_iters: int = 1, **kwargs): + """ + PARSeq base model (img_size=224x224, patch_size=16x16, d_model=384) + @param pretrained: (bool) Use pretrained weights + @param decode_ar: (bool) use AR decoding + @param refine_iters: (int) number of refinement iterations to use + """ + return create_model('parseq-patch16-224', pretrained, decode_ar=decode_ar, refine_iters=refine_iters, **kwargs) + + +def abinet(pretrained: bool = False, iter_size: int = 3, **kwargs): + """ + ABINet model (img_size=128x32) + @param pretrained: (bool) Use pretrained weights + @param iter_size: (int) number of refinement iterations to use + """ + return create_model('abinet', pretrained, iter_size=iter_size, **kwargs) + + +def trba(pretrained: bool = False, **kwargs): + """ + TRBA model (img_size=128x32) + @param pretrained: (bool) Use pretrained weights + """ + return create_model('trba', pretrained, **kwargs) + + +def vitstr(pretrained: bool = False, **kwargs): + """ + ViTSTR small model (img_size=128x32, patch_size=8x4, d_model=384) + @param pretrained: (bool) Use pretrained weights + """ + return create_model('vitstr', pretrained, **kwargs) + + +def crnn(pretrained: bool = False, **kwargs): + """ + CRNN model (img_size=128x32) + @param pretrained: (bool) Use pretrained weights + """ + return create_model('crnn', pretrained, **kwargs) diff --git a/torch/hub/baudm_parseq_main/pyproject.toml b/torch/hub/baudm_parseq_main/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8fc583ad1aea4b468b953b74f8bc6991b0274b14 --- /dev/null +++ b/torch/hub/baudm_parseq_main/pyproject.toml @@ -0,0 +1,53 @@ +[build-system] +requires = ["setuptools", "setuptools-scm"] +build-backend = "setuptools.build_meta" + +[project] +name = "strhub" +version = "1.2.0" +description = "Scene Text Recognition Model Hub: A collection of deep learning models for Scene Text Recognition" +authors = [ + {name = "Darwin Bautista", email = "baudm@users.noreply.github.com"}, +] +readme = "README.md" +requires-python = ">=3.9" +dynamic = ["optional-dependencies"] + +[project.urls] +Homepage = "https://github.com/baudm/parseq" + +[tool.setuptools] +packages = ["strhub"] +license-files = ["NOTICE", "LICENSE", "strhub/models/*/LICENSE"] + +[tool.setuptools.dynamic] +optional-dependencies.dev = { file = ["requirements/dev.txt"] } +optional-dependencies.train = { file = ["requirements/train.txt"] } +optional-dependencies.test = { file = ["requirements/test.txt"] } +optional-dependencies.bench = { file = ["requirements/bench.txt"] } +optional-dependencies.tune = { file = ["requirements/tune.txt"] } + +[tool.pyink] +line-length = 120 +pyink-use-majority-quotes = true + +[tool.isort] +py_version = "auto" +profile = "django" +line_length = 120 +ignore_comments = true # To clear unused fmt: skip comments +known_torch = ["torch", "torchvision"] +known_torchlibs = ["timm", "pytorch_lightning"] +sections = ["FUTURE", "STDLIB", "THIRDPARTY", "TORCH", "TORCHLIBS", "FIRSTPARTY", "LOCALFOLDER"] + +[tool.ruff] +fix = true +show-fixes = true +line-length = 120 +output-format = "grouped" + +[tool.ruff.lint.pydocstyle] +convention = "google" + +[tool.ruff.lint.flake8-quotes] +inline-quotes = "single" diff --git a/torch/hub/baudm_parseq_main/read.py b/torch/hub/baudm_parseq_main/read.py new file mode 100644 index 0000000000000000000000000000000000000000..b8117051b34a84e523d03a5231f85777c65d2dc0 --- /dev/null +++ b/torch/hub/baudm_parseq_main/read.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse + +from PIL import Image + +import torch + +from strhub.data.module import SceneTextDataModule +from strhub.models.utils import load_from_checkpoint, parse_model_args + + +@torch.inference_mode() +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('checkpoint', help="Model checkpoint (or 'pretrained=')") + parser.add_argument('--images', nargs='+', help='Images to read') + parser.add_argument('--device', default='cuda') + args, unknown = parser.parse_known_args() + kwargs = parse_model_args(unknown) + print(f'Additional keyword arguments: {kwargs}') + + model = load_from_checkpoint(args.checkpoint, **kwargs).eval().to(args.device) + img_transform = SceneTextDataModule.get_transform(model.hparams.img_size) + + for fname in args.images: + # Load image and prepare for input + image = Image.open(fname).convert('RGB') + image = img_transform(image).unsqueeze(0).to(args.device) + + p = model(image).softmax(-1) + pred, p = model.tokenizer.decode(p) + print(f'{fname}: {pred[0]}') + + +if __name__ == '__main__': + main() diff --git a/torch/hub/baudm_parseq_main/requirements/bench.in b/torch/hub/baudm_parseq_main/requirements/bench.in new file mode 100644 index 0000000000000000000000000000000000000000..4bfecab8d786f84882fb8d5bf7697f31bbb5a3fc --- /dev/null +++ b/torch/hub/baudm_parseq_main/requirements/bench.in @@ -0,0 +1,4 @@ +-c ${CONSTRAINTS} + +hydra-core >=1.2.0 +fvcore diff --git a/torch/hub/baudm_parseq_main/requirements/bench.txt b/torch/hub/baudm_parseq_main/requirements/bench.txt new file mode 100644 index 0000000000000000000000000000000000000000..6c2c849fe84d025d212385b19397a225341cc665 --- /dev/null +++ b/torch/hub/baudm_parseq_main/requirements/bench.txt @@ -0,0 +1,15 @@ +antlr4-python3-runtime==4.9.3 +fvcore==0.1.5.post20221221 +hydra-core==1.3.2 +iopath==0.1.10 +numpy==1.26.4 +omegaconf==2.3.0 +packaging==23.2 +pillow==10.2.0 +portalocker==2.8.2 +pyyaml==6.0.1 +tabulate==0.9.0 +termcolor==2.4.0 +tqdm==4.66.2 +typing-extensions==4.9.0 +yacs==0.1.8 diff --git a/torch/hub/baudm_parseq_main/requirements/constraints.txt b/torch/hub/baudm_parseq_main/requirements/constraints.txt new file mode 100644 index 0000000000000000000000000000000000000000..b2b4887fe5ea48d2e22461ec5c394c9c4a1d01ce --- /dev/null +++ b/torch/hub/baudm_parseq_main/requirements/constraints.txt @@ -0,0 +1,400 @@ +--extra-index-url https://download.pytorch.org/whl/cpu + +aiohttp==3.9.3 + # via fsspec +aiosignal==1.3.1 + # via + # aiohttp + # ray +antlr4-python3-runtime==4.9.3 + # via + # hydra-core + # omegaconf +asttokens==2.4.1 + # via stack-data +async-timeout==4.0.3 + # via aiohttp +attrs==23.2.0 + # via + # aiohttp + # jsonschema + # referencing +ax-platform==0.3.6 + # via -r requirements/tune.in +botorch==0.9.5 + # via ax-platform +certifi==2024.2.2 + # via requests +cfgv==3.4.0 + # via pre-commit +charset-normalizer==3.3.2 + # via requests +click==8.1.7 + # via + # nltk + # ray +comm==0.2.1 + # via ipywidgets +contourpy==1.2.0 + # via matplotlib +cycler==0.12.1 + # via matplotlib +decorator==5.1.1 + # via ipython +distlib==0.3.8 + # via virtualenv +exceptiongroup==1.2.0 + # via ipython +executing==2.0.1 + # via stack-data +filelock==3.13.1 + # via + # huggingface-hub + # ray + # torch + # virtualenv +fonttools==4.49.0 + # via matplotlib +frozenlist==1.4.1 + # via + # aiohttp + # aiosignal + # ray +fsspec==2024.2.0 + # via + # huggingface-hub + # pytorch-lightning + # ray + # torch +fvcore==0.1.5.post20221221 + # via -r requirements/bench.in +gpytorch==1.11 + # via botorch +huggingface-hub==0.20.3 + # via timm +hydra-core==1.3.2 + # via + # -r requirements/bench.in + # -r requirements/train.in + # -r requirements/tune.in +identify==2.5.35 + # via pre-commit +idna==3.6 + # via + # requests + # yarl +imageio==2.34.0 + # via + # imgaug + # scikit-image +imgaug==0.4.0 + # via + # -r requirements/train.in + # -r requirements/tune.in +importlib-resources==6.1.1 + # via matplotlib +iopath==0.1.10 + # via fvcore +ipython==8.18.1 + # via ipywidgets +ipywidgets==8.1.2 + # via ax-platform +jaxtyping==0.2.25 + # via linear-operator +jedi==0.19.1 + # via ipython +jinja2==3.1.3 + # via + # ax-platform + # torch +joblib==1.3.2 + # via + # nltk + # scikit-learn +jsonschema==4.21.1 + # via ray +jsonschema-specifications==2023.12.1 + # via jsonschema +jupyterlab-widgets==3.0.10 + # via ipywidgets +kiwisolver==1.4.5 + # via matplotlib +lazy-loader==0.3 + # via scikit-image +lightning-utilities==0.10.1 + # via + # pytorch-lightning + # torchmetrics +linear-operator==0.5.1 + # via + # botorch + # gpytorch +lmdb==1.4.1 + # via + # -r requirements/test.in + # -r requirements/train.in + # -r requirements/tune.in +markupsafe==2.1.5 + # via jinja2 +matplotlib==3.8.3 + # via imgaug +matplotlib-inline==0.1.6 + # via ipython +mpmath==1.3.0 + # via sympy +msgpack==1.0.7 + # via ray +multidict==6.0.5 + # via + # aiohttp + # yarl +multipledispatch==1.0.0 + # via botorch +mypy-extensions==1.0.0 + # via typing-inspect +networkx==3.2.1 + # via + # scikit-image + # torch +nltk==3.8.1 + # via -r requirements/core.in +nodeenv==1.8.0 + # via pre-commit +numpy==1.26.4 + # via + # contourpy + # fvcore + # imageio + # imgaug + # jaxtyping + # matplotlib + # opencv-python + # opt-einsum + # pandas + # pyarrow + # pyro-ppl + # pytorch-lightning + # scikit-image + # scikit-learn + # scipy + # shapely + # tensorboardx + # tifffile + # torchmetrics + # torchvision +omegaconf==2.3.0 + # via hydra-core +opencv-python==4.9.0.80 + # via imgaug +opt-einsum==3.3.0 + # via pyro-ppl +packaging==23.2 + # via + # huggingface-hub + # hydra-core + # lightning-utilities + # matplotlib + # plotly + # pytorch-lightning + # ray + # scikit-image + # tensorboardx + # torchmetrics +pandas==2.2.0 + # via + # ax-platform + # ray +parso==0.8.3 + # via jedi +pexpect==4.9.0 + # via ipython +pillow==10.2.0 + # via + # -r requirements/test.in + # -r requirements/train.in + # -r requirements/tune.in + # fvcore + # imageio + # imgaug + # matplotlib + # scikit-image + # torchvision +platformdirs==4.2.0 + # via virtualenv +plotly==5.19.0 + # via ax-platform +portalocker==2.8.2 + # via iopath +pre-commit==3.6.2 + # via -r requirements/dev.in +prompt-toolkit==3.0.43 + # via ipython +protobuf==4.25.3 + # via + # ray + # tensorboardx +ptyprocess==0.7.0 + # via pexpect +pure-eval==0.2.2 + # via stack-data +pyarrow==15.0.0 + # via ray +pygments==2.17.2 + # via ipython +pyparsing==3.1.1 + # via matplotlib +pyre-extensions==0.0.30 + # via ax-platform +pyro-api==0.1.2 + # via pyro-ppl +pyro-ppl==1.9.0 + # via botorch +python-dateutil==2.8.2 + # via + # matplotlib + # pandas +pytorch-lightning==2.2.0.post0 + # via -r requirements/core.in +pytz==2024.1 + # via pandas +pyyaml==6.0.1 + # via + # -r requirements/core.in + # fvcore + # huggingface-hub + # omegaconf + # pre-commit + # pytorch-lightning + # ray + # timm + # yacs +ray==2.9.2 + # via -r requirements/tune.in +referencing==0.33.0 + # via + # jsonschema + # jsonschema-specifications +regex==2023.12.25 + # via nltk +requests==2.31.0 + # via + # huggingface-hub + # ray +rpds-py==0.18.0 + # via + # jsonschema + # referencing +safetensors==0.4.2 + # via timm +scikit-image==0.22.0 + # via imgaug +scikit-learn==1.4.1.post1 + # via + # ax-platform + # gpytorch +scipy==1.12.0 + # via + # ax-platform + # botorch + # imgaug + # linear-operator + # scikit-image + # scikit-learn +shapely==2.0.3 + # via imgaug +six==1.16.0 + # via + # asttokens + # imgaug + # python-dateutil +stack-data==0.6.3 + # via ipython +sympy==1.12 + # via torch +tabulate==0.9.0 + # via fvcore +tenacity==8.2.3 + # via plotly +tensorboardx==2.6.2.2 + # via + # -r requirements/train.in + # ray +termcolor==2.4.0 + # via fvcore +threadpoolctl==3.3.0 + # via scikit-learn +tifffile==2024.2.12 + # via scikit-image +timm==0.9.16 + # via -r requirements/core.in +torch==2.2.1+cpu + # via + # -r requirements/core.in + # botorch + # linear-operator + # pyro-ppl + # pytorch-lightning + # timm + # torchmetrics + # torchvision +torchmetrics==1.3.1 + # via pytorch-lightning +torchvision==0.17.1+cpu + # via + # -r requirements/core.in + # timm +tqdm==4.66.2 + # via + # -r requirements/test.in + # fvcore + # huggingface-hub + # iopath + # nltk + # pyro-ppl + # pytorch-lightning +traitlets==5.14.1 + # via + # comm + # ipython + # ipywidgets + # matplotlib-inline +typeguard==2.13.3 + # via + # ax-platform + # jaxtyping + # linear-operator +typing-extensions==4.9.0 + # via + # huggingface-hub + # iopath + # ipython + # jaxtyping + # lightning-utilities + # pyre-extensions + # pytorch-lightning + # torch + # typing-inspect +typing-inspect==0.9.0 + # via pyre-extensions +tzdata==2024.1 + # via pandas +urllib3==2.2.1 + # via requests +virtualenv==20.25.1 + # via pre-commit +wcwidth==0.2.13 + # via prompt-toolkit +widgetsnbextension==4.0.10 + # via ipywidgets +yacs==0.1.8 + # via fvcore +yarl==1.9.4 + # via aiohttp +zipp==3.17.0 + # via importlib-resources + +# The following packages are considered to be unsafe in a requirements file: +setuptools==69.1.0 + # via + # lightning-utilities + # nodeenv diff --git a/torch/hub/baudm_parseq_main/requirements/core.in b/torch/hub/baudm_parseq_main/requirements/core.in new file mode 100644 index 0000000000000000000000000000000000000000..1398419b26a7dc9cffc65566c5802aa081ae22e8 --- /dev/null +++ b/torch/hub/baudm_parseq_main/requirements/core.in @@ -0,0 +1,8 @@ +-c ${CONSTRAINTS} + +torch >=2.0.0 +torchvision >=0.15.0 +timm >=0.6.5 +pytorch-lightning >=2.0.0 # TODO: refactor code to separate model from training code. +nltk >=3.7.0 # TODO: refactor/reorganize code. This is a train/test dependency. +PyYAML >=6.0.0 # TODO: can we move this to train/test? diff --git a/torch/hub/baudm_parseq_main/requirements/core.txt b/torch/hub/baudm_parseq_main/requirements/core.txt new file mode 100644 index 0000000000000000000000000000000000000000..b33d6452d69b1962445581919ae093b90fad2c89 --- /dev/null +++ b/torch/hub/baudm_parseq_main/requirements/core.txt @@ -0,0 +1,42 @@ +--extra-index-url https://download.pytorch.org/whl/cpu + +aiohttp==3.9.3 +aiosignal==1.3.1 +async-timeout==4.0.3 +attrs==23.2.0 +certifi==2024.2.2 +charset-normalizer==3.3.2 +click==8.1.7 +filelock==3.13.1 +frozenlist==1.4.1 +fsspec==2024.2.0 +huggingface-hub==0.20.3 +idna==3.6 +jinja2==3.1.3 +joblib==1.3.2 +lightning-utilities==0.10.1 +markupsafe==2.1.5 +mpmath==1.3.0 +multidict==6.0.5 +networkx==3.2.1 +nltk==3.8.1 +numpy==1.26.4 +packaging==23.2 +pillow==10.2.0 +pytorch-lightning==2.2.0.post0 +pyyaml==6.0.1 +regex==2023.12.25 +requests==2.31.0 +safetensors==0.4.2 +sympy==1.12 +timm==0.9.16 +torch==2.2.1+cpu +torchmetrics==1.3.1 +torchvision==0.17.1+cpu +tqdm==4.66.2 +typing-extensions==4.9.0 +urllib3==2.2.1 +yarl==1.9.4 + +# The following packages are considered to be unsafe in a requirements file: +setuptools==69.1.0 diff --git a/torch/hub/baudm_parseq_main/requirements/dev.in b/torch/hub/baudm_parseq_main/requirements/dev.in new file mode 100644 index 0000000000000000000000000000000000000000..b170182557d0831e7e91c420dbe57bfc4042f114 --- /dev/null +++ b/torch/hub/baudm_parseq_main/requirements/dev.in @@ -0,0 +1,3 @@ +-c ${CONSTRAINTS} + +pre-commit diff --git a/torch/hub/baudm_parseq_main/requirements/dev.txt b/torch/hub/baudm_parseq_main/requirements/dev.txt new file mode 100644 index 0000000000000000000000000000000000000000..b4881f41f0c31137734a5e28658f4550450a2407 --- /dev/null +++ b/torch/hub/baudm_parseq_main/requirements/dev.txt @@ -0,0 +1,11 @@ +cfgv==3.4.0 +distlib==0.3.8 +filelock==3.13.1 +identify==2.5.35 +nodeenv==1.8.0 +platformdirs==4.2.0 +pre-commit==3.6.2 +pyyaml==6.0.1 +virtualenv==20.25.1 +# The following packages are considered to be unsafe in a requirements file: +setuptools==69.1.0 diff --git a/torch/hub/baudm_parseq_main/requirements/test.in b/torch/hub/baudm_parseq_main/requirements/test.in new file mode 100644 index 0000000000000000000000000000000000000000..76613bb5236e07a9c69354757b3f94a11212a930 --- /dev/null +++ b/torch/hub/baudm_parseq_main/requirements/test.in @@ -0,0 +1,5 @@ +-c ${CONSTRAINTS} + +lmdb +Pillow +tqdm diff --git a/torch/hub/baudm_parseq_main/requirements/test.txt b/torch/hub/baudm_parseq_main/requirements/test.txt new file mode 100644 index 0000000000000000000000000000000000000000..09ba9d93a4f1aa1ea29c2daf2c6f39ffaec9b201 --- /dev/null +++ b/torch/hub/baudm_parseq_main/requirements/test.txt @@ -0,0 +1,3 @@ +lmdb==1.4.1 +pillow==10.2.0 +tqdm==4.66.2 diff --git a/torch/hub/baudm_parseq_main/requirements/train.in b/torch/hub/baudm_parseq_main/requirements/train.in new file mode 100644 index 0000000000000000000000000000000000000000..1fa8d896b753c949f4374106b875ae0a1012c215 --- /dev/null +++ b/torch/hub/baudm_parseq_main/requirements/train.in @@ -0,0 +1,7 @@ +-c ${CONSTRAINTS} + +lmdb +Pillow +imgaug +hydra-core >=1.2.0 +tensorboardx diff --git a/torch/hub/baudm_parseq_main/requirements/train.txt b/torch/hub/baudm_parseq_main/requirements/train.txt new file mode 100644 index 0000000000000000000000000000000000000000..d30f8ed837986d468c07f4158620df7f29431766 --- /dev/null +++ b/torch/hub/baudm_parseq_main/requirements/train.txt @@ -0,0 +1,29 @@ +antlr4-python3-runtime==4.9.3 +contourpy==1.2.0 +cycler==0.12.1 +fonttools==4.49.0 +hydra-core==1.3.2 +imageio==2.34.0 +imgaug==0.4.0 +importlib-resources==6.1.1 +kiwisolver==1.4.5 +lazy-loader==0.3 +lmdb==1.4.1 +matplotlib==3.8.3 +networkx==3.2.1 +numpy==1.26.4 +omegaconf==2.3.0 +opencv-python==4.9.0.80 +packaging==23.2 +pillow==10.2.0 +protobuf==4.25.3 +pyparsing==3.1.1 +python-dateutil==2.8.2 +pyyaml==6.0.1 +scikit-image==0.22.0 +scipy==1.12.0 +shapely==2.0.3 +six==1.16.0 +tensorboardx==2.6.2.2 +tifffile==2024.2.12 +zipp==3.17.0 diff --git a/torch/hub/baudm_parseq_main/requirements/tune.in b/torch/hub/baudm_parseq_main/requirements/tune.in new file mode 100644 index 0000000000000000000000000000000000000000..db1be249279bb821c035c41ef7c29885103948bc --- /dev/null +++ b/torch/hub/baudm_parseq_main/requirements/tune.in @@ -0,0 +1,8 @@ +-c ${CONSTRAINTS} + +lmdb +Pillow +imgaug +hydra-core >=1.2.0 +ray[tune] >=2.0.0 +ax-platform diff --git a/torch/hub/baudm_parseq_main/requirements/tune.txt b/torch/hub/baudm_parseq_main/requirements/tune.txt new file mode 100644 index 0000000000000000000000000000000000000000..86ed86985ef8a88a5a72312e9c48748fcf306d36 --- /dev/null +++ b/torch/hub/baudm_parseq_main/requirements/tune.txt @@ -0,0 +1,94 @@ +aiosignal==1.3.1 +antlr4-python3-runtime==4.9.3 +asttokens==2.4.1 +attrs==23.2.0 +ax-platform==0.3.6 +botorch==0.9.5 +certifi==2024.2.2 +charset-normalizer==3.3.2 +click==8.1.7 +comm==0.2.1 +contourpy==1.2.0 +cycler==0.12.1 +decorator==5.1.1 +exceptiongroup==1.2.0 +executing==2.0.1 +filelock==3.13.1 +fonttools==4.49.0 +frozenlist==1.4.1 +fsspec==2024.2.0 +gpytorch==1.11 +hydra-core==1.3.2 +idna==3.6 +imageio==2.34.0 +imgaug==0.4.0 +importlib-resources==6.1.1 +ipython==8.18.1 +ipywidgets==8.1.2 +jaxtyping==0.2.25 +jedi==0.19.1 +jinja2==3.1.3 +joblib==1.3.2 +jsonschema==4.21.1 +jsonschema-specifications==2023.12.1 +jupyterlab-widgets==3.0.10 +kiwisolver==1.4.5 +lazy-loader==0.3 +linear-operator==0.5.1 +lmdb==1.4.1 +markupsafe==2.1.5 +matplotlib==3.8.3 +matplotlib-inline==0.1.6 +mpmath==1.3.0 +msgpack==1.0.7 +multipledispatch==1.0.0 +mypy-extensions==1.0.0 +networkx==3.2.1 +numpy==1.26.4 +omegaconf==2.3.0 +opencv-python==4.9.0.80 +opt-einsum==3.3.0 +packaging==23.2 +pandas==2.2.0 +parso==0.8.3 +pexpect==4.9.0 +pillow==10.2.0 +plotly==5.19.0 +prompt-toolkit==3.0.43 +protobuf==4.25.3 +ptyprocess==0.7.0 +pure-eval==0.2.2 +pyarrow==15.0.0 +pygments==2.17.2 +pyparsing==3.1.1 +pyre-extensions==0.0.30 +pyro-api==0.1.2 +pyro-ppl==1.9.0 +python-dateutil==2.8.2 +pytz==2024.1 +pyyaml==6.0.1 +ray==2.9.2 +referencing==0.33.0 +requests==2.31.0 +rpds-py==0.18.0 +scikit-image==0.22.0 +scikit-learn==1.4.1.post1 +scipy==1.12.0 +shapely==2.0.3 +six==1.16.0 +stack-data==0.6.3 +sympy==1.12 +tenacity==8.2.3 +tensorboardx==2.6.2.2 +threadpoolctl==3.3.0 +tifffile==2024.2.12 +tqdm==4.66.2 +traitlets==5.14.1 +typeguard==2.13.3 +typing-extensions==4.9.0 +typing-inspect==0.9.0 +tzdata==2024.1 +urllib3==2.2.1 +wcwidth==0.2.13 +widgetsnbextension==4.0.10 +zipp==3.17.0 diff --git a/torch/hub/baudm_parseq_main/strhub/.DS_Store b/torch/hub/baudm_parseq_main/strhub/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..51a67e17070309cd63437d5a0f00567b607d306b Binary files /dev/null and b/torch/hub/baudm_parseq_main/strhub/.DS_Store differ diff --git a/torch/hub/baudm_parseq_main/strhub/__init__.py b/torch/hub/baudm_parseq_main/strhub/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/torch/hub/baudm_parseq_main/strhub/data/__init__.py b/torch/hub/baudm_parseq_main/strhub/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/torch/hub/baudm_parseq_main/strhub/data/aa_overrides.py b/torch/hub/baudm_parseq_main/strhub/data/aa_overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..ef374e2e4166c3847d80d30bab2b0eb6ba88d70c --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/data/aa_overrides.py @@ -0,0 +1,46 @@ +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Extends default ops to accept optional parameters.""" +from functools import partial + +from timm.data.auto_augment import _LEVEL_DENOM, LEVEL_TO_ARG, NAME_TO_OP, _randomly_negate, rotate + + +def rotate_expand(img, degrees, **kwargs): + """Rotate operation with expand=True to avoid cutting off the characters""" + kwargs['expand'] = True + return rotate(img, degrees, **kwargs) + + +def _level_to_arg(level, hparams, key, default): + magnitude = hparams.get(key, default) + level = (level / _LEVEL_DENOM) * magnitude + level = _randomly_negate(level) + return (level,) + + +def apply(): + # Overrides + NAME_TO_OP.update({ + 'Rotate': rotate_expand, + }) + LEVEL_TO_ARG.update({ + 'Rotate': partial(_level_to_arg, key='rotate_deg', default=30.0), + 'ShearX': partial(_level_to_arg, key='shear_x_pct', default=0.3), + 'ShearY': partial(_level_to_arg, key='shear_y_pct', default=0.3), + 'TranslateXRel': partial(_level_to_arg, key='translate_x_pct', default=0.45), + 'TranslateYRel': partial(_level_to_arg, key='translate_y_pct', default=0.45), + }) diff --git a/torch/hub/baudm_parseq_main/strhub/data/augment.py b/torch/hub/baudm_parseq_main/strhub/data/augment.py new file mode 100644 index 0000000000000000000000000000000000000000..ed8832503693863907640b83d5771de90ed6e773 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/data/augment.py @@ -0,0 +1,112 @@ +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from functools import partial + +import imgaug.augmenters as iaa +import numpy as np +from PIL import Image, ImageFilter + +from timm.data import auto_augment + +from strhub.data import aa_overrides + +aa_overrides.apply() + +_OP_CACHE = {} + + +def _get_op(key, factory): + try: + op = _OP_CACHE[key] + except KeyError: + op = factory() + _OP_CACHE[key] = op + return op + + +def _get_param(level, img, max_dim_factor, min_level=1): + max_level = max(min_level, max_dim_factor * max(img.size)) + return round(min(level, max_level)) + + +def gaussian_blur(img, radius, **__): + radius = _get_param(radius, img, 0.02) + key = 'gaussian_blur_' + str(radius) + op = _get_op(key, lambda: ImageFilter.GaussianBlur(radius)) + return img.filter(op) + + +def motion_blur(img, k, **__): + k = _get_param(k, img, 0.08, 3) | 1 # bin to odd values + key = 'motion_blur_' + str(k) + op = _get_op(key, lambda: iaa.MotionBlur(k)) + return Image.fromarray(op(image=np.asarray(img))) + + +def gaussian_noise(img, scale, **_): + scale = _get_param(scale, img, 0.25) | 1 # bin to odd values + key = 'gaussian_noise_' + str(scale) + op = _get_op(key, lambda: iaa.AdditiveGaussianNoise(scale=scale)) + return Image.fromarray(op(image=np.asarray(img))) + + +def poisson_noise(img, lam, **_): + lam = _get_param(lam, img, 0.2) | 1 # bin to odd values + key = 'poisson_noise_' + str(lam) + op = _get_op(key, lambda: iaa.AdditivePoissonNoise(lam)) + return Image.fromarray(op(image=np.asarray(img))) + + +def _level_to_arg(level, _hparams, max): + level = max * level / auto_augment._LEVEL_DENOM + return (level,) + + +_RAND_TRANSFORMS = auto_augment._RAND_INCREASING_TRANSFORMS.copy() +_RAND_TRANSFORMS.remove('SharpnessIncreasing') # remove, interferes with *blur ops +_RAND_TRANSFORMS.extend([ + 'GaussianBlur', + # 'MotionBlur', + # 'GaussianNoise', + 'PoissonNoise', +]) +auto_augment.LEVEL_TO_ARG.update({ + 'GaussianBlur': partial(_level_to_arg, max=4), + 'MotionBlur': partial(_level_to_arg, max=20), + 'GaussianNoise': partial(_level_to_arg, max=0.1 * 255), + 'PoissonNoise': partial(_level_to_arg, max=40), +}) +auto_augment.NAME_TO_OP.update({ + 'GaussianBlur': gaussian_blur, + 'MotionBlur': motion_blur, + 'GaussianNoise': gaussian_noise, + 'PoissonNoise': poisson_noise, +}) + + +def rand_augment_transform(magnitude=5, num_layers=3): + # These are tuned for magnitude=5, which means that effective magnitudes are half of these values. + hparams = { + 'rotate_deg': 30, + 'shear_x_pct': 0.9, + 'shear_y_pct': 0.2, + 'translate_x_pct': 0.10, + 'translate_y_pct': 0.30, + } + ra_ops = auto_augment.rand_augment_ops(magnitude, hparams=hparams, transforms=_RAND_TRANSFORMS) + # Supply weights to disable replacement in random selection (i.e. avoid applying the same op twice) + choice_weights = [1.0 / len(ra_ops) for _ in range(len(ra_ops))] + return auto_augment.RandAugment(ra_ops, num_layers, choice_weights) diff --git a/torch/hub/baudm_parseq_main/strhub/data/dataset.py b/torch/hub/baudm_parseq_main/strhub/data/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..0b73c39b212232ad90e7d540f7bbe5719d1da46e --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/data/dataset.py @@ -0,0 +1,148 @@ +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import glob +import io +import logging +import unicodedata +from pathlib import Path, PurePath +from typing import Callable, Optional, Union + +import lmdb +from PIL import Image + +from torch.utils.data import ConcatDataset, Dataset + +from strhub.data.utils import CharsetAdapter + +log = logging.getLogger(__name__) + + +def build_tree_dataset(root: Union[PurePath, str], *args, **kwargs): + try: + kwargs.pop('root') # prevent 'root' from being passed via kwargs + except KeyError: + pass + root = Path(root).absolute() + log.info(f'dataset root:\t{root}') + datasets = [] + for mdb in glob.glob(str(root / '**/data.mdb'), recursive=True): + mdb = Path(mdb) + ds_name = str(mdb.parent.relative_to(root)) + ds_root = str(mdb.parent.absolute()) + dataset = LmdbDataset(ds_root, *args, **kwargs) + log.info(f'\tlmdb:\t{ds_name}\tnum samples: {len(dataset)}') + datasets.append(dataset) + return ConcatDataset(datasets) + + +class LmdbDataset(Dataset): + """Dataset interface to an LMDB database. + + It supports both labelled and unlabelled datasets. For unlabelled datasets, the image index itself is returned + as the label. Unicode characters are normalized by default. Case-sensitivity is inferred from the charset. + Labels are transformed according to the charset. + """ + + def __init__( + self, + root: str, + charset: str, + max_label_len: int, + min_image_dim: int = 0, + remove_whitespace: bool = True, + normalize_unicode: bool = True, + unlabelled: bool = False, + transform: Optional[Callable] = None, + ): + self._env = None + self.root = root + self.unlabelled = unlabelled + self.transform = transform + self.labels = [] + self.filtered_index_list = [] + self.num_samples = self._preprocess_labels( + charset, remove_whitespace, normalize_unicode, max_label_len, min_image_dim + ) + + def __del__(self): + if self._env is not None: + self._env.close() + self._env = None + + def _create_env(self): + return lmdb.open( + self.root, max_readers=1, readonly=True, create=False, readahead=False, meminit=False, lock=False + ) + + @property + def env(self): + if self._env is None: + self._env = self._create_env() + return self._env + + def _preprocess_labels(self, charset, remove_whitespace, normalize_unicode, max_label_len, min_image_dim): + charset_adapter = CharsetAdapter(charset) + with self._create_env() as env, env.begin() as txn: + num_samples = int(txn.get('num-samples'.encode())) + if self.unlabelled: + return num_samples + for index in range(num_samples): + index += 1 # lmdb starts with 1 + label_key = f'label-{index:09d}'.encode() + label = txn.get(label_key).decode() + # Normally, whitespace is removed from the labels. + if remove_whitespace: + label = ''.join(label.split()) + # Normalize unicode composites (if any) and convert to compatible ASCII characters + if normalize_unicode: + label = unicodedata.normalize('NFKD', label).encode('ascii', 'ignore').decode() + # Filter by length before removing unsupported characters. The original label might be too long. + if len(label) > max_label_len: + continue + label = charset_adapter(label) + # We filter out samples which don't contain any supported characters + if not label: + continue + # Filter images that are too small. + if min_image_dim > 0: + img_key = f'image-{index:09d}'.encode() + buf = io.BytesIO(txn.get(img_key)) + w, h = Image.open(buf).size + if w < self.min_image_dim or h < self.min_image_dim: + continue + self.labels.append(label) + self.filtered_index_list.append(index) + return len(self.labels) + + def __len__(self): + return self.num_samples + + def __getitem__(self, index): + if self.unlabelled: + label = index + else: + label = self.labels[index] + index = self.filtered_index_list[index] + + img_key = f'image-{index:09d}'.encode() + with self.env.begin() as txn: + imgbuf = txn.get(img_key) + buf = io.BytesIO(imgbuf) + img = Image.open(buf).convert('RGB') + + if self.transform is not None: + img = self.transform(img) + + return img, label diff --git a/torch/hub/baudm_parseq_main/strhub/data/module.py b/torch/hub/baudm_parseq_main/strhub/data/module.py new file mode 100644 index 0000000000000000000000000000000000000000..4d6aac7556e10a7584fca8e9a0e419f08e3f2c44 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/data/module.py @@ -0,0 +1,157 @@ +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from pathlib import PurePath +from typing import Callable, Optional, Sequence + +from torch.utils.data import DataLoader +from torchvision import transforms as T + +import pytorch_lightning as pl + +from .dataset import LmdbDataset, build_tree_dataset + + +class SceneTextDataModule(pl.LightningDataModule): + TEST_BENCHMARK_SUB = ('IIIT5k', 'SVT', 'IC13_857', 'IC15_1811', 'SVTP', 'CUTE80') + TEST_BENCHMARK = ('IIIT5k', 'SVT', 'IC13_1015', 'IC15_2077', 'SVTP', 'CUTE80') + TEST_NEW = ('ArT', 'COCOv1.4', 'Uber') + TEST_ALL = tuple(set(TEST_BENCHMARK_SUB + TEST_BENCHMARK + TEST_NEW)) + + def __init__( + self, + root_dir: str, + train_dir: str, + img_size: Sequence[int], + max_label_length: int, + charset_train: str, + charset_test: str, + batch_size: int, + num_workers: int, + augment: bool, + remove_whitespace: bool = True, + normalize_unicode: bool = True, + min_image_dim: int = 0, + rotation: int = 0, + collate_fn: Optional[Callable] = None, + ): + super().__init__() + self.root_dir = root_dir + self.train_dir = train_dir + self.img_size = tuple(img_size) + self.max_label_length = max_label_length + self.charset_train = charset_train + self.charset_test = charset_test + self.batch_size = batch_size + self.num_workers = num_workers + self.augment = augment + self.remove_whitespace = remove_whitespace + self.normalize_unicode = normalize_unicode + self.min_image_dim = min_image_dim + self.rotation = rotation + self.collate_fn = collate_fn + self._train_dataset = None + self._val_dataset = None + + @staticmethod + def get_transform(img_size: tuple[int], augment: bool = False, rotation: int = 0): + transforms = [] + if augment: + from .augment import rand_augment_transform + + transforms.append(rand_augment_transform()) + if rotation: + transforms.append(lambda img: img.rotate(rotation, expand=True)) + transforms.extend([ + T.Resize(img_size, T.InterpolationMode.BICUBIC), + T.ToTensor(), + T.Normalize(0.5, 0.5), + ]) + return T.Compose(transforms) + + @property + def train_dataset(self): + if self._train_dataset is None: + transform = self.get_transform(self.img_size, self.augment) + root = PurePath(self.root_dir, 'train', self.train_dir) + self._train_dataset = build_tree_dataset( + root, + self.charset_train, + self.max_label_length, + self.min_image_dim, + self.remove_whitespace, + self.normalize_unicode, + transform=transform, + ) + return self._train_dataset + + @property + def val_dataset(self): + if self._val_dataset is None: + transform = self.get_transform(self.img_size) + root = PurePath(self.root_dir, 'val') + self._val_dataset = build_tree_dataset( + root, + self.charset_test, + self.max_label_length, + self.min_image_dim, + self.remove_whitespace, + self.normalize_unicode, + transform=transform, + ) + return self._val_dataset + + def train_dataloader(self): + return DataLoader( + self.train_dataset, + batch_size=self.batch_size, + shuffle=True, + num_workers=self.num_workers, + persistent_workers=self.num_workers > 0, + pin_memory=True, + collate_fn=self.collate_fn, + ) + + def val_dataloader(self): + return DataLoader( + self.val_dataset, + batch_size=self.batch_size, + num_workers=self.num_workers, + persistent_workers=self.num_workers > 0, + pin_memory=True, + collate_fn=self.collate_fn, + ) + + def test_dataloaders(self, subset): + transform = self.get_transform(self.img_size, rotation=self.rotation) + root = PurePath(self.root_dir, 'test') + datasets = { + s: LmdbDataset( + str(root / s), + self.charset_test, + self.max_label_length, + self.min_image_dim, + self.remove_whitespace, + self.normalize_unicode, + transform=transform, + ) + for s in subset + } + return { + k: DataLoader( + v, batch_size=self.batch_size, num_workers=self.num_workers, pin_memory=True, collate_fn=self.collate_fn + ) + for k, v in datasets.items() + } diff --git a/torch/hub/baudm_parseq_main/strhub/data/utils.py b/torch/hub/baudm_parseq_main/strhub/data/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..16fd30d0bba424361730b9d1c33016746de23f68 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/data/utils.py @@ -0,0 +1,150 @@ +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import re +from abc import ABC, abstractmethod +from itertools import groupby +from typing import Optional + +import torch +from torch import Tensor +from torch.nn.utils.rnn import pad_sequence + + +class CharsetAdapter: + """Transforms labels according to the target charset.""" + + def __init__(self, target_charset) -> None: + super().__init__() + self.lowercase_only = target_charset == target_charset.lower() + self.uppercase_only = target_charset == target_charset.upper() + self.unsupported = re.compile(f'[^{re.escape(target_charset)}]') + + def __call__(self, label): + if self.lowercase_only: + label = label.lower() + elif self.uppercase_only: + label = label.upper() + # Remove unsupported characters + label = self.unsupported.sub('', label) + return label + + +class BaseTokenizer(ABC): + + def __init__(self, charset: str, specials_first: tuple = (), specials_last: tuple = ()) -> None: + self._itos = specials_first + tuple(charset) + specials_last + self._stoi = {s: i for i, s in enumerate(self._itos)} + + def __len__(self): + return len(self._itos) + + def _tok2ids(self, tokens: str) -> list[int]: + return [self._stoi[s] for s in tokens] + + def _ids2tok(self, token_ids: list[int], join: bool = True) -> str: + tokens = [self._itos[i] for i in token_ids] + return ''.join(tokens) if join else tokens + + @abstractmethod + def encode(self, labels: list[str], device: Optional[torch.device] = None) -> Tensor: + """Encode a batch of labels to a representation suitable for the model. + + Args: + labels: List of labels. Each can be of arbitrary length. + device: Create tensor on this device. + + Returns: + Batched tensor representation padded to the max label length. Shape: N, L + """ + raise NotImplementedError + + @abstractmethod + def _filter(self, probs: Tensor, ids: Tensor) -> tuple[Tensor, list[int]]: + """Internal method which performs the necessary filtering prior to decoding.""" + raise NotImplementedError + + def decode(self, token_dists: Tensor, raw: bool = False) -> tuple[list[str], list[Tensor]]: + """Decode a batch of token distributions. + + Args: + token_dists: softmax probabilities over the token distribution. Shape: N, L, C + raw: return unprocessed labels (will return list of list of strings) + + Returns: + list of string labels (arbitrary length) and + their corresponding sequence probabilities as a list of Tensors + """ + batch_tokens = [] + batch_probs = [] + for dist in token_dists: + probs, ids = dist.max(-1) # greedy selection + if not raw: + probs, ids = self._filter(probs, ids) + tokens = self._ids2tok(ids, not raw) + batch_tokens.append(tokens) + batch_probs.append(probs) + return batch_tokens, batch_probs + + +class Tokenizer(BaseTokenizer): + BOS = '[B]' + EOS = '[E]' + PAD = '[P]' + + def __init__(self, charset: str) -> None: + specials_first = (self.EOS,) + specials_last = (self.BOS, self.PAD) + super().__init__(charset, specials_first, specials_last) + self.eos_id, self.bos_id, self.pad_id = [self._stoi[s] for s in specials_first + specials_last] + + def encode(self, labels: list[str], device: Optional[torch.device] = None) -> Tensor: + batch = [ + torch.as_tensor([self.bos_id] + self._tok2ids(y) + [self.eos_id], dtype=torch.long, device=device) + for y in labels + ] + return pad_sequence(batch, batch_first=True, padding_value=self.pad_id) + + def _filter(self, probs: Tensor, ids: Tensor) -> tuple[Tensor, list[int]]: + ids = ids.tolist() + try: + eos_idx = ids.index(self.eos_id) + except ValueError: + eos_idx = len(ids) # Nothing to truncate. + # Truncate after EOS + ids = ids[:eos_idx] + probs = probs[: eos_idx + 1] # but include prob. for EOS (if it exists) + return probs, ids + + +class CTCTokenizer(BaseTokenizer): + BLANK = '[B]' + + def __init__(self, charset: str) -> None: + # BLANK uses index == 0 by default + super().__init__(charset, specials_first=(self.BLANK,)) + self.blank_id = self._stoi[self.BLANK] + + def encode(self, labels: list[str], device: Optional[torch.device] = None) -> Tensor: + # We use a padded representation since we don't want to use CUDNN's CTC implementation + batch = [torch.as_tensor(self._tok2ids(y), dtype=torch.long, device=device) for y in labels] + return pad_sequence(batch, batch_first=True, padding_value=self.blank_id) + + def _filter(self, probs: Tensor, ids: Tensor) -> tuple[Tensor, list[int]]: + # Best path decoding: + ids = list(zip(*groupby(ids.tolist())))[0] # Remove duplicate tokens + ids = [x for x in ids if x != self.blank_id] # Remove BLANKs + # `probs` is just pass-through since all positions are considered part of the path + return probs, ids diff --git a/torch/hub/baudm_parseq_main/strhub/models/__init__.py b/torch/hub/baudm_parseq_main/strhub/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/torch/hub/baudm_parseq_main/strhub/models/abinet/LICENSE b/torch/hub/baudm_parseq_main/strhub/models/abinet/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2f1d4adb4889b2719f13ed6edf56aed10246a516 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/abinet/LICENSE @@ -0,0 +1,25 @@ +ABINet for non-commercial purposes + +Copyright (c) 2021, USTC +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/torch/hub/baudm_parseq_main/strhub/models/abinet/__init__.py b/torch/hub/baudm_parseq_main/strhub/models/abinet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..604811036fda52d8485eecfebd4ffeb7f7176042 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/abinet/__init__.py @@ -0,0 +1,13 @@ +r""" +Fang, Shancheng, Hongtao, Xie, Yuxin, Wang, Zhendong, Mao, and Yongdong, Zhang. +"Read Like Humans: Autonomous, Bidirectional and Iterative Language Modeling for Scene Text Recognition." . +In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) (pp. 7098-7107).2021. + +https://arxiv.org/abs/2103.06495 + +All source files, except `system.py`, are based on the implementation listed below, +and hence are released under the license of the original. + +Source: https://github.com/FangShancheng/ABINet +License: 2-clause BSD License (see included LICENSE file) +""" diff --git a/torch/hub/baudm_parseq_main/strhub/models/abinet/attention.py b/torch/hub/baudm_parseq_main/strhub/models/abinet/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..cc8fba0638e7444fdffe964f72d0566c1a5bb818 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/abinet/attention.py @@ -0,0 +1,100 @@ +import torch +import torch.nn as nn + +from .transformer import PositionalEncoding + + +class Attention(nn.Module): + def __init__(self, in_channels=512, max_length=25, n_feature=256): + super().__init__() + self.max_length = max_length + + self.f0_embedding = nn.Embedding(max_length, in_channels) + self.w0 = nn.Linear(max_length, n_feature) + self.wv = nn.Linear(in_channels, in_channels) + self.we = nn.Linear(in_channels, max_length) + + self.active = nn.Tanh() + self.softmax = nn.Softmax(dim=2) + + def forward(self, enc_output): + enc_output = enc_output.permute(0, 2, 3, 1).flatten(1, 2) + reading_order = torch.arange(self.max_length, dtype=torch.long, device=enc_output.device) + reading_order = reading_order.unsqueeze(0).expand(enc_output.size(0), -1) # (S,) -> (B, S) + reading_order_embed = self.f0_embedding(reading_order) # b,25,512 + + t = self.w0(reading_order_embed.permute(0, 2, 1)) # b,512,256 + t = self.active(t.permute(0, 2, 1) + self.wv(enc_output)) # b,256,512 + + attn = self.we(t) # b,256,25 + attn = self.softmax(attn.permute(0, 2, 1)) # b,25,256 + g_output = torch.bmm(attn, enc_output) # b,25,512 + return g_output, attn.view(*attn.shape[:2], 8, 32) + + +def encoder_layer(in_c, out_c, k=3, s=2, p=1): + return nn.Sequential(nn.Conv2d(in_c, out_c, k, s, p), + nn.BatchNorm2d(out_c), + nn.ReLU(True)) + + +def decoder_layer(in_c, out_c, k=3, s=1, p=1, mode='nearest', scale_factor=None, size=None): + align_corners = None if mode == 'nearest' else True + return nn.Sequential(nn.Upsample(size=size, scale_factor=scale_factor, + mode=mode, align_corners=align_corners), + nn.Conv2d(in_c, out_c, k, s, p), + nn.BatchNorm2d(out_c), + nn.ReLU(True)) + + +class PositionAttention(nn.Module): + def __init__(self, max_length, in_channels=512, num_channels=64, + h=8, w=32, mode='nearest', **kwargs): + super().__init__() + self.max_length = max_length + self.k_encoder = nn.Sequential( + encoder_layer(in_channels, num_channels, s=(1, 2)), + encoder_layer(num_channels, num_channels, s=(2, 2)), + encoder_layer(num_channels, num_channels, s=(2, 2)), + encoder_layer(num_channels, num_channels, s=(2, 2)) + ) + self.k_decoder = nn.Sequential( + decoder_layer(num_channels, num_channels, scale_factor=2, mode=mode), + decoder_layer(num_channels, num_channels, scale_factor=2, mode=mode), + decoder_layer(num_channels, num_channels, scale_factor=2, mode=mode), + decoder_layer(num_channels, in_channels, size=(h, w), mode=mode) + ) + + self.pos_encoder = PositionalEncoding(in_channels, dropout=0., max_len=max_length) + self.project = nn.Linear(in_channels, in_channels) + + def forward(self, x): + N, E, H, W = x.size() + k, v = x, x # (N, E, H, W) + + # calculate key vector + features = [] + for i in range(0, len(self.k_encoder)): + k = self.k_encoder[i](k) + features.append(k) + for i in range(0, len(self.k_decoder) - 1): + k = self.k_decoder[i](k) + k = k + features[len(self.k_decoder) - 2 - i] + k = self.k_decoder[-1](k) + + # calculate query vector + # TODO q=f(q,k) + zeros = x.new_zeros((self.max_length, N, E)) # (T, N, E) + q = self.pos_encoder(zeros) # (T, N, E) + q = q.permute(1, 0, 2) # (N, T, E) + q = self.project(q) # (N, T, E) + + # calculate attention + attn_scores = torch.bmm(q, k.flatten(2, 3)) # (N, T, (H*W)) + attn_scores = attn_scores / (E ** 0.5) + attn_scores = torch.softmax(attn_scores, dim=-1) + + v = v.permute(0, 2, 3, 1).view(N, -1, E) # (N, (H*W), E) + attn_vecs = torch.bmm(attn_scores, v) # (N, T, E) + + return attn_vecs, attn_scores.view(N, -1, H, W) diff --git a/torch/hub/baudm_parseq_main/strhub/models/abinet/backbone.py b/torch/hub/baudm_parseq_main/strhub/models/abinet/backbone.py new file mode 100644 index 0000000000000000000000000000000000000000..debcabd7f115db0e698a55175a01a0ff0131e10f --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/abinet/backbone.py @@ -0,0 +1,24 @@ +import torch.nn as nn +from torch.nn import TransformerEncoderLayer, TransformerEncoder + +from .resnet import resnet45 +from .transformer import PositionalEncoding + + +class ResTranformer(nn.Module): + def __init__(self, d_model=512, nhead=8, d_inner=2048, dropout=0.1, activation='relu', backbone_ln=2): + super().__init__() + self.resnet = resnet45() + self.pos_encoder = PositionalEncoding(d_model, max_len=8 * 32) + encoder_layer = TransformerEncoderLayer(d_model=d_model, nhead=nhead, + dim_feedforward=d_inner, dropout=dropout, activation=activation) + self.transformer = TransformerEncoder(encoder_layer, backbone_ln) + + def forward(self, images): + feature = self.resnet(images) + n, c, h, w = feature.shape + feature = feature.view(n, c, -1).permute(2, 0, 1) + feature = self.pos_encoder(feature) + feature = self.transformer(feature) + feature = feature.permute(1, 2, 0).view(n, c, h, w) + return feature diff --git a/torch/hub/baudm_parseq_main/strhub/models/abinet/model.py b/torch/hub/baudm_parseq_main/strhub/models/abinet/model.py new file mode 100644 index 0000000000000000000000000000000000000000..cc0cd143d324822c57b897b6e5749024d857fd30 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/abinet/model.py @@ -0,0 +1,31 @@ +import torch +import torch.nn as nn + + +class Model(nn.Module): + + def __init__(self, dataset_max_length: int, null_label: int): + super().__init__() + self.max_length = dataset_max_length + 1 # additional stop token + self.null_label = null_label + + def _get_length(self, logit, dim=-1): + """ Greed decoder to obtain length from logit""" + out = (logit.argmax(dim=-1) == self.null_label) + abn = out.any(dim) + out = ((out.cumsum(dim) == 1) & out).max(dim)[1] + out = out + 1 # additional end token + out = torch.where(abn, out, out.new_tensor(logit.shape[1], device=out.device)) + return out + + @staticmethod + def _get_padding_mask(length, max_length): + length = length.unsqueeze(-1) + grid = torch.arange(0, max_length, device=length.device).unsqueeze(0) + return grid >= length + + @staticmethod + def _get_location_mask(sz, device=None): + mask = torch.eye(sz, device=device) + mask = mask.float().masked_fill(mask == 1, float('-inf')) + return mask diff --git a/torch/hub/baudm_parseq_main/strhub/models/abinet/model_abinet_iter.py b/torch/hub/baudm_parseq_main/strhub/models/abinet/model_abinet_iter.py new file mode 100644 index 0000000000000000000000000000000000000000..1a8523ff6431f991037d56dc8dd72ae67c7bf242 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/abinet/model_abinet_iter.py @@ -0,0 +1,39 @@ +import torch +from torch import nn + +from .model_alignment import BaseAlignment +from .model_language import BCNLanguage +from .model_vision import BaseVision + + +class ABINetIterModel(nn.Module): + def __init__(self, dataset_max_length, null_label, num_classes, iter_size=1, + d_model=512, nhead=8, d_inner=2048, dropout=0.1, activation='relu', + v_loss_weight=1., v_attention='position', v_attention_mode='nearest', + v_backbone='transformer', v_num_layers=2, + l_loss_weight=1., l_num_layers=4, l_detach=True, l_use_self_attn=False, + a_loss_weight=1.): + super().__init__() + self.iter_size = iter_size + self.vision = BaseVision(dataset_max_length, null_label, num_classes, v_attention, v_attention_mode, + v_loss_weight, d_model, nhead, d_inner, dropout, activation, v_backbone, v_num_layers) + self.language = BCNLanguage(dataset_max_length, null_label, num_classes, d_model, nhead, d_inner, dropout, + activation, l_num_layers, l_detach, l_use_self_attn, l_loss_weight) + self.alignment = BaseAlignment(dataset_max_length, null_label, num_classes, d_model, a_loss_weight) + + def forward(self, images): + v_res = self.vision(images) + a_res = v_res + all_l_res, all_a_res = [], [] + for _ in range(self.iter_size): + tokens = torch.softmax(a_res['logits'], dim=-1) + lengths = a_res['pt_lengths'] + lengths.clamp_(2, self.language.max_length) # TODO:move to langauge model + l_res = self.language(tokens, lengths) + all_l_res.append(l_res) + a_res = self.alignment(l_res['feature'], v_res['feature']) + all_a_res.append(a_res) + if self.training: + return all_a_res, all_l_res, v_res + else: + return a_res, all_l_res[-1], v_res diff --git a/torch/hub/baudm_parseq_main/strhub/models/abinet/model_alignment.py b/torch/hub/baudm_parseq_main/strhub/models/abinet/model_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..9ccfa95e65dbd7176c8bcee693bb0bcb8ad13c69 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/abinet/model_alignment.py @@ -0,0 +1,28 @@ +import torch +import torch.nn as nn + +from .model import Model + + +class BaseAlignment(Model): + def __init__(self, dataset_max_length, null_label, num_classes, d_model=512, loss_weight=1.0): + super().__init__(dataset_max_length, null_label) + self.loss_weight = loss_weight + self.w_att = nn.Linear(2 * d_model, d_model) + self.cls = nn.Linear(d_model, num_classes) + + def forward(self, l_feature, v_feature): + """ + Args: + l_feature: (N, T, E) where T is length, N is batch size and d is dim of model + v_feature: (N, T, E) shape the same as l_feature + """ + f = torch.cat((l_feature, v_feature), dim=2) + f_att = torch.sigmoid(self.w_att(f)) + output = f_att * v_feature + (1 - f_att) * l_feature + + logits = self.cls(output) # (N, T, C) + pt_lengths = self._get_length(logits) + + return {'logits': logits, 'pt_lengths': pt_lengths, 'loss_weight': self.loss_weight, + 'name': 'alignment'} diff --git a/torch/hub/baudm_parseq_main/strhub/models/abinet/model_language.py b/torch/hub/baudm_parseq_main/strhub/models/abinet/model_language.py new file mode 100644 index 0000000000000000000000000000000000000000..aa8bb8f60b61ad96dca3c54f7db94e19ffd42b83 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/abinet/model_language.py @@ -0,0 +1,49 @@ +import torch.nn as nn + +from .model import Model +from .transformer import PositionalEncoding, TransformerDecoderLayer, TransformerDecoder + + +class BCNLanguage(Model): + def __init__(self, dataset_max_length, null_label, num_classes, d_model=512, nhead=8, d_inner=2048, dropout=0.1, + activation='relu', num_layers=4, detach=True, use_self_attn=False, loss_weight=1.0, + global_debug=False): + super().__init__(dataset_max_length, null_label) + self.detach = detach + self.loss_weight = loss_weight + self.proj = nn.Linear(num_classes, d_model, False) + self.token_encoder = PositionalEncoding(d_model, max_len=self.max_length) + self.pos_encoder = PositionalEncoding(d_model, dropout=0, max_len=self.max_length) + decoder_layer = TransformerDecoderLayer(d_model, nhead, d_inner, dropout, + activation, self_attn=use_self_attn, debug=global_debug) + self.model = TransformerDecoder(decoder_layer, num_layers) + self.cls = nn.Linear(d_model, num_classes) + + def forward(self, tokens, lengths): + """ + Args: + tokens: (N, T, C) where T is length, N is batch size and C is classes number + lengths: (N,) + """ + if self.detach: + tokens = tokens.detach() + embed = self.proj(tokens) # (N, T, E) + embed = embed.permute(1, 0, 2) # (T, N, E) + embed = self.token_encoder(embed) # (T, N, E) + padding_mask = self._get_padding_mask(lengths, self.max_length) + + zeros = embed.new_zeros(*embed.shape) + qeury = self.pos_encoder(zeros) + location_mask = self._get_location_mask(self.max_length, tokens.device) + output = self.model(qeury, embed, + tgt_key_padding_mask=padding_mask, + memory_mask=location_mask, + memory_key_padding_mask=padding_mask) # (T, N, E) + output = output.permute(1, 0, 2) # (N, T, E) + + logits = self.cls(output) # (N, T, C) + pt_lengths = self._get_length(logits) + + res = {'feature': output, 'logits': logits, 'pt_lengths': pt_lengths, + 'loss_weight': self.loss_weight, 'name': 'language'} + return res diff --git a/torch/hub/baudm_parseq_main/strhub/models/abinet/model_vision.py b/torch/hub/baudm_parseq_main/strhub/models/abinet/model_vision.py new file mode 100644 index 0000000000000000000000000000000000000000..bddb7d5f237854b81c388090e2e20fc26632c431 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/abinet/model_vision.py @@ -0,0 +1,45 @@ +from torch import nn + +from .attention import PositionAttention, Attention +from .backbone import ResTranformer +from .model import Model +from .resnet import resnet45 + + +class BaseVision(Model): + def __init__(self, dataset_max_length, null_label, num_classes, + attention='position', attention_mode='nearest', loss_weight=1.0, + d_model=512, nhead=8, d_inner=2048, dropout=0.1, activation='relu', + backbone='transformer', backbone_ln=2): + super().__init__(dataset_max_length, null_label) + self.loss_weight = loss_weight + self.out_channels = d_model + + if backbone == 'transformer': + self.backbone = ResTranformer(d_model, nhead, d_inner, dropout, activation, backbone_ln) + else: + self.backbone = resnet45() + + if attention == 'position': + self.attention = PositionAttention( + max_length=self.max_length, + mode=attention_mode + ) + elif attention == 'attention': + self.attention = Attention( + max_length=self.max_length, + n_feature=8 * 32, + ) + else: + raise ValueError(f'invalid attention: {attention}') + + self.cls = nn.Linear(self.out_channels, num_classes) + + def forward(self, images): + features = self.backbone(images) # (N, E, H, W) + attn_vecs, attn_scores = self.attention(features) # (N, T, E), (N, T, H, W) + logits = self.cls(attn_vecs) # (N, T, C) + pt_lengths = self._get_length(logits) + + return {'feature': attn_vecs, 'logits': logits, 'pt_lengths': pt_lengths, + 'attn_scores': attn_scores, 'loss_weight': self.loss_weight, 'name': 'vision'} diff --git a/torch/hub/baudm_parseq_main/strhub/models/abinet/resnet.py b/torch/hub/baudm_parseq_main/strhub/models/abinet/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..59bf38896987b3560e254e8037426d29bcdd5844 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/abinet/resnet.py @@ -0,0 +1,72 @@ +import math +from typing import Optional, Callable + +import torch.nn as nn +from torchvision.models import resnet + + +class BasicBlock(resnet.BasicBlock): + + def __init__(self, inplanes: int, planes: int, stride: int = 1, downsample: Optional[nn.Module] = None, + groups: int = 1, base_width: int = 64, dilation: int = 1, + norm_layer: Optional[Callable[..., nn.Module]] = None) -> None: + super().__init__(inplanes, planes, stride, downsample, groups, base_width, dilation, norm_layer) + self.conv1 = resnet.conv1x1(inplanes, planes) + self.conv2 = resnet.conv3x3(planes, planes, stride) + + +class ResNet(nn.Module): + + def __init__(self, block, layers): + super().__init__() + self.inplanes = 32 + self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1, + bias=False) + self.bn1 = nn.BatchNorm2d(32) + self.relu = nn.ReLU(inplace=True) + + self.layer1 = self._make_layer(block, 32, layers[0], stride=2) + self.layer2 = self._make_layer(block, 64, layers[1], stride=1) + self.layer3 = self._make_layer(block, 128, layers[2], stride=2) + self.layer4 = self._make_layer(block, 256, layers[3], stride=1) + self.layer5 = self._make_layer(block, 512, layers[4], stride=1) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + m.weight.data.normal_(0, math.sqrt(2. / n)) + elif isinstance(m, nn.BatchNorm2d): + m.weight.data.fill_(1) + m.bias.data.zero_() + + def _make_layer(self, block, planes, blocks, stride=1): + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + nn.Conv2d(self.inplanes, planes * block.expansion, + kernel_size=1, stride=stride, bias=False), + nn.BatchNorm2d(planes * block.expansion), + ) + + layers = [] + layers.append(block(self.inplanes, planes, stride, downsample)) + self.inplanes = planes * block.expansion + for i in range(1, blocks): + layers.append(block(self.inplanes, planes)) + + return nn.Sequential(*layers) + + def forward(self, x): + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + x = self.layer5(x) + return x + + +def resnet45(): + return ResNet(BasicBlock, [3, 4, 6, 6, 3]) diff --git a/torch/hub/baudm_parseq_main/strhub/models/abinet/system.py b/torch/hub/baudm_parseq_main/strhub/models/abinet/system.py new file mode 100644 index 0000000000000000000000000000000000000000..f56e9d1dff021318095d28fb5eb99cace5371ecb --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/abinet/system.py @@ -0,0 +1,215 @@ +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import math +from typing import Any, Optional + +import torch +import torch.nn.functional as F +from torch import Tensor, nn +from torch.optim import AdamW +from torch.optim.lr_scheduler import OneCycleLR + +from pytorch_lightning.utilities.types import STEP_OUTPUT +from timm.optim.optim_factory import param_groups_weight_decay + +from strhub.models.base import CrossEntropySystem +from strhub.models.utils import init_weights + +from .model_abinet_iter import ABINetIterModel as Model + +log = logging.getLogger(__name__) + + +class ABINet(CrossEntropySystem): + + def __init__( + self, + charset_train: str, + charset_test: str, + max_label_length: int, + batch_size: int, + lr: float, + warmup_pct: float, + weight_decay: float, + iter_size: int, + d_model: int, + nhead: int, + d_inner: int, + dropout: float, + activation: str, + v_loss_weight: float, + v_attention: str, + v_attention_mode: str, + v_backbone: str, + v_num_layers: int, + l_loss_weight: float, + l_num_layers: int, + l_detach: bool, + l_use_self_attn: bool, + l_lr: float, + a_loss_weight: float, + lm_only: bool = False, + **kwargs, + ) -> None: + super().__init__(charset_train, charset_test, batch_size, lr, warmup_pct, weight_decay) + self.scheduler = None + self.save_hyperparameters() + self.max_label_length = max_label_length + self.num_classes = len(self.tokenizer) - 2 # We don't predict nor + self.model = Model( + max_label_length, + self.eos_id, + self.num_classes, + iter_size, + d_model, + nhead, + d_inner, + dropout, + activation, + v_loss_weight, + v_attention, + v_attention_mode, + v_backbone, + v_num_layers, + l_loss_weight, + l_num_layers, + l_detach, + l_use_self_attn, + a_loss_weight, + ) + self.model.apply(init_weights) + # FIXME: doesn't support resumption from checkpoint yet + self._reset_alignment = True + self._reset_optimizers = True + self.l_lr = l_lr + self.lm_only = lm_only + # Train LM only. Freeze other submodels. + if lm_only: + self.l_lr = lr # for tuning + self.model.vision.requires_grad_(False) + self.model.alignment.requires_grad_(False) + + @property + def _pretraining(self): + # In the original work, VM was pretrained for 8 epochs while full model was trained for an additional 10 epochs. + total_steps = self.trainer.estimated_stepping_batches * self.trainer.accumulate_grad_batches + return self.global_step < (8 / (8 + 10)) * total_steps + + @torch.jit.ignore + def no_weight_decay(self): + return {'model.language.proj.weight'} + + def _add_weight_decay(self, model: nn.Module, skip_list=()): + if self.weight_decay: + return param_groups_weight_decay(model, self.weight_decay, skip_list) + else: + return [{'params': model.parameters()}] + + def configure_optimizers(self): + agb = self.trainer.accumulate_grad_batches + # Linear scaling so that the effective learning rate is constant regardless of the number of GPUs used with DDP. + lr_scale = agb * math.sqrt(self.trainer.num_devices) * self.batch_size / 256.0 + lr = lr_scale * self.lr + l_lr = lr_scale * self.l_lr + params = [] + params.extend(self._add_weight_decay(self.model.vision)) + params.extend(self._add_weight_decay(self.model.alignment)) + # We use a different learning rate for the LM. + for p in self._add_weight_decay(self.model.language, ('proj.weight',)): + p['lr'] = l_lr + params.append(p) + max_lr = [p.get('lr', lr) for p in params] + optim = AdamW(params, lr) + self.scheduler = OneCycleLR( + optim, max_lr, self.trainer.estimated_stepping_batches, pct_start=self.warmup_pct, cycle_momentum=False + ) + return {'optimizer': optim, 'lr_scheduler': {'scheduler': self.scheduler, 'interval': 'step'}} + + def forward(self, images: Tensor, max_length: Optional[int] = None) -> Tensor: + max_length = self.max_label_length if max_length is None else min(max_length, self.max_label_length) + logits = self.model.forward(images)[0]['logits'] + return logits[:, : max_length + 1] # truncate + + def calc_loss(self, targets, *res_lists) -> Tensor: + total_loss = 0 + for res_list in res_lists: + loss = 0 + if isinstance(res_list, dict): + res_list = [res_list] + for res in res_list: + logits = res['logits'].flatten(end_dim=1) + loss += F.cross_entropy(logits, targets.flatten(), ignore_index=self.pad_id) + loss /= len(res_list) + self.log('loss_' + res_list[0]['name'], loss) + total_loss += res_list[0]['loss_weight'] * loss + return total_loss + + def on_train_batch_start(self, batch: Any, batch_idx: int) -> None: + if not self._pretraining and self._reset_optimizers: + log.info('Pretraining ends. Updating base LRs.') + self._reset_optimizers = False + # Make base_lr the same for all groups + base_lr = self.scheduler.base_lrs[0] # base_lr of group 0 - VM + self.scheduler.base_lrs = [base_lr] * len(self.scheduler.base_lrs) + + def _prepare_inputs_and_targets(self, labels): + # Use dummy label to ensure sequence length is constant. + dummy = ['0' * self.max_label_length] + targets = self.tokenizer.encode(dummy + list(labels), self.device)[1:] + targets = targets[:, 1:] # remove . Unused here. + # Inputs are padded with eos_id + inputs = torch.where(targets == self.pad_id, self.eos_id, targets) + inputs = F.one_hot(inputs, self.num_classes).float() + lengths = torch.as_tensor(list(map(len, labels)), device=self.device) + 1 # +1 for eos + return inputs, lengths, targets + + def training_step(self, batch, batch_idx) -> STEP_OUTPUT: + images, labels = batch + inputs, lengths, targets = self._prepare_inputs_and_targets(labels) + if self.lm_only: + l_res = self.model.language(inputs, lengths) + loss = self.calc_loss(targets, l_res) + # Pretrain submodels independently first + elif self._pretraining: + # Vision + v_res = self.model.vision(images) + # Language + l_res = self.model.language(inputs, lengths) + # We also train the alignment model to 'satisfy' DDP requirements (all parameters should be used). + # We'll reset its parameters prior to joint training. + a_res = self.model.alignment(l_res['feature'].detach(), v_res['feature'].detach()) + loss = self.calc_loss(targets, v_res, l_res, a_res) + else: + # Reset alignment model's parameters once prior to full model training. + if self._reset_alignment: + log.info('Pretraining ends. Resetting alignment model.') + self._reset_alignment = False + self.model.alignment.apply(init_weights) + all_a_res, all_l_res, v_res = self.model.forward(images) + loss = self.calc_loss(targets, v_res, all_l_res, all_a_res) + self.log('loss', loss) + return loss + + def forward_logits_loss(self, images: Tensor, labels: list[str]) -> tuple[Tensor, Tensor, int]: + if self.lm_only: + inputs, lengths, targets = self._prepare_inputs_and_targets(labels) + l_res = self.model.language(inputs, lengths) + loss = self.calc_loss(targets, l_res) + loss_numel = (targets != self.pad_id).sum() + return l_res['logits'], loss, loss_numel + else: + return super().forward_logits_loss(images, labels) diff --git a/torch/hub/baudm_parseq_main/strhub/models/abinet/transformer.py b/torch/hub/baudm_parseq_main/strhub/models/abinet/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..03ae4b13976ddc67dfb2e2bfd83885a823cf9ecb --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/abinet/transformer.py @@ -0,0 +1,198 @@ +import math + +import torch +import torch.nn.functional as F +from torch import nn +from torch.nn.modules.transformer import _get_activation_fn, _get_clones + + +class TransformerDecoder(nn.Module): + r"""TransformerDecoder is a stack of N decoder layers + + Args: + decoder_layer: an instance of the TransformerDecoderLayer() class (required). + num_layers: the number of sub-decoder-layers in the decoder (required). + norm: the layer normalization component (optional). + + Examples:: + >>> decoder_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8) + >>> transformer_decoder = nn.TransformerDecoder(decoder_layer, num_layers=6) + >>> memory = torch.rand(10, 32, 512) + >>> tgt = torch.rand(20, 32, 512) + >>> out = transformer_decoder(tgt, memory) + """ + __constants__ = ['norm'] + + def __init__(self, decoder_layer, num_layers, norm=None): + super(TransformerDecoder, self).__init__() + self.layers = _get_clones(decoder_layer, num_layers) + self.num_layers = num_layers + self.norm = norm + + def forward(self, tgt, memory, memory2=None, tgt_mask=None, + memory_mask=None, memory_mask2=None, tgt_key_padding_mask=None, + memory_key_padding_mask=None, memory_key_padding_mask2=None): + # type: (Tensor, Tensor, Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor]) -> Tensor + r"""Pass the inputs (and mask) through the decoder layer in turn. + + Args: + tgt: the sequence to the decoder (required). + memory: the sequence from the last layer of the encoder (required). + tgt_mask: the mask for the tgt sequence (optional). + memory_mask: the mask for the memory sequence (optional). + tgt_key_padding_mask: the mask for the tgt keys per batch (optional). + memory_key_padding_mask: the mask for the memory keys per batch (optional). + + Shape: + see the docs in Transformer class. + """ + output = tgt + + for mod in self.layers: + output = mod(output, memory, memory2=memory2, tgt_mask=tgt_mask, + memory_mask=memory_mask, memory_mask2=memory_mask2, + tgt_key_padding_mask=tgt_key_padding_mask, + memory_key_padding_mask=memory_key_padding_mask, + memory_key_padding_mask2=memory_key_padding_mask2) + + if self.norm is not None: + output = self.norm(output) + + return output + + +class TransformerDecoderLayer(nn.Module): + r"""TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. + This standard decoder layer is based on the paper "Attention Is All You Need". + Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, + Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in + Neural Information Processing Systems, pages 6000-6010. Users may modify or implement + in a different way during application. + + Args: + d_model: the number of expected features in the input (required). + nhead: the number of heads in the multiheadattention models (required). + dim_feedforward: the dimension of the feedforward network model (default=2048). + dropout: the dropout value (default=0.1). + activation: the activation function of intermediate layer, relu or gelu (default=relu). + + Examples:: + >>> decoder_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8) + >>> memory = torch.rand(10, 32, 512) + >>> tgt = torch.rand(20, 32, 512) + >>> out = decoder_layer(tgt, memory) + """ + + def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, + activation="relu", self_attn=True, siamese=False, debug=False): + super().__init__() + self.has_self_attn, self.siamese = self_attn, siamese + self.debug = debug + if self.has_self_attn: + self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) + self.norm1 = nn.LayerNorm(d_model) + self.dropout1 = nn.Dropout(dropout) + self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) + # Implementation of Feedforward model + self.linear1 = nn.Linear(d_model, dim_feedforward) + self.dropout = nn.Dropout(dropout) + self.linear2 = nn.Linear(dim_feedforward, d_model) + + self.norm2 = nn.LayerNorm(d_model) + self.norm3 = nn.LayerNorm(d_model) + self.dropout2 = nn.Dropout(dropout) + self.dropout3 = nn.Dropout(dropout) + if self.siamese: + self.multihead_attn2 = nn.MultiheadAttention(d_model, nhead, dropout=dropout) + + self.activation = _get_activation_fn(activation) + + def __setstate__(self, state): + if 'activation' not in state: + state['activation'] = F.relu + super().__setstate__(state) + + def forward(self, tgt, memory, tgt_mask=None, memory_mask=None, + tgt_key_padding_mask=None, memory_key_padding_mask=None, + memory2=None, memory_mask2=None, memory_key_padding_mask2=None): + # type: (Tensor, Tensor, Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor]) -> Tensor + r"""Pass the inputs (and mask) through the decoder layer. + + Args: + tgt: the sequence to the decoder layer (required). + memory: the sequence from the last layer of the encoder (required). + tgt_mask: the mask for the tgt sequence (optional). + memory_mask: the mask for the memory sequence (optional). + tgt_key_padding_mask: the mask for the tgt keys per batch (optional). + memory_key_padding_mask: the mask for the memory keys per batch (optional). + + Shape: + see the docs in Transformer class. + """ + if self.has_self_attn: + tgt2, attn = self.self_attn(tgt, tgt, tgt, attn_mask=tgt_mask, + key_padding_mask=tgt_key_padding_mask) + tgt = tgt + self.dropout1(tgt2) + tgt = self.norm1(tgt) + if self.debug: self.attn = attn + tgt2, attn2 = self.multihead_attn(tgt, memory, memory, attn_mask=memory_mask, + key_padding_mask=memory_key_padding_mask) + if self.debug: self.attn2 = attn2 + + if self.siamese: + tgt3, attn3 = self.multihead_attn2(tgt, memory2, memory2, attn_mask=memory_mask2, + key_padding_mask=memory_key_padding_mask2) + tgt = tgt + self.dropout2(tgt3) + if self.debug: self.attn3 = attn3 + + tgt = tgt + self.dropout2(tgt2) + tgt = self.norm2(tgt) + tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) + tgt = tgt + self.dropout3(tgt2) + tgt = self.norm3(tgt) + + return tgt + + +class PositionalEncoding(nn.Module): + r"""Inject some information about the relative or absolute position of the tokens + in the sequence. The positional encodings have the same dimension as + the embeddings, so that the two can be summed. Here, we use sine and cosine + functions of different frequencies. + .. math:: + \text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model)) + \text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model)) + \text{where pos is the word position and i is the embed idx) + Args: + d_model: the embed dim (required). + dropout: the dropout value (default=0.1). + max_len: the max. length of the incoming sequence (default=5000). + Examples: + >>> pos_encoder = PositionalEncoding(d_model) + """ + + def __init__(self, d_model, dropout=0.1, max_len=5000): + super().__init__() + self.dropout = nn.Dropout(p=dropout) + + pe = torch.zeros(max_len, d_model) + position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) + div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) + pe[:, 0::2] = torch.sin(position * div_term) + pe[:, 1::2] = torch.cos(position * div_term) + pe = pe.unsqueeze(0).transpose(0, 1) + self.register_buffer('pe', pe) + + def forward(self, x): + r"""Inputs of forward function + Args: + x: the sequence fed to the positional encoder model (required). + Shape: + x: [sequence length, batch size, embed dim] + output: [sequence length, batch size, embed dim] + Examples: + >>> output = pos_encoder(x) + """ + + x = x + self.pe[:x.size(0), :] + return self.dropout(x) diff --git a/torch/hub/baudm_parseq_main/strhub/models/base.py b/torch/hub/baudm_parseq_main/strhub/models/base.py new file mode 100644 index 0000000000000000000000000000000000000000..353cf1a22fd6430b715dea8e6ebd6ab86e67f2f6 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/base.py @@ -0,0 +1,221 @@ +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from abc import ABC, abstractmethod +from dataclasses import dataclass +from typing import Optional + +from nltk import edit_distance + +import torch +import torch.nn.functional as F +from torch import Tensor +from torch.optim import Optimizer +from torch.optim.lr_scheduler import OneCycleLR + +import pytorch_lightning as pl +from pytorch_lightning.utilities.types import STEP_OUTPUT +from timm.optim import create_optimizer_v2 + +from strhub.data.utils import BaseTokenizer, CharsetAdapter, CTCTokenizer, Tokenizer + + +@dataclass +class BatchResult: + num_samples: int + correct: int + ned: float + confidence: float + label_length: int + loss: Tensor + loss_numel: int + + +EPOCH_OUTPUT = list[dict[str, BatchResult]] + + +class BaseSystem(pl.LightningModule, ABC): + + def __init__( + self, + tokenizer: BaseTokenizer, + charset_test: str, + batch_size: int, + lr: float, + warmup_pct: float, + weight_decay: float, + ) -> None: + super().__init__() + self.tokenizer = tokenizer + self.charset_adapter = CharsetAdapter(charset_test) + self.batch_size = batch_size + self.lr = lr + self.warmup_pct = warmup_pct + self.weight_decay = weight_decay + self.outputs: EPOCH_OUTPUT = [] + + @abstractmethod + def forward(self, images: Tensor, max_length: Optional[int] = None) -> Tensor: + """Inference + + Args: + images: Batch of images. Shape: N, Ch, H, W + max_length: Max sequence length of the output. If None, will use default. + + Returns: + logits: N, L, C (L = sequence length, C = number of classes, typically len(charset_train) + num specials) + """ + raise NotImplementedError + + @abstractmethod + def forward_logits_loss(self, images: Tensor, labels: list[str]) -> tuple[Tensor, Tensor, int]: + """Like forward(), but also computes the loss (calls forward() internally). + + Args: + images: Batch of images. Shape: N, Ch, H, W + labels: Text labels of the images + + Returns: + logits: N, L, C (L = sequence length, C = number of classes, typically len(charset_train) + num specials) + loss: mean loss for the batch + loss_numel: number of elements the loss was calculated from + """ + raise NotImplementedError + + def configure_optimizers(self): + agb = self.trainer.accumulate_grad_batches + # Linear scaling so that the effective learning rate is constant regardless of the number of GPUs used with DDP. + lr_scale = agb * math.sqrt(self.trainer.num_devices) * self.batch_size / 256.0 + lr = lr_scale * self.lr + optim = create_optimizer_v2(self, 'adamw', lr, self.weight_decay) + sched = OneCycleLR( + optim, lr, self.trainer.estimated_stepping_batches, pct_start=self.warmup_pct, cycle_momentum=False + ) + return {'optimizer': optim, 'lr_scheduler': {'scheduler': sched, 'interval': 'step'}} + + def optimizer_zero_grad(self, epoch: int, batch_idx: int, optimizer: Optimizer) -> None: + optimizer.zero_grad(set_to_none=True) + + def _eval_step(self, batch, validation: bool) -> Optional[STEP_OUTPUT]: + images, labels = batch + + correct = 0 + total = 0 + ned = 0 + confidence = 0 + label_length = 0 + if validation: + logits, loss, loss_numel = self.forward_logits_loss(images, labels) + else: + # At test-time, we shouldn't specify a max_label_length because the test-time charset used + # might be different from the train-time charset. max_label_length in eval_logits_loss() is computed + # based on the transformed label, which could be wrong if the actual gt label contains characters existing + # in the train-time charset but not in the test-time charset. For example, "aishahaleyes.blogspot.com" + # is exactly 25 characters, but if processed by CharsetAdapter for the 36-char set, it becomes 23 characters + # long only, which sets max_label_length = 23. This will cause the model prediction to be truncated. + logits = self.forward(images) + loss = loss_numel = None # Only used for validation; not needed at test-time. + + probs = logits.softmax(-1) + preds, probs = self.tokenizer.decode(probs) + for pred, prob, gt in zip(preds, probs, labels): + confidence += prob.prod().item() + pred = self.charset_adapter(pred) + # Follow ICDAR 2019 definition of N.E.D. + ned += edit_distance(pred, gt) / max(len(pred), len(gt)) + if pred == gt: + correct += 1 + total += 1 + label_length += len(pred) + return dict(output=BatchResult(total, correct, ned, confidence, label_length, loss, loss_numel)) + + @staticmethod + def _aggregate_results(outputs: EPOCH_OUTPUT) -> tuple[float, float, float]: + if not outputs: + return 0.0, 0.0, 0.0 + total_loss = 0 + total_loss_numel = 0 + total_n_correct = 0 + total_norm_ED = 0 + total_size = 0 + for result in outputs: + result = result['output'] + total_loss += result.loss_numel * result.loss + total_loss_numel += result.loss_numel + total_n_correct += result.correct + total_norm_ED += result.ned + total_size += result.num_samples + acc = total_n_correct / total_size + ned = 1 - total_norm_ED / total_size + loss = total_loss / total_loss_numel + return acc, ned, loss + + def validation_step(self, batch, batch_idx) -> Optional[STEP_OUTPUT]: + result = self._eval_step(batch, True) + self.outputs.append(result) + return result + + def on_validation_epoch_end(self) -> None: + acc, ned, loss = self._aggregate_results(self.outputs) + self.outputs.clear() + self.log('val_accuracy', 100 * acc, sync_dist=True) + self.log('val_NED', 100 * ned, sync_dist=True) + self.log('val_loss', loss, sync_dist=True) + self.log('hp_metric', acc, sync_dist=True) + + def test_step(self, batch, batch_idx) -> Optional[STEP_OUTPUT]: + return self._eval_step(batch, False) + + +class CrossEntropySystem(BaseSystem): + + def __init__( + self, charset_train: str, charset_test: str, batch_size: int, lr: float, warmup_pct: float, weight_decay: float + ) -> None: + tokenizer = Tokenizer(charset_train) + super().__init__(tokenizer, charset_test, batch_size, lr, warmup_pct, weight_decay) + self.bos_id = tokenizer.bos_id + self.eos_id = tokenizer.eos_id + self.pad_id = tokenizer.pad_id + + def forward_logits_loss(self, images: Tensor, labels: list[str]) -> tuple[Tensor, Tensor, int]: + targets = self.tokenizer.encode(labels, self.device) + targets = targets[:, 1:] # Discard + max_len = targets.shape[1] - 1 # exclude from count + logits = self.forward(images, max_len) + loss = F.cross_entropy(logits.flatten(end_dim=1), targets.flatten(), ignore_index=self.pad_id) + loss_numel = (targets != self.pad_id).sum() + return logits, loss, loss_numel + + +class CTCSystem(BaseSystem): + + def __init__( + self, charset_train: str, charset_test: str, batch_size: int, lr: float, warmup_pct: float, weight_decay: float + ) -> None: + tokenizer = CTCTokenizer(charset_train) + super().__init__(tokenizer, charset_test, batch_size, lr, warmup_pct, weight_decay) + self.blank_id = tokenizer.blank_id + + def forward_logits_loss(self, images: Tensor, labels: list[str]) -> tuple[Tensor, Tensor, int]: + targets = self.tokenizer.encode(labels, self.device) + logits = self.forward(images) + log_probs = logits.log_softmax(-1).transpose(0, 1) # swap batch and seq. dims + T, N, _ = log_probs.shape + input_lengths = torch.full(size=(N,), fill_value=T, dtype=torch.long, device=self.device) + target_lengths = torch.as_tensor(list(map(len, labels)), dtype=torch.long, device=self.device) + loss = F.ctc_loss(log_probs, targets, input_lengths, target_lengths, blank=self.blank_id, zero_infinity=True) + return logits, loss, N diff --git a/torch/hub/baudm_parseq_main/strhub/models/crnn/LICENSE b/torch/hub/baudm_parseq_main/strhub/models/crnn/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f98687be392fdce266708e79885aadaa4991b67f --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/crnn/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Jieru Mei + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/torch/hub/baudm_parseq_main/strhub/models/crnn/__init__.py b/torch/hub/baudm_parseq_main/strhub/models/crnn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a4535947d9233c8fb0a85e9c22b151697d37f410 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/crnn/__init__.py @@ -0,0 +1,13 @@ +r""" +Shi, Baoguang, Xiang Bai, and Cong Yao. +"An end-to-end trainable neural network for image-based sequence recognition and its application to scene text recognition." +IEEE transactions on pattern analysis and machine intelligence 39, no. 11 (2016): 2298-2304. + +https://arxiv.org/abs/1507.05717 + +All source files, except `system.py`, are based on the implementation listed below, +and hence are released under the license of the original. + +Source: https://github.com/meijieru/crnn.pytorch +License: MIT License (see included LICENSE file) +""" diff --git a/torch/hub/baudm_parseq_main/strhub/models/crnn/model.py b/torch/hub/baudm_parseq_main/strhub/models/crnn/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4d5c9e8e6a1a2f3d4ed32c976f47a8cbdff22946 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/crnn/model.py @@ -0,0 +1,62 @@ +import torch.nn as nn + +from strhub.models.modules import BidirectionalLSTM + + +class CRNN(nn.Module): + + def __init__(self, img_h, nc, nclass, nh, leaky_relu=False): + super().__init__() + assert img_h % 16 == 0, 'img_h has to be a multiple of 16' + + ks = [3, 3, 3, 3, 3, 3, 2] + ps = [1, 1, 1, 1, 1, 1, 0] + ss = [1, 1, 1, 1, 1, 1, 1] + nm = [64, 128, 256, 256, 512, 512, 512] + + cnn = nn.Sequential() + + def convRelu(i, batchNormalization=False): + nIn = nc if i == 0 else nm[i - 1] + nOut = nm[i] + cnn.add_module(f'conv{i}', + nn.Conv2d(nIn, nOut, ks[i], ss[i], ps[i], bias=not batchNormalization)) + if batchNormalization: + cnn.add_module(f'batchnorm{i}', nn.BatchNorm2d(nOut)) + if leaky_relu: + cnn.add_module(f'relu{i}', + nn.LeakyReLU(0.2, inplace=True)) + else: + cnn.add_module(f'relu{i}', nn.ReLU(True)) + + convRelu(0) + cnn.add_module('pooling0', nn.MaxPool2d(2, 2)) # 64x16x64 + convRelu(1) + cnn.add_module('pooling1', nn.MaxPool2d(2, 2)) # 128x8x32 + convRelu(2, True) + convRelu(3) + cnn.add_module('pooling2', + nn.MaxPool2d((2, 2), (2, 1), (0, 1))) # 256x4x16 + convRelu(4, True) + convRelu(5) + cnn.add_module('pooling3', + nn.MaxPool2d((2, 2), (2, 1), (0, 1))) # 512x2x16 + convRelu(6, True) # 512x1x16 + + self.cnn = cnn + self.rnn = nn.Sequential( + BidirectionalLSTM(512, nh, nh), + BidirectionalLSTM(nh, nh, nclass)) + + def forward(self, input): + # conv features + conv = self.cnn(input) + b, c, h, w = conv.size() + assert h == 1, 'the height of conv must be 1' + conv = conv.squeeze(2) + conv = conv.transpose(1, 2) # [b, w, c] + + # rnn features + output = self.rnn(conv) + + return output diff --git a/torch/hub/baudm_parseq_main/strhub/models/crnn/system.py b/torch/hub/baudm_parseq_main/strhub/models/crnn/system.py new file mode 100644 index 0000000000000000000000000000000000000000..a69dfdd131cc3895bfc7b0aaa0832681dbfaab25 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/crnn/system.py @@ -0,0 +1,56 @@ +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Optional, Sequence + +from torch import Tensor + +from pytorch_lightning.utilities.types import STEP_OUTPUT + +from strhub.models.base import CTCSystem +from strhub.models.utils import init_weights + +from .model import CRNN as Model + + +class CRNN(CTCSystem): + + def __init__( + self, + charset_train: str, + charset_test: str, + max_label_length: int, + batch_size: int, + lr: float, + warmup_pct: float, + weight_decay: float, + img_size: Sequence[int], + hidden_size: int, + leaky_relu: bool, + **kwargs, + ) -> None: + super().__init__(charset_train, charset_test, batch_size, lr, warmup_pct, weight_decay) + self.save_hyperparameters() + self.model = Model(img_size[0], 3, len(self.tokenizer), hidden_size, leaky_relu) + self.model.apply(init_weights) + + def forward(self, images: Tensor, max_length: Optional[int] = None) -> Tensor: + return self.model.forward(images) + + def training_step(self, batch, batch_idx) -> STEP_OUTPUT: + images, labels = batch + loss = self.forward_logits_loss(images, labels)[1] + self.log('loss', loss) + return loss diff --git a/torch/hub/baudm_parseq_main/strhub/models/modules.py b/torch/hub/baudm_parseq_main/strhub/models/modules.py new file mode 100644 index 0000000000000000000000000000000000000000..a89d05f6afd67437f3cfa8aff6d2d8b12df3fafa --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/modules.py @@ -0,0 +1,20 @@ +r"""Shared modules used by CRNN and TRBA""" +from torch import nn + + +class BidirectionalLSTM(nn.Module): + """Ref: https://github.com/clovaai/deep-text-recognition-benchmark/blob/master/modules/sequence_modeling.py""" + + def __init__(self, input_size, hidden_size, output_size): + super().__init__() + self.rnn = nn.LSTM(input_size, hidden_size, bidirectional=True, batch_first=True) + self.linear = nn.Linear(hidden_size * 2, output_size) + + def forward(self, input): + """ + input : visual feature [batch_size x T x input_size], T = num_steps. + output : contextual feature [batch_size x T x output_size] + """ + recurrent, _ = self.rnn(input) # batch_size x T x input_size -> batch_size x T x (2*hidden_size) + output = self.linear(recurrent) # batch_size x T x output_size + return output diff --git a/torch/hub/baudm_parseq_main/strhub/models/parseq/__init__.py b/torch/hub/baudm_parseq_main/strhub/models/parseq/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/torch/hub/baudm_parseq_main/strhub/models/parseq/model.py b/torch/hub/baudm_parseq_main/strhub/models/parseq/model.py new file mode 100644 index 0000000000000000000000000000000000000000..8a0e1cae2d43c507c5743d06a6b446e7844e41a1 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/parseq/model.py @@ -0,0 +1,169 @@ +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from functools import partial +from typing import Optional, Sequence + +import torch +import torch.nn as nn +from torch import Tensor + +from timm.models.helpers import named_apply + +from strhub.data.utils import Tokenizer +from strhub.models.utils import init_weights + +from .modules import Decoder, DecoderLayer, Encoder, TokenEmbedding + + +class PARSeq(nn.Module): + + def __init__( + self, + num_tokens: int, + max_label_length: int, + img_size: Sequence[int], + patch_size: Sequence[int], + embed_dim: int, + enc_num_heads: int, + enc_mlp_ratio: int, + enc_depth: int, + dec_num_heads: int, + dec_mlp_ratio: int, + dec_depth: int, + decode_ar: bool, + refine_iters: int, + dropout: float, + ) -> None: + super().__init__() + + self.max_label_length = max_label_length + self.decode_ar = decode_ar + self.refine_iters = refine_iters + + self.encoder = Encoder( + img_size, patch_size, embed_dim=embed_dim, depth=enc_depth, num_heads=enc_num_heads, mlp_ratio=enc_mlp_ratio + ) + decoder_layer = DecoderLayer(embed_dim, dec_num_heads, embed_dim * dec_mlp_ratio, dropout) + self.decoder = Decoder(decoder_layer, num_layers=dec_depth, norm=nn.LayerNorm(embed_dim)) + + # We don't predict nor + self.head = nn.Linear(embed_dim, num_tokens - 2) + self.text_embed = TokenEmbedding(num_tokens, embed_dim) + + # +1 for + self.pos_queries = nn.Parameter(torch.Tensor(1, max_label_length + 1, embed_dim)) + self.dropout = nn.Dropout(p=dropout) + # Encoder has its own init. + named_apply(partial(init_weights, exclude=['encoder']), self) + nn.init.trunc_normal_(self.pos_queries, std=0.02) + + @property + def _device(self) -> torch.device: + return next(self.head.parameters(recurse=False)).device + + @torch.jit.ignore + def no_weight_decay(self): + param_names = {'text_embed.embedding.weight', 'pos_queries'} + enc_param_names = {'encoder.' + n for n in self.encoder.no_weight_decay()} + return param_names.union(enc_param_names) + + def encode(self, img: torch.Tensor): + return self.encoder(img) + + def decode( + self, + tgt: torch.Tensor, + memory: torch.Tensor, + tgt_mask: Optional[Tensor] = None, + tgt_padding_mask: Optional[Tensor] = None, + tgt_query: Optional[Tensor] = None, + tgt_query_mask: Optional[Tensor] = None, + ): + N, L = tgt.shape + # stands for the null context. We only supply position information for characters after . + null_ctx = self.text_embed(tgt[:, :1]) + tgt_emb = self.pos_queries[:, : L - 1] + self.text_embed(tgt[:, 1:]) + tgt_emb = self.dropout(torch.cat([null_ctx, tgt_emb], dim=1)) + if tgt_query is None: + tgt_query = self.pos_queries[:, :L].expand(N, -1, -1) + tgt_query = self.dropout(tgt_query) + return self.decoder(tgt_query, tgt_emb, memory, tgt_query_mask, tgt_mask, tgt_padding_mask) + + def forward(self, tokenizer: Tokenizer, images: Tensor, max_length: Optional[int] = None) -> Tensor: + testing = max_length is None + max_length = self.max_label_length if max_length is None else min(max_length, self.max_label_length) + bs = images.shape[0] + # +1 for at end of sequence. + num_steps = max_length + 1 + memory = self.encode(images) + + # Query positions up to `num_steps` + pos_queries = self.pos_queries[:, :num_steps].expand(bs, -1, -1) + + # Special case for the forward permutation. Faster than using `generate_attn_masks()` + tgt_mask = query_mask = torch.triu(torch.ones((num_steps, num_steps), dtype=torch.bool, device=self._device), 1) + + if self.decode_ar: + tgt_in = torch.full((bs, num_steps), tokenizer.pad_id, dtype=torch.long, device=self._device) + tgt_in[:, 0] = tokenizer.bos_id + + logits = [] + for i in range(num_steps): + j = i + 1 # next token index + # Efficient decoding: + # Input the context up to the ith token. We use only one query (at position = i) at a time. + # This works because of the lookahead masking effect of the canonical (forward) AR context. + # Past tokens have no access to future tokens, hence are fixed once computed. + tgt_out = self.decode( + tgt_in[:, :j], + memory, + tgt_mask[:j, :j], + tgt_query=pos_queries[:, i:j], + tgt_query_mask=query_mask[i:j, :j], + ) + # the next token probability is in the output's ith token position + p_i = self.head(tgt_out) + logits.append(p_i) + if j < num_steps: + # greedy decode. add the next token index to the target input + tgt_in[:, j] = p_i.squeeze().argmax(-1) + # Efficient batch decoding: If all output words have at least one EOS token, end decoding. + if testing and (tgt_in == tokenizer.eos_id).any(dim=-1).all(): + break + + logits = torch.cat(logits, dim=1) + else: + # No prior context, so input is just . We query all positions. + tgt_in = torch.full((bs, 1), tokenizer.bos_id, dtype=torch.long, device=self._device) + tgt_out = self.decode(tgt_in, memory, tgt_query=pos_queries) + logits = self.head(tgt_out) + + if self.refine_iters: + # For iterative refinement, we always use a 'cloze' mask. + # We can derive it from the AR forward mask by unmasking the token context to the right. + query_mask[torch.triu(torch.ones(num_steps, num_steps, dtype=torch.bool, device=self._device), 2)] = 0 + bos = torch.full((bs, 1), tokenizer.bos_id, dtype=torch.long, device=self._device) + for i in range(self.refine_iters): + # Prior context is the previous output. + tgt_in = torch.cat([bos, logits[:, :-1].argmax(-1)], dim=1) + # Mask tokens beyond the first EOS token. + tgt_padding_mask = (tgt_in == tokenizer.eos_id).int().cumsum(-1) > 0 + tgt_out = self.decode( + tgt_in, memory, tgt_mask, tgt_padding_mask, pos_queries, query_mask[:, : tgt_in.shape[1]] + ) + logits = self.head(tgt_out) + + return logits diff --git a/torch/hub/baudm_parseq_main/strhub/models/parseq/modules.py b/torch/hub/baudm_parseq_main/strhub/models/parseq/modules.py new file mode 100644 index 0000000000000000000000000000000000000000..e3e3f23f6ee52c9de8b21df63efe7299100eb44d --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/parseq/modules.py @@ -0,0 +1,176 @@ +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from typing import Optional + +import torch +from torch import Tensor, nn as nn +from torch.nn import functional as F +from torch.nn.modules import transformer + +from timm.models.vision_transformer import PatchEmbed, VisionTransformer + + +class DecoderLayer(nn.Module): + """A Transformer decoder layer supporting two-stream attention (XLNet) + This implements a pre-LN decoder, as opposed to the post-LN default in PyTorch.""" + + def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='gelu', layer_norm_eps=1e-5): + super().__init__() + self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout, batch_first=True) + self.cross_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout, batch_first=True) + # Implementation of Feedforward model + self.linear1 = nn.Linear(d_model, dim_feedforward) + self.dropout = nn.Dropout(dropout) + self.linear2 = nn.Linear(dim_feedforward, d_model) + + self.norm1 = nn.LayerNorm(d_model, eps=layer_norm_eps) + self.norm2 = nn.LayerNorm(d_model, eps=layer_norm_eps) + self.norm_q = nn.LayerNorm(d_model, eps=layer_norm_eps) + self.norm_c = nn.LayerNorm(d_model, eps=layer_norm_eps) + self.dropout1 = nn.Dropout(dropout) + self.dropout2 = nn.Dropout(dropout) + self.dropout3 = nn.Dropout(dropout) + + self.activation = transformer._get_activation_fn(activation) + + def __setstate__(self, state): + if 'activation' not in state: + state['activation'] = F.gelu + super().__setstate__(state) + + def forward_stream( + self, + tgt: Tensor, + tgt_norm: Tensor, + tgt_kv: Tensor, + memory: Tensor, + tgt_mask: Optional[Tensor], + tgt_key_padding_mask: Optional[Tensor], + ): + """Forward pass for a single stream (i.e. content or query) + tgt_norm is just a LayerNorm'd tgt. Added as a separate parameter for efficiency. + Both tgt_kv and memory are expected to be LayerNorm'd too. + memory is LayerNorm'd by ViT. + """ + tgt2, sa_weights = self.self_attn( + tgt_norm, tgt_kv, tgt_kv, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask + ) + tgt = tgt + self.dropout1(tgt2) + + tgt2, ca_weights = self.cross_attn(self.norm1(tgt), memory, memory) + tgt = tgt + self.dropout2(tgt2) + + tgt2 = self.linear2(self.dropout(self.activation(self.linear1(self.norm2(tgt))))) + tgt = tgt + self.dropout3(tgt2) + return tgt, sa_weights, ca_weights + + def forward( + self, + query, + content, + memory, + query_mask: Optional[Tensor] = None, + content_mask: Optional[Tensor] = None, + content_key_padding_mask: Optional[Tensor] = None, + update_content: bool = True, + ): + query_norm = self.norm_q(query) + content_norm = self.norm_c(content) + query = self.forward_stream(query, query_norm, content_norm, memory, query_mask, content_key_padding_mask)[0] + if update_content: + content = self.forward_stream( + content, content_norm, content_norm, memory, content_mask, content_key_padding_mask + )[0] + return query, content + + +class Decoder(nn.Module): + __constants__ = ['norm'] + + def __init__(self, decoder_layer, num_layers, norm): + super().__init__() + self.layers = transformer._get_clones(decoder_layer, num_layers) + self.num_layers = num_layers + self.norm = norm + + def forward( + self, + query, + content, + memory, + query_mask: Optional[Tensor] = None, + content_mask: Optional[Tensor] = None, + content_key_padding_mask: Optional[Tensor] = None, + ): + for i, mod in enumerate(self.layers): + last = i == len(self.layers) - 1 + query, content = mod( + query, content, memory, query_mask, content_mask, content_key_padding_mask, update_content=not last + ) + query = self.norm(query) + return query + + +class Encoder(VisionTransformer): + + def __init__( + self, + img_size=224, + patch_size=16, + in_chans=3, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=True, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + embed_layer=PatchEmbed, + ): + super().__init__( + img_size, + patch_size, + in_chans, + embed_dim=embed_dim, + depth=depth, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + drop_rate=drop_rate, + attn_drop_rate=attn_drop_rate, + drop_path_rate=drop_path_rate, + embed_layer=embed_layer, + num_classes=0, # These + global_pool='', # disable the + class_token=False, # classifier head. + ) + + def forward(self, x): + # Return all tokens + return self.forward_features(x) + + +class TokenEmbedding(nn.Module): + + def __init__(self, charset_size: int, embed_dim: int): + super().__init__() + self.embedding = nn.Embedding(charset_size, embed_dim) + self.embed_dim = embed_dim + + def forward(self, tokens: torch.Tensor): + return math.sqrt(self.embed_dim) * self.embedding(tokens) diff --git a/torch/hub/baudm_parseq_main/strhub/models/parseq/system.py b/torch/hub/baudm_parseq_main/strhub/models/parseq/system.py new file mode 100644 index 0000000000000000000000000000000000000000..be8581e2b92ebcc9a6a1eb4cb776e4fe9a1d3821 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/parseq/system.py @@ -0,0 +1,200 @@ +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from itertools import permutations +from typing import Any, Optional, Sequence + +import numpy as np + +import torch +import torch.nn.functional as F +from torch import Tensor + +from pytorch_lightning.utilities.types import STEP_OUTPUT + +from strhub.models.base import CrossEntropySystem + +from .model import PARSeq as Model + + +class PARSeq(CrossEntropySystem): + + def __init__( + self, + charset_train: str, + charset_test: str, + max_label_length: int, + batch_size: int, + lr: float, + warmup_pct: float, + weight_decay: float, + img_size: Sequence[int], + patch_size: Sequence[int], + embed_dim: int, + enc_num_heads: int, + enc_mlp_ratio: int, + enc_depth: int, + dec_num_heads: int, + dec_mlp_ratio: int, + dec_depth: int, + perm_num: int, + perm_forward: bool, + perm_mirrored: bool, + decode_ar: bool, + refine_iters: int, + dropout: float, + **kwargs: Any, + ) -> None: + super().__init__(charset_train, charset_test, batch_size, lr, warmup_pct, weight_decay) + self.save_hyperparameters() + + self.model = Model( + len(self.tokenizer), + max_label_length, + img_size, + patch_size, + embed_dim, + enc_num_heads, + enc_mlp_ratio, + enc_depth, + dec_num_heads, + dec_mlp_ratio, + dec_depth, + decode_ar, + refine_iters, + dropout, + ) + + # Perm/attn mask stuff + self.rng = np.random.default_rng() + self.max_gen_perms = perm_num // 2 if perm_mirrored else perm_num + self.perm_forward = perm_forward + self.perm_mirrored = perm_mirrored + + def forward(self, images: Tensor, max_length: Optional[int] = None) -> Tensor: + return self.model.forward(self.tokenizer, images, max_length) + + def gen_tgt_perms(self, tgt): + """Generate shared permutations for the whole batch. + This works because the same attention mask can be used for the shorter sequences + because of the padding mask. + """ + # We don't permute the position of BOS, we permute EOS separately + max_num_chars = tgt.shape[1] - 2 + # Special handling for 1-character sequences + if max_num_chars == 1: + return torch.arange(3, device=self._device).unsqueeze(0) + perms = [torch.arange(max_num_chars, device=self._device)] if self.perm_forward else [] + # Additional permutations if needed + max_perms = math.factorial(max_num_chars) + if self.perm_mirrored: + max_perms //= 2 + num_gen_perms = min(self.max_gen_perms, max_perms) + # For 4-char sequences and shorter, we generate all permutations and sample from the pool to avoid collisions + # Note that this code path might NEVER get executed since the labels in a mini-batch typically exceed 4 chars. + if max_num_chars < 5: + # Pool of permutations to sample from. We only need the first half (if complementary option is selected) + # Special handling for max_num_chars == 4 which correctly divides the pool into the flipped halves + if max_num_chars == 4 and self.perm_mirrored: + selector = [0, 3, 4, 6, 9, 10, 12, 16, 17, 18, 19, 21] + else: + selector = list(range(max_perms)) + perm_pool = torch.as_tensor( + list(permutations(range(max_num_chars), max_num_chars)), + device=self._device, + )[selector] + # If the forward permutation is always selected, no need to add it to the pool for sampling + if self.perm_forward: + perm_pool = perm_pool[1:] + perms = torch.stack(perms) + if len(perm_pool): + i = self.rng.choice(len(perm_pool), size=num_gen_perms - len(perms), replace=False) + perms = torch.cat([perms, perm_pool[i]]) + else: + perms.extend( + [torch.randperm(max_num_chars, device=self._device) for _ in range(num_gen_perms - len(perms))] + ) + perms = torch.stack(perms) + if self.perm_mirrored: + # Add complementary pairs + comp = perms.flip(-1) + # Stack in such a way that the pairs are next to each other. + perms = torch.stack([perms, comp]).transpose(0, 1).reshape(-1, max_num_chars) + # NOTE: + # The only meaningful way of permuting the EOS position is by moving it one character position at a time. + # However, since the number of permutations = T! and number of EOS positions = T + 1, the number of possible EOS + # positions will always be much less than the number of permutations (unless a low perm_num is set). + # Thus, it would be simpler to just train EOS using the full and null contexts rather than trying to evenly + # distribute it across the chosen number of permutations. + # Add position indices of BOS and EOS + bos_idx = perms.new_zeros((len(perms), 1)) + eos_idx = perms.new_full((len(perms), 1), max_num_chars + 1) + perms = torch.cat([bos_idx, perms + 1, eos_idx], dim=1) + # Special handling for the reverse direction. This does two things: + # 1. Reverse context for the characters + # 2. Null context for [EOS] (required for learning to predict [EOS] in NAR mode) + if len(perms) > 1: + perms[1, 1:] = max_num_chars + 1 - torch.arange(max_num_chars + 1, device=self._device) + return perms + + def generate_attn_masks(self, perm): + """Generate attention masks given a sequence permutation (includes pos. for bos and eos tokens) + :param perm: the permutation sequence. i = 0 is always the BOS + :return: lookahead attention masks + """ + sz = perm.shape[0] + mask = torch.zeros((sz, sz), dtype=torch.bool, device=self._device) + for i in range(sz): + query_idx = perm[i] + masked_keys = perm[i + 1 :] + mask[query_idx, masked_keys] = True + content_mask = mask[:-1, :-1].clone() + mask[torch.eye(sz, dtype=torch.bool, device=self._device)] = True # mask "self" + query_mask = mask[1:, :-1] + return content_mask, query_mask + + def training_step(self, batch, batch_idx) -> STEP_OUTPUT: + images, labels = batch + tgt = self.tokenizer.encode(labels, self._device) + + # Encode the source sequence (i.e. the image codes) + memory = self.model.encode(images) + + # Prepare the target sequences (input and output) + tgt_perms = self.gen_tgt_perms(tgt) + tgt_in = tgt[:, :-1] + tgt_out = tgt[:, 1:] + # The [EOS] token is not depended upon by any other token in any permutation ordering + tgt_padding_mask = (tgt_in == self.pad_id) | (tgt_in == self.eos_id) + + loss = 0 + loss_numel = 0 + n = (tgt_out != self.pad_id).sum().item() + for i, perm in enumerate(tgt_perms): + tgt_mask, query_mask = self.generate_attn_masks(perm) + out = self.model.decode(tgt_in, memory, tgt_mask, tgt_padding_mask, tgt_query_mask=query_mask) + logits = self.model.head(out).flatten(end_dim=1) + loss += n * F.cross_entropy(logits, tgt_out.flatten(), ignore_index=self.pad_id) + loss_numel += n + # After the second iteration (i.e. done with canonical and reverse orderings), + # remove the [EOS] tokens for the succeeding perms + if i == 1: + tgt_out = torch.where(tgt_out == self.eos_id, self.pad_id, tgt_out) + n = (tgt_out != self.pad_id).sum().item() + loss /= loss_numel + + self.log('loss', loss) + return loss diff --git a/torch/hub/baudm_parseq_main/strhub/models/trba/__init__.py b/torch/hub/baudm_parseq_main/strhub/models/trba/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a574a8af95e7f1ffaa05c45b4cd22f4a3cc0a5c0 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/trba/__init__.py @@ -0,0 +1,13 @@ +r""" +Baek, Jeonghun, Geewook Kim, Junyeop Lee, Sungrae Park, Dongyoon Han, Sangdoo Yun, Seong Joon Oh, and Hwalsuk Lee. +"What is wrong with scene text recognition model comparisons? dataset and model analysis." +In Proceedings of the IEEE/CVF International Conference on Computer Vision, pp. 4715-4723. 2019. + +https://arxiv.org/abs/1904.01906 + +All source files, except `system.py`, are based on the implementation listed below, +and hence are released under the license of the original. + +Source: https://github.com/clovaai/deep-text-recognition-benchmark +License: Apache License 2.0 (see LICENSE file in project root) +""" diff --git a/torch/hub/baudm_parseq_main/strhub/models/trba/feature_extraction.py b/torch/hub/baudm_parseq_main/strhub/models/trba/feature_extraction.py new file mode 100644 index 0000000000000000000000000000000000000000..17646e3ff83ad28c1021237824a838e38c3b6345 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/trba/feature_extraction.py @@ -0,0 +1,110 @@ +import torch.nn as nn + +from torchvision.models.resnet import BasicBlock + + +class ResNet_FeatureExtractor(nn.Module): + """ FeatureExtractor of FAN (http://openaccess.thecvf.com/content_ICCV_2017/papers/Cheng_Focusing_Attention_Towards_ICCV_2017_paper.pdf) """ + + def __init__(self, input_channel, output_channel=512): + super().__init__() + self.ConvNet = ResNet(input_channel, output_channel, BasicBlock, [1, 2, 5, 3]) + + def forward(self, input): + return self.ConvNet(input) + + +class ResNet(nn.Module): + + def __init__(self, input_channel, output_channel, block, layers): + super().__init__() + + self.output_channel_block = [int(output_channel / 4), int(output_channel / 2), output_channel, output_channel] + + self.inplanes = int(output_channel / 8) + self.conv0_1 = nn.Conv2d(input_channel, int(output_channel / 16), + kernel_size=3, stride=1, padding=1, bias=False) + self.bn0_1 = nn.BatchNorm2d(int(output_channel / 16)) + self.conv0_2 = nn.Conv2d(int(output_channel / 16), self.inplanes, + kernel_size=3, stride=1, padding=1, bias=False) + self.bn0_2 = nn.BatchNorm2d(self.inplanes) + self.relu = nn.ReLU(inplace=True) + + self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0) + self.layer1 = self._make_layer(block, self.output_channel_block[0], layers[0]) + self.conv1 = nn.Conv2d(self.output_channel_block[0], self.output_channel_block[ + 0], kernel_size=3, stride=1, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(self.output_channel_block[0]) + + self.maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0) + self.layer2 = self._make_layer(block, self.output_channel_block[1], layers[1], stride=1) + self.conv2 = nn.Conv2d(self.output_channel_block[1], self.output_channel_block[ + 1], kernel_size=3, stride=1, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(self.output_channel_block[1]) + + self.maxpool3 = nn.MaxPool2d(kernel_size=2, stride=(2, 1), padding=(0, 1)) + self.layer3 = self._make_layer(block, self.output_channel_block[2], layers[2], stride=1) + self.conv3 = nn.Conv2d(self.output_channel_block[2], self.output_channel_block[ + 2], kernel_size=3, stride=1, padding=1, bias=False) + self.bn3 = nn.BatchNorm2d(self.output_channel_block[2]) + + self.layer4 = self._make_layer(block, self.output_channel_block[3], layers[3], stride=1) + self.conv4_1 = nn.Conv2d(self.output_channel_block[3], self.output_channel_block[ + 3], kernel_size=2, stride=(2, 1), padding=(0, 1), bias=False) + self.bn4_1 = nn.BatchNorm2d(self.output_channel_block[3]) + self.conv4_2 = nn.Conv2d(self.output_channel_block[3], self.output_channel_block[ + 3], kernel_size=2, stride=1, padding=0, bias=False) + self.bn4_2 = nn.BatchNorm2d(self.output_channel_block[3]) + + def _make_layer(self, block, planes, blocks, stride=1): + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + nn.Conv2d(self.inplanes, planes * block.expansion, + kernel_size=1, stride=stride, bias=False), + nn.BatchNorm2d(planes * block.expansion), + ) + + layers = [] + layers.append(block(self.inplanes, planes, stride, downsample)) + self.inplanes = planes * block.expansion + for i in range(1, blocks): + layers.append(block(self.inplanes, planes)) + + return nn.Sequential(*layers) + + def forward(self, x): + x = self.conv0_1(x) + x = self.bn0_1(x) + x = self.relu(x) + x = self.conv0_2(x) + x = self.bn0_2(x) + x = self.relu(x) + + x = self.maxpool1(x) + x = self.layer1(x) + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + + x = self.maxpool2(x) + x = self.layer2(x) + x = self.conv2(x) + x = self.bn2(x) + x = self.relu(x) + + x = self.maxpool3(x) + x = self.layer3(x) + x = self.conv3(x) + x = self.bn3(x) + x = self.relu(x) + + x = self.layer4(x) + x = self.conv4_1(x) + x = self.bn4_1(x) + x = self.relu(x) + x = self.conv4_2(x) + x = self.bn4_2(x) + x = self.relu(x) + + return x diff --git a/torch/hub/baudm_parseq_main/strhub/models/trba/model.py b/torch/hub/baudm_parseq_main/strhub/models/trba/model.py new file mode 100644 index 0000000000000000000000000000000000000000..41161a4df4e2ff368bfe1c62f681c6964510a0c0 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/trba/model.py @@ -0,0 +1,55 @@ +import torch.nn as nn + +from strhub.models.modules import BidirectionalLSTM +from .feature_extraction import ResNet_FeatureExtractor +from .prediction import Attention +from .transformation import TPS_SpatialTransformerNetwork + + +class TRBA(nn.Module): + + def __init__(self, img_h, img_w, num_class, num_fiducial=20, input_channel=3, output_channel=512, hidden_size=256, + use_ctc=False): + super().__init__() + """ Transformation """ + self.Transformation = TPS_SpatialTransformerNetwork( + F=num_fiducial, I_size=(img_h, img_w), I_r_size=(img_h, img_w), + I_channel_num=input_channel) + + """ FeatureExtraction """ + self.FeatureExtraction = ResNet_FeatureExtractor(input_channel, output_channel) + self.FeatureExtraction_output = output_channel + self.AdaptiveAvgPool = nn.AdaptiveAvgPool2d((None, 1)) # Transform final (imgH/16-1) -> 1 + + """ Sequence modeling""" + self.SequenceModeling = nn.Sequential( + BidirectionalLSTM(self.FeatureExtraction_output, hidden_size, hidden_size), + BidirectionalLSTM(hidden_size, hidden_size, hidden_size)) + self.SequenceModeling_output = hidden_size + + """ Prediction """ + if use_ctc: + self.Prediction = nn.Linear(self.SequenceModeling_output, num_class) + else: + self.Prediction = Attention(self.SequenceModeling_output, hidden_size, num_class) + + def forward(self, image, max_label_length, text=None): + """ Transformation stage """ + image = self.Transformation(image) + + """ Feature extraction stage """ + visual_feature = self.FeatureExtraction(image) + visual_feature = visual_feature.permute(0, 3, 1, 2) # [b, c, h, w] -> [b, w, c, h] + visual_feature = self.AdaptiveAvgPool(visual_feature) # [b, w, c, h] -> [b, w, c, 1] + visual_feature = visual_feature.squeeze(3) # [b, w, c, 1] -> [b, w, c] + + """ Sequence modeling stage """ + contextual_feature = self.SequenceModeling(visual_feature) # [b, num_steps, hidden_size] + + """ Prediction stage """ + if isinstance(self.Prediction, Attention): + prediction = self.Prediction(contextual_feature.contiguous(), text, max_label_length) + else: + prediction = self.Prediction(contextual_feature.contiguous()) # CTC + + return prediction # [b, num_steps, num_class] diff --git a/torch/hub/baudm_parseq_main/strhub/models/trba/prediction.py b/torch/hub/baudm_parseq_main/strhub/models/trba/prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..5609398a28ef5288d3f3971786c2cebc2e574336 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/trba/prediction.py @@ -0,0 +1,73 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class Attention(nn.Module): + + def __init__(self, input_size, hidden_size, num_class, num_char_embeddings=256): + super().__init__() + self.attention_cell = AttentionCell(input_size, hidden_size, num_char_embeddings) + self.hidden_size = hidden_size + self.num_class = num_class + self.generator = nn.Linear(hidden_size, num_class) + self.char_embeddings = nn.Embedding(num_class, num_char_embeddings) + + def forward(self, batch_H, text, max_label_length=25): + """ + input: + batch_H : contextual_feature H = hidden state of encoder. [batch_size x num_steps x num_class] + text : the text-index of each image. [batch_size x (max_length+1)]. +1 for [SOS] token. text[:, 0] = [SOS]. + output: probability distribution at each step [batch_size x num_steps x num_class] + """ + batch_size = batch_H.size(0) + num_steps = max_label_length + 1 # +1 for [EOS] at end of sentence. + + output_hiddens = batch_H.new_zeros((batch_size, num_steps, self.hidden_size), dtype=torch.float) + hidden = (batch_H.new_zeros((batch_size, self.hidden_size), dtype=torch.float), + batch_H.new_zeros((batch_size, self.hidden_size), dtype=torch.float)) + + if self.training: + for i in range(num_steps): + char_embeddings = self.char_embeddings(text[:, i]) + # hidden : decoder's hidden s_{t-1}, batch_H : encoder's hidden H, char_embeddings : f(y_{t-1}) + hidden, alpha = self.attention_cell(hidden, batch_H, char_embeddings) + output_hiddens[:, i, :] = hidden[0] # LSTM hidden index (0: hidden, 1: Cell) + probs = self.generator(output_hiddens) + + else: + targets = text[0].expand(batch_size) # should be fill with [SOS] token + probs = batch_H.new_zeros((batch_size, num_steps, self.num_class), dtype=torch.float) + + for i in range(num_steps): + char_embeddings = self.char_embeddings(targets) + hidden, alpha = self.attention_cell(hidden, batch_H, char_embeddings) + probs_step = self.generator(hidden[0]) + probs[:, i, :] = probs_step + _, next_input = probs_step.max(1) + targets = next_input + + return probs # batch_size x num_steps x num_class + + +class AttentionCell(nn.Module): + + def __init__(self, input_size, hidden_size, num_embeddings): + super().__init__() + self.i2h = nn.Linear(input_size, hidden_size, bias=False) + self.h2h = nn.Linear(hidden_size, hidden_size) # either i2i or h2h should have bias + self.score = nn.Linear(hidden_size, 1, bias=False) + self.rnn = nn.LSTMCell(input_size + num_embeddings, hidden_size) + self.hidden_size = hidden_size + + def forward(self, prev_hidden, batch_H, char_embeddings): + # [batch_size x num_encoder_step x num_channel] -> [batch_size x num_encoder_step x hidden_size] + batch_H_proj = self.i2h(batch_H) + prev_hidden_proj = self.h2h(prev_hidden[0]).unsqueeze(1) + e = self.score(torch.tanh(batch_H_proj + prev_hidden_proj)) # batch_size x num_encoder_step * 1 + + alpha = F.softmax(e, dim=1) + context = torch.bmm(alpha.permute(0, 2, 1), batch_H).squeeze(1) # batch_size x num_channel + concat_context = torch.cat([context, char_embeddings], 1) # batch_size x (num_channel + num_embedding) + cur_hidden = self.rnn(concat_context, prev_hidden) + return cur_hidden, alpha diff --git a/torch/hub/baudm_parseq_main/strhub/models/trba/system.py b/torch/hub/baudm_parseq_main/strhub/models/trba/system.py new file mode 100644 index 0000000000000000000000000000000000000000..eabc5bacf3ef0a61d6b50cb1707c7da9eb2cb930 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/trba/system.py @@ -0,0 +1,125 @@ +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from functools import partial +from typing import Any, Optional, Sequence + +import torch +import torch.nn.functional as F +from torch import Tensor + +from pytorch_lightning.utilities.types import STEP_OUTPUT +from timm.models.helpers import named_apply + +from strhub.models.base import CrossEntropySystem, CTCSystem +from strhub.models.utils import init_weights + +from .model import TRBA as Model + + +class TRBA(CrossEntropySystem): + + def __init__( + self, + charset_train: str, + charset_test: str, + max_label_length: int, + batch_size: int, + lr: float, + warmup_pct: float, + weight_decay: float, + img_size: Sequence[int], + num_fiducial: int, + output_channel: int, + hidden_size: int, + **kwargs: Any, + ) -> None: + super().__init__(charset_train, charset_test, batch_size, lr, warmup_pct, weight_decay) + self.save_hyperparameters() + self.max_label_length = max_label_length + img_h, img_w = img_size + self.model = Model( + img_h, + img_w, + len(self.tokenizer), + num_fiducial, + output_channel=output_channel, + hidden_size=hidden_size, + use_ctc=False, + ) + named_apply(partial(init_weights, exclude=['Transformation.LocalizationNetwork.localization_fc2']), self.model) + + @torch.jit.ignore + def no_weight_decay(self): + return {'model.Prediction.char_embeddings.weight'} + + def forward(self, images: Tensor, max_length: Optional[int] = None) -> Tensor: + max_length = self.max_label_length if max_length is None else min(max_length, self.max_label_length) + text = images.new_full([1], self.bos_id, dtype=torch.long) + return self.model.forward(images, max_length, text) + + def training_step(self, batch, batch_idx) -> STEP_OUTPUT: + images, labels = batch + encoded = self.tokenizer.encode(labels, self.device) + inputs = encoded[:, :-1] # remove + targets = encoded[:, 1:] # remove + max_length = encoded.shape[1] - 2 # exclude and from count + logits = self.model.forward(images, max_length, inputs) + loss = F.cross_entropy(logits.flatten(end_dim=1), targets.flatten(), ignore_index=self.pad_id) + self.log('loss', loss) + return loss + + +class TRBC(CTCSystem): + + def __init__( + self, + charset_train: str, + charset_test: str, + max_label_length: int, + batch_size: int, + lr: float, + warmup_pct: float, + weight_decay: float, + img_size: Sequence[int], + num_fiducial: int, + output_channel: int, + hidden_size: int, + **kwargs: Any, + ) -> None: + super().__init__(charset_train, charset_test, batch_size, lr, warmup_pct, weight_decay) + self.save_hyperparameters() + self.max_label_length = max_label_length + img_h, img_w = img_size + self.model = Model( + img_h, + img_w, + len(self.tokenizer), + num_fiducial, + output_channel=output_channel, + hidden_size=hidden_size, + use_ctc=True, + ) + named_apply(partial(init_weights, exclude=['Transformation.LocalizationNetwork.localization_fc2']), self.model) + + def forward(self, images: Tensor, max_length: Optional[int] = None) -> Tensor: + # max_label_length is unused in CTC prediction + return self.model.forward(images, None) + + def training_step(self, batch, batch_idx) -> STEP_OUTPUT: + images, labels = batch + loss = self.forward_logits_loss(images, labels)[1] + self.log('loss', loss) + return loss diff --git a/torch/hub/baudm_parseq_main/strhub/models/trba/transformation.py b/torch/hub/baudm_parseq_main/strhub/models/trba/transformation.py new file mode 100644 index 0000000000000000000000000000000000000000..960419d135ec878aaaa3297c3ff5c22e998ef6be --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/trba/transformation.py @@ -0,0 +1,169 @@ +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class TPS_SpatialTransformerNetwork(nn.Module): + """ Rectification Network of RARE, namely TPS based STN """ + + def __init__(self, F, I_size, I_r_size, I_channel_num=1): + """ Based on RARE TPS + input: + batch_I: Batch Input Image [batch_size x I_channel_num x I_height x I_width] + I_size : (height, width) of the input image I + I_r_size : (height, width) of the rectified image I_r + I_channel_num : the number of channels of the input image I + output: + batch_I_r: rectified image [batch_size x I_channel_num x I_r_height x I_r_width] + """ + super().__init__() + self.F = F + self.I_size = I_size + self.I_r_size = I_r_size # = (I_r_height, I_r_width) + self.I_channel_num = I_channel_num + self.LocalizationNetwork = LocalizationNetwork(self.F, self.I_channel_num) + self.GridGenerator = GridGenerator(self.F, self.I_r_size) + + def forward(self, batch_I): + batch_C_prime = self.LocalizationNetwork(batch_I) # batch_size x K x 2 + # batch_size x n (= I_r_width x I_r_height) x 2 + build_P_prime = self.GridGenerator.build_P_prime(batch_C_prime) + build_P_prime_reshape = build_P_prime.reshape([build_P_prime.size(0), self.I_r_size[0], self.I_r_size[1], 2]) + + if torch.__version__ > "1.2.0": + batch_I_r = F.grid_sample(batch_I, build_P_prime_reshape, padding_mode='border', align_corners=True) + else: + batch_I_r = F.grid_sample(batch_I, build_P_prime_reshape, padding_mode='border') + + return batch_I_r + + +class LocalizationNetwork(nn.Module): + """ Localization Network of RARE, which predicts C' (K x 2) from I (I_width x I_height) """ + + def __init__(self, F, I_channel_num): + super().__init__() + self.F = F + self.I_channel_num = I_channel_num + self.conv = nn.Sequential( + nn.Conv2d(in_channels=self.I_channel_num, out_channels=64, kernel_size=3, stride=1, padding=1, + bias=False), nn.BatchNorm2d(64), nn.ReLU(True), + nn.MaxPool2d(2, 2), # batch_size x 64 x I_height/2 x I_width/2 + nn.Conv2d(64, 128, 3, 1, 1, bias=False), nn.BatchNorm2d(128), nn.ReLU(True), + nn.MaxPool2d(2, 2), # batch_size x 128 x I_height/4 x I_width/4 + nn.Conv2d(128, 256, 3, 1, 1, bias=False), nn.BatchNorm2d(256), nn.ReLU(True), + nn.MaxPool2d(2, 2), # batch_size x 256 x I_height/8 x I_width/8 + nn.Conv2d(256, 512, 3, 1, 1, bias=False), nn.BatchNorm2d(512), nn.ReLU(True), + nn.AdaptiveAvgPool2d(1) # batch_size x 512 + ) + + self.localization_fc1 = nn.Sequential(nn.Linear(512, 256), nn.ReLU(True)) + self.localization_fc2 = nn.Linear(256, self.F * 2) + + # Init fc2 in LocalizationNetwork + self.localization_fc2.weight.data.fill_(0) + """ see RARE paper Fig. 6 (a) """ + ctrl_pts_x = np.linspace(-1.0, 1.0, int(F / 2)) + ctrl_pts_y_top = np.linspace(0.0, -1.0, num=int(F / 2)) + ctrl_pts_y_bottom = np.linspace(1.0, 0.0, num=int(F / 2)) + ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1) + ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1) + initial_bias = np.concatenate([ctrl_pts_top, ctrl_pts_bottom], axis=0) + self.localization_fc2.bias.data = torch.from_numpy(initial_bias).float().view(-1) + + def forward(self, batch_I): + """ + input: batch_I : Batch Input Image [batch_size x I_channel_num x I_height x I_width] + output: batch_C_prime : Predicted coordinates of fiducial points for input batch [batch_size x F x 2] + """ + batch_size = batch_I.size(0) + features = self.conv(batch_I).view(batch_size, -1) + batch_C_prime = self.localization_fc2(self.localization_fc1(features)).view(batch_size, self.F, 2) + return batch_C_prime + + +class GridGenerator(nn.Module): + """ Grid Generator of RARE, which produces P_prime by multipling T with P """ + + def __init__(self, F, I_r_size): + """ Generate P_hat and inv_delta_C for later """ + super().__init__() + self.eps = 1e-6 + self.I_r_height, self.I_r_width = I_r_size + self.F = F + self.C = self._build_C(self.F) # F x 2 + self.P = self._build_P(self.I_r_width, self.I_r_height) + + # num_gpu = torch.cuda.device_count() + # if num_gpu > 1: + # for multi-gpu, you may need register buffer + self.register_buffer("inv_delta_C", torch.tensor( + self._build_inv_delta_C(self.F, self.C)).float()) # F+3 x F+3 + self.register_buffer("P_hat", torch.tensor(self._build_P_hat(self.F, self.C, self.P)).float()) # n x F+3 + # else: + # # for fine-tuning with different image width, you may use below instead of self.register_buffer + # self.inv_delta_C = torch.tensor(self._build_inv_delta_C(self.F, self.C)).float() # F+3 x F+3 + # self.P_hat = torch.tensor(self._build_P_hat(self.F, self.C, self.P)).float() # n x F+3 + + def _build_C(self, F): + """ Return coordinates of fiducial points in I_r; C """ + ctrl_pts_x = np.linspace(-1.0, 1.0, int(F / 2)) + ctrl_pts_y_top = -1 * np.ones(int(F / 2)) + ctrl_pts_y_bottom = np.ones(int(F / 2)) + ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1) + ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1) + C = np.concatenate([ctrl_pts_top, ctrl_pts_bottom], axis=0) + return C # F x 2 + + def _build_inv_delta_C(self, F, C): + """ Return inv_delta_C which is needed to calculate T """ + hat_C = np.zeros((F, F), dtype=float) # F x F + for i in range(0, F): + for j in range(i, F): + r = np.linalg.norm(C[i] - C[j]) + hat_C[i, j] = r + hat_C[j, i] = r + np.fill_diagonal(hat_C, 1) + hat_C = (hat_C ** 2) * np.log(hat_C) + # print(C.shape, hat_C.shape) + delta_C = np.concatenate( # F+3 x F+3 + [ + np.concatenate([np.ones((F, 1)), C, hat_C], axis=1), # F x F+3 + np.concatenate([np.zeros((2, 3)), np.transpose(C)], axis=1), # 2 x F+3 + np.concatenate([np.zeros((1, 3)), np.ones((1, F))], axis=1) # 1 x F+3 + ], + axis=0 + ) + inv_delta_C = np.linalg.inv(delta_C) + return inv_delta_C # F+3 x F+3 + + def _build_P(self, I_r_width, I_r_height): + I_r_grid_x = (np.arange(-I_r_width, I_r_width, 2) + 1.0) / I_r_width # self.I_r_width + I_r_grid_y = (np.arange(-I_r_height, I_r_height, 2) + 1.0) / I_r_height # self.I_r_height + P = np.stack( # self.I_r_width x self.I_r_height x 2 + np.meshgrid(I_r_grid_x, I_r_grid_y), + axis=2 + ) + return P.reshape([-1, 2]) # n (= self.I_r_width x self.I_r_height) x 2 + + def _build_P_hat(self, F, C, P): + n = P.shape[0] # n (= self.I_r_width x self.I_r_height) + P_tile = np.tile(np.expand_dims(P, axis=1), (1, F, 1)) # n x 2 -> n x 1 x 2 -> n x F x 2 + C_tile = np.expand_dims(C, axis=0) # 1 x F x 2 + P_diff = P_tile - C_tile # n x F x 2 + rbf_norm = np.linalg.norm(P_diff, ord=2, axis=2, keepdims=False) # n x F + rbf = np.multiply(np.square(rbf_norm), np.log(rbf_norm + self.eps)) # n x F + P_hat = np.concatenate([np.ones((n, 1)), P, rbf], axis=1) + return P_hat # n x F+3 + + def build_P_prime(self, batch_C_prime): + """ Generate Grid from batch_C_prime [batch_size x F x 2] """ + batch_size = batch_C_prime.size(0) + batch_inv_delta_C = self.inv_delta_C.repeat(batch_size, 1, 1) + batch_P_hat = self.P_hat.repeat(batch_size, 1, 1) + batch_C_prime_with_zeros = torch.cat((batch_C_prime, batch_C_prime.new_zeros( + (batch_size, 3, 2), dtype=torch.float)), dim=1) # batch_size x F+3 x 2 + batch_T = torch.bmm(batch_inv_delta_C, batch_C_prime_with_zeros) # batch_size x F+3 x 2 + batch_P_prime = torch.bmm(batch_P_hat, batch_T) # batch_size x n x 2 + return batch_P_prime # batch_size x n x 2 diff --git a/torch/hub/baudm_parseq_main/strhub/models/utils.py b/torch/hub/baudm_parseq_main/strhub/models/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..34f2354477aa6fb7aa4e101b939dd4d2c0d52964 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/utils.py @@ -0,0 +1,126 @@ +from pathlib import PurePath +from typing import Sequence + +import yaml + +import torch +from torch import nn + + +class InvalidModelError(RuntimeError): + """Exception raised for any model-related error (creation, loading)""" + + +_WEIGHTS_URL = { + 'parseq-tiny': 'https://github.com/baudm/parseq/releases/download/v1.0.0/parseq_tiny-e7a21b54.pt', + 'parseq-patch16-224': 'https://github.com/baudm/parseq/releases/download/v1.0.0/parseq_small_patch16_224-fcf06f5a.pt', + 'parseq': 'https://github.com/baudm/parseq/releases/download/v1.0.0/parseq-bb5792a6.pt', + 'abinet': 'https://github.com/baudm/parseq/releases/download/v1.0.0/abinet-1d1e373e.pt', + 'trba': 'https://github.com/baudm/parseq/releases/download/v1.0.0/trba-cfaed284.pt', + 'vitstr': 'https://github.com/baudm/parseq/releases/download/v1.0.0/vitstr-26d0fcf4.pt', + 'crnn': 'https://github.com/baudm/parseq/releases/download/v1.0.0/crnn-679d0e31.pt', +} + + +def _get_config(experiment: str, **kwargs): + """Emulates hydra config resolution""" + root = PurePath(__file__).parents[2] + with open(root / 'configs/main.yaml', 'r') as f: + config = yaml.load(f, yaml.Loader)['model'] + with open(root / 'configs/charset/94_full.yaml', 'r') as f: + config.update(yaml.load(f, yaml.Loader)['model']) + with open(root / f'configs/experiment/{experiment}.yaml', 'r') as f: + exp = yaml.load(f, yaml.Loader) + # Apply base model config + model = exp['defaults'][0]['override /model'] + with open(root / f'configs/model/{model}.yaml', 'r') as f: + config.update(yaml.load(f, yaml.Loader)) + # Apply experiment config + if 'model' in exp: + config.update(exp['model']) + config.update(kwargs) + # Workaround for now: manually cast the lr to the correct type. + config['lr'] = float(config['lr']) + return config + + +def _get_model_class(key): + if 'abinet' in key: + from .abinet.system import ABINet as ModelClass + elif 'crnn' in key: + from .crnn.system import CRNN as ModelClass + elif 'parseq' in key: + from .parseq.system import PARSeq as ModelClass + elif 'trba' in key: + from .trba.system import TRBA as ModelClass + elif 'trbc' in key: + from .trba.system import TRBC as ModelClass + elif 'vitstr' in key: + from .vitstr.system import ViTSTR as ModelClass + else: + raise InvalidModelError(f"Unable to find model class for '{key}'") + return ModelClass + + +def get_pretrained_weights(experiment): + try: + url = _WEIGHTS_URL[experiment] + except KeyError: + raise InvalidModelError(f"No pretrained weights found for '{experiment}'") from None + return torch.hub.load_state_dict_from_url(url=url, map_location='cpu', check_hash=True) + + +def create_model(experiment: str, pretrained: bool = False, **kwargs): + try: + config = _get_config(experiment, **kwargs) + except FileNotFoundError: + raise InvalidModelError(f"No configuration found for '{experiment}'") from None + ModelClass = _get_model_class(experiment) + print(ModelClass) + model = ModelClass(**config) + if pretrained: + m = model.model if 'parseq' in experiment else model + m.load_state_dict(get_pretrained_weights(experiment)) + return model + + +def load_from_checkpoint(checkpoint_path: str, **kwargs): + if checkpoint_path.startswith('pretrained='): + model_id = checkpoint_path.split('=', maxsplit=1)[1] + model = create_model(model_id, True, **kwargs) + else: + ModelClass = _get_model_class(checkpoint_path) + model = ModelClass.load_from_checkpoint(checkpoint_path, **kwargs) + return model + + +def parse_model_args(args): + kwargs = {} + arg_types = {t.__name__: t for t in [int, float, str]} + arg_types['bool'] = lambda v: v.lower() == 'true' # special handling for bool + for arg in args: + name, value = arg.split('=', maxsplit=1) + name, arg_type = name.split(':', maxsplit=1) + kwargs[name] = arg_types[arg_type](value) + return kwargs + + +def init_weights(module: nn.Module, name: str = '', exclude: Sequence[str] = ()): + """Initialize the weights using the typical initialization schemes used in SOTA models.""" + if any(map(name.startswith, exclude)): + return + if isinstance(module, nn.Linear): + nn.init.trunc_normal_(module.weight, std=0.02) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.trunc_normal_(module.weight, std=0.02) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + elif isinstance(module, nn.Conv2d): + nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu') + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, (nn.LayerNorm, nn.BatchNorm2d, nn.GroupNorm)): + nn.init.ones_(module.weight) + nn.init.zeros_(module.bias) diff --git a/torch/hub/baudm_parseq_main/strhub/models/vitstr/__init__.py b/torch/hub/baudm_parseq_main/strhub/models/vitstr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..19e985679da1fcaa6deb306697993fd601892d6c --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/vitstr/__init__.py @@ -0,0 +1,12 @@ +r""" +Atienza, Rowel. "Vision Transformer for Fast and Efficient Scene Text Recognition." +In International Conference on Document Analysis and Recognition (ICDAR). 2021. + +https://arxiv.org/abs/2105.08582 + +All source files, except `system.py`, are based on the implementation listed below, +and hence are released under the license of the original. + +Source: https://github.com/roatienza/deep-text-recognition-benchmark +License: Apache License 2.0 (see LICENSE file in project root) +""" diff --git a/torch/hub/baudm_parseq_main/strhub/models/vitstr/model.py b/torch/hub/baudm_parseq_main/strhub/models/vitstr/model.py new file mode 100644 index 0000000000000000000000000000000000000000..62c5d551626c325243a4f0d055869384a59b3910 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/vitstr/model.py @@ -0,0 +1,28 @@ +""" +Implementation of ViTSTR based on timm VisionTransformer. + +TODO: +1) distilled deit backbone +2) base deit backbone + +Copyright 2021 Rowel Atienza +""" + +from timm.models.vision_transformer import VisionTransformer + + +class ViTSTR(VisionTransformer): + """ + ViTSTR is basically a ViT that uses DeiT weights. + Modified head to support a sequence of characters prediction for STR. + """ + + def forward(self, x, seqlen: int = 25): + x = self.forward_features(x) + x = x[:, :seqlen] + + # batch, seqlen, embsize + b, s, e = x.size() + x = x.reshape(b * s, e) + x = self.head(x).view(b, s, self.num_classes) + return x diff --git a/torch/hub/baudm_parseq_main/strhub/models/vitstr/system.py b/torch/hub/baudm_parseq_main/strhub/models/vitstr/system.py new file mode 100644 index 0000000000000000000000000000000000000000..37b762e1a074055873413655e35ef2605ffa8238 --- /dev/null +++ b/torch/hub/baudm_parseq_main/strhub/models/vitstr/system.py @@ -0,0 +1,79 @@ +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any, Optional, Sequence + +import torch +from torch import Tensor + +from pytorch_lightning.utilities.types import STEP_OUTPUT + +from strhub.models.base import CrossEntropySystem +from strhub.models.utils import init_weights + +from .model import ViTSTR as Model + + +class ViTSTR(CrossEntropySystem): + + def __init__( + self, + charset_train: str, + charset_test: str, + max_label_length: int, + batch_size: int, + lr: float, + warmup_pct: float, + weight_decay: float, + img_size: Sequence[int], + patch_size: Sequence[int], + embed_dim: int, + num_heads: int, + **kwargs: Any, + ) -> None: + super().__init__(charset_train, charset_test, batch_size, lr, warmup_pct, weight_decay) + self.save_hyperparameters() + self.max_label_length = max_label_length + # We don't predict nor + self.model = Model( + img_size=img_size, + patch_size=patch_size, + depth=12, + mlp_ratio=4, + qkv_bias=True, + embed_dim=embed_dim, + num_heads=num_heads, + num_classes=len(self.tokenizer) - 2, + ) + # Non-zero weight init for the head + self.model.head.apply(init_weights) + + @torch.jit.ignore + def no_weight_decay(self): + return {'model.' + n for n in self.model.no_weight_decay()} + + def forward(self, images: Tensor, max_length: Optional[int] = None) -> Tensor: + max_length = self.max_label_length if max_length is None else min(max_length, self.max_label_length) + logits = self.model.forward(images, max_length + 2) # +2 tokens for [GO] and [s] + # Truncate to conform to other models. [GO] in ViTSTR is actually used as the padding (therefore, ignored). + # First position corresponds to the class token, which is unused and ignored in the original work. + logits = logits[:, 1:] + return logits + + def training_step(self, batch, batch_idx) -> STEP_OUTPUT: + images, labels = batch + loss = self.forward_logits_loss(images, labels)[1] + self.log('loss', loss) + return loss diff --git a/torch/hub/baudm_parseq_main/test.py b/torch/hub/baudm_parseq_main/test.py new file mode 100644 index 0000000000000000000000000000000000000000..898ce9e53f09f28b974abb0ab02d74fc1aba16e9 --- /dev/null +++ b/torch/hub/baudm_parseq_main/test.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import string +import sys +from dataclasses import dataclass + +from tqdm import tqdm + +import torch + +from strhub.data.module import SceneTextDataModule +from strhub.models.utils import load_from_checkpoint, parse_model_args + + +@dataclass +class Result: + dataset: str + num_samples: int + accuracy: float + ned: float + confidence: float + label_length: float + + +def print_results_table(results: list[Result], file=None): + w = max(map(len, map(getattr, results, ['dataset'] * len(results)))) + w = max(w, len('Dataset'), len('Combined')) + print('| {:<{w}} | # samples | Accuracy | 1 - NED | Confidence | Label Length |'.format('Dataset', w=w), file=file) + print('|:{:-<{w}}:|----------:|---------:|--------:|-----------:|-------------:|'.format('----', w=w), file=file) + c = Result('Combined', 0, 0, 0, 0, 0) + for res in results: + c.num_samples += res.num_samples + c.accuracy += res.num_samples * res.accuracy + c.ned += res.num_samples * res.ned + c.confidence += res.num_samples * res.confidence + c.label_length += res.num_samples * res.label_length + print( + f'| {res.dataset:<{w}} | {res.num_samples:>9} | {res.accuracy:>8.2f} | {res.ned:>7.2f} ' + f'| {res.confidence:>10.2f} | {res.label_length:>12.2f} |', + file=file, + ) + c.accuracy /= c.num_samples + c.ned /= c.num_samples + c.confidence /= c.num_samples + c.label_length /= c.num_samples + print('|-{:-<{w}}-|-----------|----------|---------|------------|--------------|'.format('----', w=w), file=file) + print( + f'| {c.dataset:<{w}} | {c.num_samples:>9} | {c.accuracy:>8.2f} | {c.ned:>7.2f} ' + f'| {c.confidence:>10.2f} | {c.label_length:>12.2f} |', + file=file, + ) + + +@torch.inference_mode() +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('checkpoint', help="Model checkpoint (or 'pretrained=')") + parser.add_argument('--data_root', default='data') + parser.add_argument('--batch_size', type=int, default=512) + parser.add_argument('--num_workers', type=int, default=4) + parser.add_argument('--cased', action='store_true', default=False, help='Cased comparison') + parser.add_argument('--punctuation', action='store_true', default=False, help='Check punctuation') + parser.add_argument('--new', action='store_true', default=False, help='Evaluate on new benchmark datasets') + parser.add_argument('--rotation', type=int, default=0, help='Angle of rotation (counter clockwise) in degrees.') + parser.add_argument('--device', default='cuda') + args, unknown = parser.parse_known_args() + kwargs = parse_model_args(unknown) + + charset_test = string.digits + string.ascii_lowercase + if args.cased: + charset_test += string.ascii_uppercase + if args.punctuation: + charset_test += string.punctuation + kwargs.update({'charset_test': charset_test}) + print(f'Additional keyword arguments: {kwargs}') + + model = load_from_checkpoint(args.checkpoint, **kwargs).eval().to(args.device) + hp = model.hparams + datamodule = SceneTextDataModule( + args.data_root, + '_unused_', + hp.img_size, + hp.max_label_length, + hp.charset_train, + hp.charset_test, + args.batch_size, + args.num_workers, + False, + rotation=args.rotation, + ) + + test_set = SceneTextDataModule.TEST_BENCHMARK_SUB + SceneTextDataModule.TEST_BENCHMARK + if args.new: + test_set += SceneTextDataModule.TEST_NEW + test_set = sorted(set(test_set)) + + results = {} + max_width = max(map(len, test_set)) + for name, dataloader in datamodule.test_dataloaders(test_set).items(): + total = 0 + correct = 0 + ned = 0 + confidence = 0 + label_length = 0 + for imgs, labels in tqdm(iter(dataloader), desc=f'{name:>{max_width}}'): + res = model.test_step((imgs.to(model.device), labels), -1)['output'] + total += res.num_samples + correct += res.correct + ned += res.ned + confidence += res.confidence + label_length += res.label_length + accuracy = 100 * correct / total + mean_ned = 100 * (1 - ned / total) + mean_conf = 100 * confidence / total + mean_label_length = label_length / total + results[name] = Result(name, total, accuracy, mean_ned, mean_conf, mean_label_length) + + result_groups = { + 'Benchmark (Subset)': SceneTextDataModule.TEST_BENCHMARK_SUB, + 'Benchmark': SceneTextDataModule.TEST_BENCHMARK, + } + if args.new: + result_groups.update({'New': SceneTextDataModule.TEST_NEW}) + with open(args.checkpoint + '.log.txt', 'w') as f: + for out in [f, sys.stdout]: + for group, subset in result_groups.items(): + print(f'{group} set:', file=out) + print_results_table([results[s] for s in subset], out) + print('\n', file=out) + + +if __name__ == '__main__': + main() diff --git a/torch/hub/baudm_parseq_main/tools/art_converter.py b/torch/hub/baudm_parseq_main/tools/art_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..f61e0b54b3e3c8facdb04b58767d2f3cdb08ed8b --- /dev/null +++ b/torch/hub/baudm_parseq_main/tools/art_converter.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 + +import json + +with open('train_task2_labels.json', 'r', encoding='utf8') as f: + d = json.load(f) + +with open('gt.txt', 'w', encoding='utf8') as f: + for k, v in d.items(): + if len(v) != 1: + print('error', v) + v = v[0] + if v['language'].lower() != 'latin': + # print('Skipping non-Latin:', v) + continue + if v['illegibility']: + # print('Skipping unreadable:', v) + continue + label = v['transcription'].strip() + if not label: + # print('Skipping blank label') + continue + if '#' in label and label != 'LocaL#3': + # print('Skipping corrupted label') + continue + f.write('\t'.join(['train_task2_images/' + k + '.jpg', label]) + '\n') diff --git a/torch/hub/baudm_parseq_main/tools/case_sensitive_str_datasets_converter.py b/torch/hub/baudm_parseq_main/tools/case_sensitive_str_datasets_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce7c0dd0f9202058ec3226ef223017a951e26ec --- /dev/null +++ b/torch/hub/baudm_parseq_main/tools/case_sensitive_str_datasets_converter.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 + +import os.path +import sys +from pathlib import Path + +d = sys.argv[1] +p = Path(d) + +gt = [] + +num_samples = len(list(p.glob('label/*.txt'))) +ext = 'jpg' if p.joinpath('IMG', '1.jpg').is_file() else 'png' + +for i in range(1, num_samples + 1): + img = p.joinpath('IMG', f'{i}.{ext}') + name = os.path.splitext(img.name)[0] + + with open(p.joinpath('label', f'{i}.txt'), 'r') as f: + label = f.readline() + gt.append((os.path.join('IMG', img.name), label)) + +with open(d + '/lmdb.txt', 'w', encoding='utf-8') as f: + for line in gt: + fname, label = line + fname = fname.strip() + label = label.strip() + f.write('\t'.join([fname, label]) + '\n') diff --git a/torch/hub/baudm_parseq_main/tools/coco_2_converter.py b/torch/hub/baudm_parseq_main/tools/coco_2_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..529607ff27531c4c95efea31cd9f439a1b0e9ee9 --- /dev/null +++ b/torch/hub/baudm_parseq_main/tools/coco_2_converter.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +import argparse +import html +import math +import os +import os.path as osp +from functools import partial + +import mmcv +from mmocr.utils.fileio import list_to_file +from PIL import Image + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Generate training and validation set of TextOCR ' 'by cropping box image.' + ) + parser.add_argument('root_path', help='Root dir path of TextOCR') + parser.add_argument('n_proc', default=1, type=int, help='Number of processes to run') + args = parser.parse_args() + return args + + +def process_img(args, src_image_root, dst_image_root): + # Dirty hack for multiprocessing + img_idx, img_info, anns = args + src_img = Image.open(osp.join(src_image_root, 'train2014', img_info['file_name'])) + src_w, src_h = src_img.size + labels = [] + for ann_idx, ann in enumerate(anns): + text_label = html.unescape(ann['utf8_string'].strip()) + + # Ignore empty labels + if ( + not text_label + or ann['class'] != 'machine printed' + or ann['language'] != 'english' + or ann['legibility'] != 'legible' + ): + continue + + # Some labels and images with '#' in the middle are actually good, but some aren't, so we just filter them all. + if text_label != '#' and '#' in text_label: + continue + + # Some labels use '*' to denote unreadable characters + if text_label.startswith('*') or text_label.endswith('*'): + continue + + pad = 2 + x, y, w, h = ann['bbox'] + x, y = max(0, math.floor(x) - pad), max(0, math.floor(y) - pad) + w, h = math.ceil(w), math.ceil(h) + x2, y2 = min(src_w, x + w + 2 * pad), min(src_h, y + h + 2 * pad) + dst_img = src_img.crop((x, y, x2, y2)) + dst_img_name = f'img_{img_idx}_{ann_idx}.jpg' + dst_img_path = osp.join(dst_image_root, dst_img_name) + # Preserve JPEG quality + dst_img.save(dst_img_path, qtables=src_img.quantization) + labels.append(f'{osp.basename(dst_image_root)}/{dst_img_name}' f' {text_label}') + src_img.close() + return labels + + +def convert_textocr(root_path, dst_image_path, dst_label_filename, annotation_filename, img_start_idx=0, nproc=1): + annotation_path = osp.join(root_path, annotation_filename) + if not osp.exists(annotation_path): + raise Exception(f'{annotation_path} not exists, please check and try again.') + src_image_root = root_path + + # outputs + dst_label_file = osp.join(root_path, dst_label_filename) + dst_image_root = osp.join(root_path, dst_image_path) + os.makedirs(dst_image_root, exist_ok=True) + + annotation = mmcv.load(annotation_path) + split = 'train' if 'train' in dst_label_filename else 'val' + + process_img_with_path = partial(process_img, src_image_root=src_image_root, dst_image_root=dst_image_root) + tasks = [] + for img_idx, img_info in enumerate(annotation['imgs'].values()): + if img_info['set'] != split: + continue + ann_ids = annotation['imgToAnns'][str(img_info['id'])] + anns = [annotation['anns'][str(ann_id)] for ann_id in ann_ids] + tasks.append((img_idx + img_start_idx, img_info, anns)) + + labels_list = mmcv.track_parallel_progress(process_img_with_path, tasks, keep_order=True, nproc=nproc) + final_labels = [] + for label_list in labels_list: + final_labels += label_list + list_to_file(dst_label_file, final_labels) + return len(annotation['imgs']) + + +def main(): + args = parse_args() + root_path = args.root_path + print('Processing training set...') + num_train_imgs = convert_textocr( + root_path=root_path, + dst_image_path='image', + dst_label_filename='train_label.txt', + annotation_filename='cocotext.v2.json', + nproc=args.n_proc, + ) + print('Processing validation set...') + convert_textocr( + root_path=root_path, + dst_image_path='image_val', + dst_label_filename='val_label.txt', + annotation_filename='cocotext.v2.json', + img_start_idx=num_train_imgs, + nproc=args.n_proc, + ) + print('Finish') + + +if __name__ == '__main__': + main() diff --git a/torch/hub/baudm_parseq_main/tools/coco_text_converter.py b/torch/hub/baudm_parseq_main/tools/coco_text_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..09d130dbe5bd2306c864bdcfab044c9ef5dc29c9 --- /dev/null +++ b/torch/hub/baudm_parseq_main/tools/coco_text_converter.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 + +for s in ['train', 'val']: + with open('{}_words_gt.txt'.format(s), 'r', encoding='utf8') as f: + d = f.readlines() + + with open('{}_lmdb.txt'.format(s), 'w', encoding='utf8') as f: + for line in d: + try: + fname, label = line.split(',', maxsplit=1) + except ValueError: + continue + fname = '{}_words/{}.jpg'.format(s, fname.strip()) + label = label.strip().strip('|') + f.write('\t'.join([fname, label]) + '\n') diff --git a/torch/hub/baudm_parseq_main/tools/create_lmdb_dataset.py b/torch/hub/baudm_parseq_main/tools/create_lmdb_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..9663dd87596c3a720d6a1397934337fd5b821878 --- /dev/null +++ b/torch/hub/baudm_parseq_main/tools/create_lmdb_dataset.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""a modified version of CRNN torch repository https://github.com/bgshih/crnn/blob/master/tool/create_dataset.py""" +import io +import os + +import fire +import lmdb +import numpy as np +from PIL import Image + + +def checkImageIsValid(imageBin): + if imageBin is None: + return False + img = Image.open(io.BytesIO(imageBin)).convert('RGB') + return np.prod(img.size) > 0 + + +def writeCache(env, cache): + with env.begin(write=True) as txn: + for k, v in cache.items(): + txn.put(k, v) + + +def createDataset(inputPath, gtFile, outputPath, checkValid=True): + """ + Create LMDB dataset for training and evaluation. + ARGS: + inputPath : input folder path where starts imagePath + outputPath : LMDB output path + gtFile : list of image path and label + checkValid : if true, check the validity of every image + """ + os.makedirs(outputPath, exist_ok=True) + env = lmdb.open(outputPath, map_size=1099511627776) + + cache = {} + cnt = 1 + + with open(gtFile, 'r', encoding='utf-8') as f: + data = f.readlines() + + nSamples = len(data) + for i, line in enumerate(data): + imagePath, label = line.strip().split(maxsplit=1) + imagePath = os.path.join(inputPath, imagePath) + with open(imagePath, 'rb') as f: + imageBin = f.read() + if checkValid: + try: + img = Image.open(io.BytesIO(imageBin)).convert('RGB') + except IOError as e: + with open(outputPath + '/error_image_log.txt', 'a') as log: + log.write('{}-th image data occured error: {}, {}\n'.format(i, imagePath, e)) + continue + if np.prod(img.size) == 0: + print('%s is not a valid image' % imagePath) + continue + + imageKey = 'image-%09d'.encode() % cnt + labelKey = 'label-%09d'.encode() % cnt + cache[imageKey] = imageBin + cache[labelKey] = label.encode() + + if cnt % 1000 == 0: + writeCache(env, cache) + cache = {} + print('Written %d / %d' % (cnt, nSamples)) + cnt += 1 + nSamples = cnt - 1 + cache['num-samples'.encode()] = str(nSamples).encode() + writeCache(env, cache) + env.close() + print('Created dataset with %d samples' % nSamples) + + +if __name__ == '__main__': + fire.Fire(createDataset) diff --git a/torch/hub/baudm_parseq_main/tools/filter_lmdb.py b/torch/hub/baudm_parseq_main/tools/filter_lmdb.py new file mode 100644 index 0000000000000000000000000000000000000000..10f30eb5581bb565d1d1874af3daabb0c41e6b21 --- /dev/null +++ b/torch/hub/baudm_parseq_main/tools/filter_lmdb.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +import io +import os +from argparse import ArgumentParser + +import lmdb +import numpy as np +from PIL import Image + + +def main(): + parser = ArgumentParser() + parser.add_argument('inputs', nargs='+', help='Path to input LMDBs') + parser.add_argument('--output', help='Path to output LMDB') + parser.add_argument('--min_image_dim', type=int, default=8) + args = parser.parse_args() + + os.makedirs(args.output, exist_ok=True) + with lmdb.open(args.output, map_size=1099511627776) as env_out: + in_samples = 0 + out_samples = 0 + samples_per_chunk = 1000 + for lmdb_in in args.inputs: + with lmdb.open(lmdb_in, readonly=True, max_readers=1, lock=False) as env_in: + with env_in.begin() as txn: + num_samples = int(txn.get('num-samples'.encode())) + in_samples += num_samples + chunks = np.array_split(range(num_samples), num_samples // samples_per_chunk) + for chunk in chunks: + cache = {} + with env_in.begin() as txn: + for index in chunk: + index += 1 # lmdb starts at 1 + image_key = f'image-{index:09d}'.encode() + image_bin = txn.get(image_key) + img = Image.open(io.BytesIO(image_bin)) + w, h = img.size + if w < args.min_image_dim or h < args.min_image_dim: + print(f'Skipping: {index}, w = {w}, h = {h}') + continue + out_samples += 1 # increment. start at 1 + label_key = f'label-{index:09d}'.encode() + out_label_key = f'label-{out_samples:09d}'.encode() + out_image_key = f'image-{out_samples:09d}'.encode() + cache[out_label_key] = txn.get(label_key) + cache[out_image_key] = image_bin + with env_out.begin(write=True) as txn: + for k, v in cache.items(): + txn.put(k, v) + print(f'Written samples from {chunk[0]} to {chunk[-1]}') + with env_out.begin(write=True) as txn: + txn.put('num-samples'.encode(), str(out_samples).encode()) + print(f'Written {out_samples} samples to {args.output} out of {in_samples} input samples.') + + +if __name__ == '__main__': + main() diff --git a/torch/hub/baudm_parseq_main/tools/lsvt_converter.py b/torch/hub/baudm_parseq_main/tools/lsvt_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..41695c6fa4fe175e956efd3945055480c6bde3bd --- /dev/null +++ b/torch/hub/baudm_parseq_main/tools/lsvt_converter.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +import argparse +import os +import os.path as osp +import re +from functools import partial + +import mmcv +import numpy as np +from mmocr.utils.fileio import list_to_file +from PIL import Image + + +def parse_args(): + parser = argparse.ArgumentParser(description='Generate training set of LSVT ' 'by cropping box image.') + parser.add_argument('root_path', help='Root dir path of LSVT') + parser.add_argument('n_proc', default=1, type=int, help='Number of processes to run') + args = parser.parse_args() + return args + + +def process_img(args, src_image_root, dst_image_root): + # Dirty hack for multiprocessing + img_idx, img_info, anns = args + try: + src_img = Image.open(osp.join(src_image_root, 'train_full_images_0/{}.jpg'.format(img_info))) + except IOError: + src_img = Image.open(osp.join(src_image_root, 'train_full_images_1/{}.jpg'.format(img_info))) + blacklist = ['LOFTINESS*'] + whitelist = ['#Find YOUR Fun#', 'Story #', '*0#'] + labels = [] + for ann_idx, ann in enumerate(anns): + text_label = ann['transcription'] + + # Ignore illegible or words with non-Latin characters + if ( + ann['illegibility'] + or re.findall(r'[\u4e00-\u9fff]+', text_label) + or text_label in blacklist + or ('#' in text_label and text_label not in whitelist) + ): + continue + + points = np.asarray(ann['points']) + x1, y1 = points.min(axis=0) + x2, y2 = points.max(axis=0) + + dst_img = src_img.crop((x1, y1, x2, y2)) + dst_img_name = f'img_{img_idx}_{ann_idx}.jpg' + dst_img_path = osp.join(dst_image_root, dst_img_name) + # Preserve JPEG quality + dst_img.save(dst_img_path, qtables=src_img.quantization) + labels.append(f'{osp.basename(dst_image_root)}/{dst_img_name}' f' {text_label}') + src_img.close() + return labels + + +def convert_lsvt(root_path, dst_image_path, dst_label_filename, annotation_filename, img_start_idx=0, nproc=1): + annotation_path = osp.join(root_path, annotation_filename) + if not osp.exists(annotation_path): + raise Exception(f'{annotation_path} not exists, please check and try again.') + src_image_root = root_path + + # outputs + dst_label_file = osp.join(root_path, dst_label_filename) + dst_image_root = osp.join(root_path, dst_image_path) + os.makedirs(dst_image_root, exist_ok=True) + + annotation = mmcv.load(annotation_path) + + process_img_with_path = partial(process_img, src_image_root=src_image_root, dst_image_root=dst_image_root) + tasks = [] + for img_idx, (img_info, anns) in enumerate(annotation.items()): + tasks.append((img_idx + img_start_idx, img_info, anns)) + labels_list = mmcv.track_parallel_progress(process_img_with_path, tasks, keep_order=True, nproc=nproc) + final_labels = [] + for label_list in labels_list: + final_labels += label_list + list_to_file(dst_label_file, final_labels) + return len(annotation) + + +def main(): + args = parse_args() + root_path = args.root_path + print('Processing training set...') + convert_lsvt( + root_path=root_path, + dst_image_path='image_train', + dst_label_filename='train_label.txt', + annotation_filename='train_full_labels.json', + nproc=args.n_proc, + ) + print('Finish') + + +if __name__ == '__main__': + main() diff --git a/torch/hub/baudm_parseq_main/tools/mlt19_converter.py b/torch/hub/baudm_parseq_main/tools/mlt19_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..665d497f9b691f8db00092206ca7018f296d995f --- /dev/null +++ b/torch/hub/baudm_parseq_main/tools/mlt19_converter.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 + +import sys + +root = sys.argv[1] + +with open(root + '/gt.txt', 'r') as f: + d = f.readlines() + +with open(root + '/lmdb.txt', 'w') as f: + for line in d: + img, script, label = line.split(',', maxsplit=2) + label = label.strip() + if label and script in ['Latin', 'Symbols']: + f.write('\t'.join([img, label]) + '\n') diff --git a/torch/hub/baudm_parseq_main/tools/openvino_converter.py b/torch/hub/baudm_parseq_main/tools/openvino_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..1b990d724af48f2c30c1945025af938ab519ae6b --- /dev/null +++ b/torch/hub/baudm_parseq_main/tools/openvino_converter.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +import math +import os +import os.path as osp +from argparse import ArgumentParser +from functools import partial + +import mmcv +from mmocr.utils.fileio import list_to_file +from PIL import Image + + +def parse_args(): + parser = ArgumentParser( + description='Generate training and validation set ' + 'of OpenVINO annotations for Open ' + 'Images by cropping box image.' + ) + parser.add_argument('root_path', help='Root dir containing images and annotations') + parser.add_argument('n_proc', default=1, type=int, help='Number of processes to run') + args = parser.parse_args() + return args + + +def process_img(args, src_image_root, dst_image_root): + # Dirty hack for multiprocessing + img_idx, img_info, anns = args + src_img = Image.open(osp.join(src_image_root, img_info['file_name'])) + labels = [] + for ann_idx, ann in enumerate(anns): + attrs = ann['attributes'] + text_label = attrs['transcription'] + + # Ignore illegible or non-English words + if not attrs['legible'] or attrs['language'] != 'english': + continue + + x, y, w, h = ann['bbox'] + x, y = max(0, math.floor(x)), max(0, math.floor(y)) + w, h = math.ceil(w), math.ceil(h) + dst_img = src_img.crop((x, y, x + w, y + h)) + dst_img_name = f'img_{img_idx}_{ann_idx}.jpg' + dst_img_path = osp.join(dst_image_root, dst_img_name) + # Preserve JPEG quality + dst_img.save(dst_img_path, qtables=src_img.quantization) + labels.append(f'{osp.basename(dst_image_root)}/{dst_img_name}' f' {text_label}') + src_img.close() + return labels + + +def convert_openimages(root_path, dst_image_path, dst_label_filename, annotation_filename, img_start_idx=0, nproc=1): + annotation_path = osp.join(root_path, annotation_filename) + if not osp.exists(annotation_path): + raise Exception(f'{annotation_path} not exists, please check and try again.') + src_image_root = root_path + + # outputs + dst_label_file = osp.join(root_path, dst_label_filename) + dst_image_root = osp.join(root_path, dst_image_path) + os.makedirs(dst_image_root, exist_ok=True) + + annotation = mmcv.load(annotation_path) + + process_img_with_path = partial(process_img, src_image_root=src_image_root, dst_image_root=dst_image_root) + tasks = [] + anns = {} + for ann in annotation['annotations']: + anns.setdefault(ann['image_id'], []).append(ann) + for img_idx, img_info in enumerate(annotation['images']): + tasks.append((img_idx + img_start_idx, img_info, anns[img_info['id']])) + labels_list = mmcv.track_parallel_progress(process_img_with_path, tasks, keep_order=True, nproc=nproc) + final_labels = [] + for label_list in labels_list: + final_labels += label_list + list_to_file(dst_label_file, final_labels) + return len(annotation['images']) + + +def main(): + args = parse_args() + root_path = args.root_path + print('Processing training set...') + num_train_imgs = 0 + for s in '125f': + num_train_imgs = convert_openimages( + root_path=root_path, + dst_image_path=f'image_{s}', + dst_label_filename=f'train_{s}_label.txt', + annotation_filename=f'text_spotting_openimages_v5_train_{s}.json', + img_start_idx=num_train_imgs, + nproc=args.n_proc, + ) + print('Processing validation set...') + convert_openimages( + root_path=root_path, + dst_image_path='image_val', + dst_label_filename='val_label.txt', + annotation_filename='text_spotting_openimages_v5_validation.json', + img_start_idx=num_train_imgs, + nproc=args.n_proc, + ) + print('Finish') + + +if __name__ == '__main__': + main() diff --git a/torch/hub/baudm_parseq_main/tools/test_abinet_lm_acc.py b/torch/hub/baudm_parseq_main/tools/test_abinet_lm_acc.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc7d828da85fd0430c80d0c24f650353693be64 --- /dev/null +++ b/torch/hub/baudm_parseq_main/tools/test_abinet_lm_acc.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +import argparse +import string +import sys + +from tqdm import tqdm + +import torch +import torch.nn.functional as F +from torch import Tensor +from torch.nn.utils.rnn import pad_sequence + +from strhub.data.module import SceneTextDataModule +from strhub.models.abinet.system import ABINet + +sys.path.insert(0, '.') +from test import Result, print_results_table + +from hubconf import _get_config + + +class ABINetLM(ABINet): + + def _encode(self, labels): + targets = [torch.arange(self.max_label_length + 1)] # dummy target. used to set pad_sequence() length + lengths = [] + for label in labels: + targets.append(torch.as_tensor([self.tokenizer._stoi[c] for c in label])) + lengths.append(len(label) + 1) + targets = pad_sequence(targets, batch_first=True, padding_value=0)[1:] # exclude dummy target + lengths = torch.as_tensor(lengths, device=self.device) + targets = ( + F.one_hot(targets, len(self.tokenizer._stoi))[..., : len(self.tokenizer._stoi) - 2].float().to(self.device) + ) + return targets, lengths + + def forward(self, labels: Tensor, max_length: int = None) -> Tensor: + targets, lengths = self._encode(labels) + return self.model.language(targets, lengths)['logits'] + + +def main(): + parser = argparse.ArgumentParser( + description='Measure the word accuracy of ABINet LM using the ground truth as input' + ) + parser.add_argument('checkpoint', help='Official pretrained weights for ABINet-LV (best-train-abinet.pth)') + parser.add_argument('--data_root', default='data') + parser.add_argument('--batch_size', type=int, default=512) + parser.add_argument('--num_workers', type=int, default=4) + parser.add_argument('--new', action='store_true', default=False, help='Evaluate on new benchmark datasets') + parser.add_argument('--device', default='cuda') + args = parser.parse_args() + + # charset used by original ABINet + charset = string.ascii_lowercase + '1234567890' + ckpt = torch.load(args.checkpoint) + + config = _get_config('abinet', charset_train=charset, charset_test=charset) + model = ABINetLM(**config) + model.model.load_state_dict(ckpt['model']) + + model = model.eval().to(args.device) + model.freeze() # disable autograd + hp = model.hparams + datamodule = SceneTextDataModule( + args.data_root, + '_unused_', + hp.img_size, + hp.max_label_length, + hp.charset_train, + hp.charset_test, + args.batch_size, + args.num_workers, + False, + ) + + test_set = SceneTextDataModule.TEST_BENCHMARK + if args.new: + test_set += SceneTextDataModule.TEST_NEW + test_set = sorted(set(test_set)) + + results = {} + max_width = max(map(len, test_set)) + for name, dataloader in datamodule.test_dataloaders(test_set).items(): + total = 0 + correct = 0 + ned = 0 + confidence = 0 + label_length = 0 + for _, labels in tqdm(iter(dataloader), desc=f'{name:>{max_width}}'): + res = model.test_step((labels, labels), -1)['output'] + total += res.num_samples + correct += res.correct + ned += res.ned + confidence += res.confidence + label_length += res.label_length + accuracy = 100 * correct / total + mean_ned = 100 * (1 - ned / total) + mean_conf = 100 * confidence / total + mean_label_length = label_length / total + results[name] = Result(name, total, accuracy, mean_ned, mean_conf, mean_label_length) + + result_groups = { + 'Benchmark': SceneTextDataModule.TEST_BENCHMARK, + } + if args.new: + result_groups.update({'New': SceneTextDataModule.TEST_NEW}) + for group, subset in result_groups.items(): + print(f'{group} set:') + print_results_table([results[s] for s in subset]) + print('\n') + + +if __name__ == '__main__': + main() diff --git a/torch/hub/baudm_parseq_main/tools/textocr_converter.py b/torch/hub/baudm_parseq_main/tools/textocr_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..ba5d143a814c5181982cdbf8cc7fe7f12f54c44d --- /dev/null +++ b/torch/hub/baudm_parseq_main/tools/textocr_converter.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import math +import os +import os.path as osp +from functools import partial + +import mmcv +import numpy as np +from mmocr.utils.fileio import list_to_file +from PIL import Image + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Generate training and validation set of TextOCR ' 'by cropping box image.' + ) + parser.add_argument('root_path', help='Root dir path of TextOCR') + parser.add_argument('n_proc', default=1, type=int, help='Number of processes to run') + parser.add_argument('--rectify_pose', action='store_true', help='Fix pose of rotated text to make them horizontal') + args = parser.parse_args() + return args + + +def rectify_image_pose(image, top_left, points): + # Points-based heuristics for determining text orientation w.r.t. bounding box + points = np.asarray(points).reshape(-1, 2) + dist = ((points - np.asarray(top_left)) ** 2).sum(axis=1) + left_midpoint = (points[0] + points[-1]) / 2 + right_corner_points = ((points - left_midpoint) ** 2).sum(axis=1).argsort()[-2:] + right_midpoint = points[right_corner_points].sum(axis=0) / 2 + d_x, d_y = abs(right_midpoint - left_midpoint) + + if dist[0] + dist[-1] <= dist[right_corner_points].sum(): + if d_x >= d_y: + rot = 0 + else: + rot = 90 + else: + if d_x >= d_y: + rot = 180 + else: + rot = -90 + if rot: + image = image.rotate(rot, expand=True) + return image + + +def process_img(args, src_image_root, dst_image_root): + # Dirty hack for multiprocessing + img_idx, img_info, anns, rectify_pose = args + src_img = Image.open(osp.join(src_image_root, img_info['file_name'])) + labels = [] + for ann_idx, ann in enumerate(anns): + text_label = ann['utf8_string'] + + # Ignore illegible or non-English words + if text_label == '.': + continue + + x, y, w, h = ann['bbox'] + x, y = max(0, math.floor(x)), max(0, math.floor(y)) + w, h = math.ceil(w), math.ceil(h) + dst_img = src_img.crop((x, y, x + w, y + h)) + if rectify_pose: + dst_img = rectify_image_pose(dst_img, (x, y), ann['points']) + dst_img_name = f'img_{img_idx}_{ann_idx}.jpg' + dst_img_path = osp.join(dst_image_root, dst_img_name) + # Preserve JPEG quality + dst_img.save(dst_img_path, qtables=src_img.quantization) + labels.append(f'{osp.basename(dst_image_root)}/{dst_img_name}' f' {text_label}') + src_img.close() + return labels + + +def convert_textocr( + root_path, dst_image_path, dst_label_filename, annotation_filename, img_start_idx=0, nproc=1, rectify_pose=False +): + annotation_path = osp.join(root_path, annotation_filename) + if not osp.exists(annotation_path): + raise Exception(f'{annotation_path} not exists, please check and try again.') + src_image_root = root_path + + # outputs + dst_label_file = osp.join(root_path, dst_label_filename) + dst_image_root = osp.join(root_path, dst_image_path) + os.makedirs(dst_image_root, exist_ok=True) + + annotation = mmcv.load(annotation_path) + + process_img_with_path = partial(process_img, src_image_root=src_image_root, dst_image_root=dst_image_root) + tasks = [] + for img_idx, img_info in enumerate(annotation['imgs'].values()): + ann_ids = annotation['imgToAnns'][img_info['id']] + anns = [annotation['anns'][ann_id] for ann_id in ann_ids] + tasks.append((img_idx + img_start_idx, img_info, anns, rectify_pose)) + labels_list = mmcv.track_parallel_progress(process_img_with_path, tasks, keep_order=True, nproc=nproc) + final_labels = [] + for label_list in labels_list: + final_labels += label_list + list_to_file(dst_label_file, final_labels) + return len(annotation['imgs']) + + +def main(): + args = parse_args() + root_path = args.root_path + print('Processing training set...') + num_train_imgs = convert_textocr( + root_path=root_path, + dst_image_path='image', + dst_label_filename='train_label.txt', + annotation_filename='TextOCR_0.1_train.json', + nproc=args.n_proc, + rectify_pose=args.rectify_pose, + ) + print('Processing validation set...') + convert_textocr( + root_path=root_path, + dst_image_path='image', + dst_label_filename='val_label.txt', + annotation_filename='TextOCR_0.1_val.json', + img_start_idx=num_train_imgs, + nproc=args.n_proc, + rectify_pose=args.rectify_pose, + ) + print('Finish') + + +if __name__ == '__main__': + main() diff --git a/torch/hub/baudm_parseq_main/train.py b/torch/hub/baudm_parseq_main/train.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c3aff5cbd6fb171a7a291072e20feadead7075 --- /dev/null +++ b/torch/hub/baudm_parseq_main/train.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import math +from pathlib import Path + +import hydra +from hydra.core.hydra_config import HydraConfig +from omegaconf import DictConfig, open_dict + +import torch + +from pytorch_lightning import Trainer +from pytorch_lightning.callbacks import ModelCheckpoint, StochasticWeightAveraging +from pytorch_lightning.loggers import TensorBoardLogger +from pytorch_lightning.strategies import DDPStrategy +from pytorch_lightning.utilities.model_summary import summarize + +from strhub.data.module import SceneTextDataModule +from strhub.models.base import BaseSystem +from strhub.models.utils import get_pretrained_weights + + +# Copied from OneCycleLR +def _annealing_cos(start, end, pct): + 'Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0.' + cos_out = math.cos(math.pi * pct) + 1 + return end + (start - end) / 2.0 * cos_out + + +def get_swa_lr_factor(warmup_pct, swa_epoch_start, div_factor=25, final_div_factor=1e4) -> float: + """Get the SWA LR factor for the given `swa_epoch_start`. Assumes OneCycleLR Scheduler.""" + total_steps = 1000 # Can be anything. We use 1000 for convenience. + start_step = int(total_steps * warmup_pct) - 1 + end_step = total_steps - 1 + step_num = int(total_steps * swa_epoch_start) - 1 + pct = (step_num - start_step) / (end_step - start_step) + return _annealing_cos(1, 1 / (div_factor * final_div_factor), pct) + + +@hydra.main(config_path='configs', config_name='main', version_base='1.2') +def main(config: DictConfig): + trainer_strategy = 'auto' + with open_dict(config): + # Resolve absolute path to data.root_dir + config.data.root_dir = hydra.utils.to_absolute_path(config.data.root_dir) + # Special handling for GPU-affected config + gpu = config.trainer.get('accelerator') == 'gpu' + devices = config.trainer.get('devices', 0) + if gpu: + # Use mixed-precision training + config.trainer.precision = 'bf16-mixed' if torch.get_autocast_gpu_dtype() is torch.bfloat16 else '16-mixed' + if gpu and devices > 1: + # Use DDP with optimizations + trainer_strategy = DDPStrategy(find_unused_parameters=False, gradient_as_bucket_view=True) + # Scale steps-based config + config.trainer.val_check_interval //= devices + if config.trainer.get('max_steps', -1) > 0: + config.trainer.max_steps //= devices + + # Special handling for PARseq + if config.model.get('perm_mirrored', False): + assert config.model.perm_num % 2 == 0, 'perm_num should be even if perm_mirrored = True' + + model: BaseSystem = hydra.utils.instantiate(config.model) + # If specified, use pretrained weights to initialize the model + if config.pretrained is not None: + m = model.model if config.model._target_.endswith('PARSeq') else model + m.load_state_dict(get_pretrained_weights(config.pretrained)) + print(summarize(model, max_depth=2)) + + datamodule: SceneTextDataModule = hydra.utils.instantiate(config.data) + + checkpoint = ModelCheckpoint( + monitor='val_accuracy', + mode='max', + save_top_k=3, + save_last=True, + filename='{epoch}-{step}-{val_accuracy:.4f}-{val_NED:.4f}', + ) + swa_epoch_start = 0.75 + swa_lr = config.model.lr * get_swa_lr_factor(config.model.warmup_pct, swa_epoch_start) + swa = StochasticWeightAveraging(swa_lr, swa_epoch_start) + cwd = ( + HydraConfig.get().runtime.output_dir + if config.ckpt_path is None + else str(Path(config.ckpt_path).parents[1].absolute()) + ) + trainer: Trainer = hydra.utils.instantiate( + config.trainer, + logger=TensorBoardLogger(cwd, '', '.'), + strategy=trainer_strategy, + enable_model_summary=False, + callbacks=[checkpoint, swa], + ) + trainer.fit(model, datamodule=datamodule, ckpt_path=config.ckpt_path) + + +if __name__ == '__main__': + main() diff --git a/torch/hub/baudm_parseq_main/tune.py b/torch/hub/baudm_parseq_main/tune.py new file mode 100644 index 0000000000000000000000000000000000000000..a5020322df6b89909d3cb203c9a15ff8357c01e9 --- /dev/null +++ b/torch/hub/baudm_parseq_main/tune.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +# Scene Text Recognition Model Hub +# Copyright 2022 Darwin Bautista +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import math +import os +import shutil +from pathlib import Path + +import hydra +import numpy as np +from hydra.core.hydra_config import HydraConfig +from omegaconf import DictConfig, open_dict +from ray import air, train, tune +from ray.tune import CLIReporter +from ray.tune.integration.pytorch_lightning import TuneReportCheckpointCallback +from ray.tune.schedulers import MedianStoppingRule +from ray.tune.search.ax import AxSearch + +from pytorch_lightning import LightningModule, Trainer +from pytorch_lightning.loggers import TensorBoardLogger + +from strhub.data.module import SceneTextDataModule +from strhub.models.base import BaseSystem + +log = logging.getLogger(__name__) + + +class MetricTracker(tune.Stopper): + """Tracks the trend of the metric. Stops downward/stagnant trials. Assumes metric is being maximized.""" + + def __init__(self, metric, max_t, patience: int = 3, window: int = 3) -> None: + super().__init__() + self.metric = metric + self.trial_history = {} + self.max_t = max_t + self.training_iteration = 0 + self.eps = 0.01 # sensitivity + self.patience = patience # number of consecutive downward/stagnant samples to trigger early stoppage. + self.kernel = self.gaussian_pdf(np.arange(window) - window // 2, sigma=0.6) + # Extra samples to keep in order to have better MAs + gradients for the middle p samples. + self.buffer = 2 * (len(self.kernel) // 2) + 2 + + @staticmethod + def gaussian_pdf(x, sigma=1.0): + return np.exp(-((x / sigma) ** 2) / 2) / (sigma * np.sqrt(2 * np.pi)) + + @staticmethod + def moving_average(x, k): + return np.convolve(x, k, 'valid') / k.sum() + + def __call__(self, trial_id, result): + self.training_iteration = result['training_iteration'] + if np.isnan(result['loss']) or self.training_iteration >= self.max_t: + try: + del self.trial_history[trial_id] + except KeyError: + pass + return True + history = self.trial_history.get(trial_id, []) + # FIFO queue of metric values. + history = history[-(self.patience + self.buffer - 1) :] + [result[self.metric]] + # Only start checking once we have enough data. At least one non-zero sample is required. + if len(history) == self.patience + self.buffer and sum(history) > 0: + smooth_grad = np.gradient(self.moving_average(history, self.kernel))[1:-1] # discard edge values. + # Check if trend is downward or stagnant + if (smooth_grad < self.eps).all(): + log.info(f'Stopping trial = {trial_id}, hist = {history}, grad = {smooth_grad}') + try: + del self.trial_history[trial_id] + except KeyError: + pass + return True + self.trial_history[trial_id] = history + return False + + def stop_all(self): + return False + + +class TuneReportCheckpointPruneCallback(TuneReportCheckpointCallback): + + def _handle(self, trainer: Trainer, pl_module: LightningModule): + super()._handle(trainer, pl_module) + # Prune older checkpoints + trial_dir = train.get_context().get_trial_dir() + for old in sorted(Path(trial_dir).glob('checkpoint_epoch=*-step=*'), key=os.path.getmtime)[:-1]: + log.info(f'Deleting old checkpoint: {old}') + shutil.rmtree(old) + + +def trainable(hparams, config): + with open_dict(config): + config.model.lr = hparams['lr'] + # config.model.weight_decay = hparams['wd'] + + model: BaseSystem = hydra.utils.instantiate(config.model) + datamodule: SceneTextDataModule = hydra.utils.instantiate(config.data) + + tune_callback = TuneReportCheckpointPruneCallback({ + 'loss': 'val_loss', + 'NED': 'val_NED', + 'accuracy': 'val_accuracy', + }) + if checkpoint := train.get_checkpoint(): + with checkpoint.as_directory() as checkpoint_dir: + ckpt_path = os.path.join(checkpoint_dir, 'checkpoint') + else: + ckpt_path = None + trainer: Trainer = hydra.utils.instantiate( + config.trainer, + enable_progress_bar=False, + enable_checkpointing=False, + logger=TensorBoardLogger(save_dir=train.get_context().get_trial_dir(), name='', version='.'), + callbacks=[tune_callback], + ) + trainer.fit(model, datamodule=datamodule, ckpt_path=ckpt_path) + + +@hydra.main(config_path='configs', config_name='tune', version_base='1.2') +def main(config: DictConfig): + # Special handling for PARseq + if config.model.get('perm_mirrored', False): + assert config.model.perm_num % 2 == 0, 'perm_num should be even if perm_mirrored = True' + # Modify config + with open_dict(config): + # Use mixed-precision training + if config.trainer.get('gpus', 0): + config.trainer.precision = 16 + # Resolve absolute path to data.root_dir + config.data.root_dir = hydra.utils.to_absolute_path(config.data.root_dir) + + hparams = { + 'lr': tune.loguniform(config.tune.lr.min, config.tune.lr.max), + # 'wd': tune.loguniform(config.tune.wd.min, config.tune.wd.max), + } + + steps_per_epoch = len(hydra.utils.instantiate(config.data).train_dataloader()) + val_steps = steps_per_epoch * config.trainer.max_epochs / config.trainer.val_check_interval + max_t = round(0.75 * val_steps) + warmup_t = round(config.model.warmup_pct * val_steps) + scheduler = MedianStoppingRule(time_attr='training_iteration', grace_period=warmup_t) + + # Always start by evenly diving the range in log scale. + lr = hparams['lr'] + start = np.log10(lr.lower) + stop = np.log10(lr.upper) + num = math.ceil(stop - start) + 1 + initial_points = [{'lr': np.clip(x, lr.lower, lr.upper).item()} for x in reversed(np.logspace(start, stop, num))] + search_alg = AxSearch(points_to_evaluate=initial_points) + + reporter = CLIReporter(parameter_columns=['lr'], metric_columns=['loss', 'accuracy', 'training_iteration']) + + out_dir = Path(HydraConfig.get().runtime.output_dir if config.tune.resume_dir is None else config.tune.resume_dir) + + resources_per_trial = { + 'cpu': 1, + 'gpu': config.tune.gpus_per_trial, + } + + wrapped_trainable = tune.with_parameters(tune.with_resources(trainable, resources_per_trial), config=config) + if config.tune.resume_dir is None: + tuner = tune.Tuner( + wrapped_trainable, + param_space=hparams, + tune_config=tune.TuneConfig( + mode='max', + metric='NED', + search_alg=search_alg, + scheduler=scheduler, + num_samples=config.tune.num_samples, + ), + run_config=air.RunConfig( + name=out_dir.name, + stop=MetricTracker('NED', max_t), + progress_reporter=reporter, + local_dir=str(out_dir.parent.absolute()), + ), + ) + else: + tuner = tune.Tuner.restore(config.tune.resume_dir, wrapped_trainable) + results = tuner.fit() + best_result = results.get_best_result() + + print('Best hyperparameters found were:', best_result.config) + print('with result:\n', best_result) + + +if __name__ == '__main__': + main() diff --git a/torch/hub/checkpoints/parseq-bb5792a6.pt b/torch/hub/checkpoints/parseq-bb5792a6.pt new file mode 100644 index 0000000000000000000000000000000000000000..1851880b182fffaf44e993e58f86b46205bd5401 --- /dev/null +++ b/torch/hub/checkpoints/parseq-bb5792a6.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb5792a68e367476abca029cbf8699abc805f3d3dc7e57aae45c8ec4f7b7cd00 +size 95392675 diff --git a/torch/hub/trusted_list b/torch/hub/trusted_list new file mode 100644 index 0000000000000000000000000000000000000000..170c596146a33308be724fcd451ab4adfdb68c30 --- /dev/null +++ b/torch/hub/trusted_list @@ -0,0 +1,3 @@ +baudm_parseq +._TorchOCR +_TorchOCR diff --git a/torchOcr.py b/torchOcr.py new file mode 100644 index 0000000000000000000000000000000000000000..f8c6347e61cb50e634fccaaecac64cf4f547c36c --- /dev/null +++ b/torchOcr.py @@ -0,0 +1,64 @@ +import os +import torch +from torchvision import transforms as T +from PIL import Image, ImageEnhance +from io import BytesIO + +MODEL_PATH = '/var/task/torch/hub/baudm_parseq_main' if os.path.isfile('/var/task/torch/hub/baudm_parseq_main') else 'torch/hub/baudm_parseq_main' +class OCRModel: + def __init__(self): + # Load the model + print(MODEL_PATH) + self.model = torch.hub.load(MODEL_PATH, 'parseq', source='local', pretrained=True, trust_repo=True).eval() + + # Preprocess transformation + self._preprocess = T.Compose([ + T.Resize((32, 128), T.InterpolationMode.BICUBIC), + T.ToTensor(), + T.Normalize(0.5, 0.5) + ]) + + def adjust_image(self, image, brightness=1.0, contrast=1.0, sharpness=1.0): + """ + Adjust the brightness, contrast, and sharpness of the image. + """ + enhancer = ImageEnhance.Brightness(image) + image = enhancer.enhance(brightness) + + enhancer = ImageEnhance.Contrast(image) + image = enhancer.enhance(contrast) + + enhancer = ImageEnhance.Sharpness(image) + image = enhancer.enhance(sharpness) + + return image + + def predict(self, image_input, brightness=1.0, contrast=1.0, sharpness=1.0): + """ + Predict text from an image. The image can be provided as a file path or a buffer. + """ + if isinstance(image_input, bytes): + image = Image.open(BytesIO(image_input)).convert('RGB') + else: + image = Image.open(image_input).convert('RGB') + + # Adjust the image according to user-defined values + image = self.adjust_image(image, brightness, contrast, sharpness) + image.save('adjusted_image.jpg') + # Preprocess the image + image = self._preprocess(image).unsqueeze(0) + + # Perform inference + with torch.no_grad(): + pred = self.model(image).softmax(-1) + label, _ = self.model.tokenizer.decode(pred) + + return label[0] + +# Example usage +# if __name__ == '__main__': +# ocr_model = OCRModel() # Instantiate the class +# with open('../../../Desktop/DFaqQf.png', 'rb') as image_file: +# image_buffer = image_file.read() +# result = ocr_model.predict(image_buffer, brightness=1.2, contrast=5.3, sharpness=2.1) # Example with adjusted values +# print("Detected Text:", result)