diff --git a/.github/contexts-example.png b/.github/contexts-example.png new file mode 100644 index 00000000..e2ae2da8 Binary files /dev/null and b/.github/contexts-example.png differ diff --git a/.github/gh-teaser.png b/.github/gh-teaser.png new file mode 100644 index 00000000..59625f7d Binary files /dev/null and b/.github/gh-teaser.png differ diff --git a/.github/system.png b/.github/system.png new file mode 100644 index 00000000..afbee46a Binary files /dev/null and b/.github/system.png differ diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..82ff1199 --- /dev/null +++ b/.gitignore @@ -0,0 +1,147 @@ +# Output directories +outputs/ +multirun/ +ray_results/ + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.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/Datasets.md b/Datasets.md new file mode 100644 index 00000000..251b4b37 --- /dev/null +++ b/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\] | +| [COCO-Text v1.4](https://rrc.cvc.uab.es/?ch=5) | 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 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/LICENSE b/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/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/NOTICE b/NOTICE new file mode 100644 index 00000000..e5c7919c --- /dev/null +++ b/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/README.md b/README.md new file mode 100644 index 00000000..e2b16d97 --- /dev/null +++ b/README.md @@ -0,0 +1,193 @@ +
+ +# Scene Text Recognition with
Permuted Autoregressive Sequence Models +[![Apache License 2.0](https://img.shields.io/badge/license-Apache 2.0-blue.svg)](https://github.com/baudm/parseq/blob/main/LICENSE) +[![arXiv preprint](http://img.shields.io/badge/arXiv-2207.06966-B31B1B.svg)](https://arxiv.org/abs/2207.06966) +[![In Proc. ECCV 2022](http://img.shields.io/badge/ECCV-2022-4b44ce.svg)](https://eccv2022.ecva.net/) + +[**Darwin Bautista**](https://github.com/baudm) and [**Rowel Atienza**](https://github.com/roatienza) + +Electrical and Electronics Engineering Institute
+University of the Philippines, Diliman + +
+ +Scene Text Recognition (STR) models use language context to be more robust against noisy or corrupted images. Recent approaches like ABINet propose a standalone or external Language Model (LM) for prediction refinement. In this work, we argue 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. + +![PARSeq](.github/gh-teaser.png) + +The figure above shows word accuracy (94-character set) vs three common computational cost indicators. PARSeq-S (our base model) achieves state-of-the-art performance while being optimal in parameter count, FLOPS, and latency. Its downsized variant, PARSeq-Ti, also achieves high word accuracy while being comparable to CRNN in parameter count and FLOPS. + +**NOTE:** _P-S and P-Ti are shorthands for PARSeq-S and PARSeq-Ti, respectively. For TRBA and PARSeqA, FLOPS and latency correspond to mean values measured on the benchmark._ + +### 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._ +
+ +### 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
+ +The dynamic nature of attention masking in Transformers allows us to control and change information flow without modifying the model architecture. This characteristic coupled with Permutation Language Modeling (PLM) allows for a _unified_ STR model 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) + +## 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). + +### Installation +Tested on Python 3.9. Requires PyTorch >= 1.10. +```bash +$ pip install -r requirements.txt +$ pip install -e . + ``` +### 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`, and `parseq`. +```python +import torch +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 = torch.randint(0, 256, (1, 3, 32, 128)) # Load image: (B, C, H, W) +img = img_transform(img) # Preprocess + +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) +``` + +## Training + +The training script can train any supported model. Default configuration is stored in ```configs/model```. You can override any configuration using the command line. Please refer to [Hydra](https://hydra.cc) docs for more info about the syntax. +```bash +$ ./train.py model=parseq model.perm_num=12 model.embed_dim=512 # dual-GPU setup. Set embed_dim to 512 instead of 384 +$ ./train.py +experiment=parseq-tiny trainer.gpus=4 # quad-GPU setup. Train tiny variant of PARSeq. See configs/experiment. +``` + +## Tuning + +We use [Ray Tune](https://www.ray.io/ray-tune) for automated parameter tuning of the learning rate. 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 +``` + +## 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 /path/to/parseq.pt +``` +**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/* +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 outputs/parseq/2021-10-28_23-23-10/checkpoints/last.ckpt refine_iters:int=2 decode_ar:bool=false --images demo_images/* +``` +

+ +## Citation +If you find our work useful, or use it in your research, please cite: +```bibtex +@InProceedings{Bautista_2022_ECCV_parseq, + author={Bautista, Darwin and Atienza, Rowel}, + title={Scene Text Recognition with Permuted Autoregressive Sequence Models}, + booktitle={Proceedings of the 17th European Conference on Computer Vision (ECCV)}, + month={10}, + year={2022}, + publisher={Springer International Publishing}, + address={Cham} +} +``` diff --git a/bench.py b/bench.py new file mode 100755 index 00000000..2a7b897b --- /dev/null +++ b/bench.py @@ -0,0 +1,57 @@ +#!/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 +import torch +from fvcore.nn import FlopCountAnalysis, ActivationCountAnalysis, flop_count_table +from omegaconf import DictConfig +from torch.utils import benchmark + + +@hydra.main(config_path='configs', config_name='bench') +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) + model.freeze() # disable autograd + + 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/configs/bench.yaml b/configs/bench.yaml new file mode 100644 index 00000000..4b5872aa --- /dev/null +++ b/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/configs/charset/36_lowercase.yaml b/configs/charset/36_lowercase.yaml new file mode 100644 index 00000000..ce2a5a08 --- /dev/null +++ b/configs/charset/36_lowercase.yaml @@ -0,0 +1,3 @@ +# @package _global_ +model: + charset_train: "0123456789abcdefghijklmnopqrstuvwxyz" diff --git a/configs/charset/62_mixed-case.yaml b/configs/charset/62_mixed-case.yaml new file mode 100644 index 00000000..07db8445 --- /dev/null +++ b/configs/charset/62_mixed-case.yaml @@ -0,0 +1,3 @@ +# @package _global_ +model: + charset_train: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" diff --git a/configs/charset/94_full.yaml b/configs/charset/94_full.yaml new file mode 100644 index 00000000..186bf42e --- /dev/null +++ b/configs/charset/94_full.yaml @@ -0,0 +1,3 @@ +# @package _global_ +model: + charset_train: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" diff --git a/configs/experiment/abinet-sv.yaml b/configs/experiment/abinet-sv.yaml new file mode 100644 index 00000000..fa2b0118 --- /dev/null +++ b/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/configs/experiment/abinet.yaml b/configs/experiment/abinet.yaml new file mode 100644 index 00000000..d6915e0a --- /dev/null +++ b/configs/experiment/abinet.yaml @@ -0,0 +1,3 @@ +# @package _global_ +defaults: + - override /model: abinet diff --git a/configs/experiment/crnn.yaml b/configs/experiment/crnn.yaml new file mode 100644 index 00000000..32e6c028 --- /dev/null +++ b/configs/experiment/crnn.yaml @@ -0,0 +1,6 @@ +# @package _global_ +defaults: + - override /model: crnn + +data: + num_workers: 5 diff --git a/configs/experiment/parseq-tiny.yaml b/configs/experiment/parseq-tiny.yaml new file mode 100644 index 00000000..9e5879ef --- /dev/null +++ b/configs/experiment/parseq-tiny.yaml @@ -0,0 +1,6 @@ +# @package _global_ +model: + name: parseq-tiny + embed_dim: 192 + enc_num_heads: 3 + dec_num_heads: 6 diff --git a/configs/experiment/parseq.yaml b/configs/experiment/parseq.yaml new file mode 100644 index 00000000..bfb8da13 --- /dev/null +++ b/configs/experiment/parseq.yaml @@ -0,0 +1,3 @@ +# @package _global_ +defaults: + - override /model: parseq diff --git a/configs/experiment/trba.yaml b/configs/experiment/trba.yaml new file mode 100644 index 00000000..59907202 --- /dev/null +++ b/configs/experiment/trba.yaml @@ -0,0 +1,6 @@ +# @package _global_ +defaults: + - override /model: trba + +data: + num_workers: 3 diff --git a/configs/experiment/trbc.yaml b/configs/experiment/trbc.yaml new file mode 100644 index 00000000..a66ba1da --- /dev/null +++ b/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/configs/experiment/tune_abinet-lm.yaml b/configs/experiment/tune_abinet-lm.yaml new file mode 100644 index 00000000..6efa5283 --- /dev/null +++ b/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/configs/experiment/vitstr.yaml b/configs/experiment/vitstr.yaml new file mode 100644 index 00000000..6a8111ae --- /dev/null +++ b/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/configs/main.yaml b/configs/main.yaml new file mode 100644 index 00000000..759f2806 --- /dev/null +++ b/configs/main.yaml @@ -0,0 +1,47 @@ +defaults: + - _self_ + - model: parseq + - charset: 94_full + - train_set: 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: ??? + img_size: ${model.img_size} + charset_train: ${model.charset_train} + charset_test: ${model.charset_test} + max_label_length: ${model.max_label_length} + batch_size: ${model.batch_size} + num_workers: 2 + augment: true + +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 + terminate_on_nan: true + gradient_clip_val: 20 + gpus: 2 + +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/configs/model/abinet.yaml b/configs/model/abinet.yaml new file mode 100644 index 00000000..a19757ad --- /dev/null +++ b/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/configs/model/crnn.yaml b/configs/model/crnn.yaml new file mode 100644 index 00000000..9c109e4f --- /dev/null +++ b/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/configs/model/parseq.yaml b/configs/model/parseq.yaml new file mode 100644 index 00000000..16c9b09a --- /dev/null +++ b/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/configs/model/trba.yaml b/configs/model/trba.yaml new file mode 100644 index 00000000..717e4642 --- /dev/null +++ b/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/configs/model/vitstr.yaml b/configs/model/vitstr.yaml new file mode 100644 index 00000000..a8207426 --- /dev/null +++ b/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/configs/train_set/real.yaml b/configs/train_set/real.yaml new file mode 100644 index 00000000..786042d1 --- /dev/null +++ b/configs/train_set/real.yaml @@ -0,0 +1,3 @@ +# @package _global_ +data: + train_dir: real diff --git a/configs/train_set/synth.yaml b/configs/train_set/synth.yaml new file mode 100644 index 00000000..0a7f0719 --- /dev/null +++ b/configs/train_set/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/configs/tune.yaml b/configs/tune.yaml new file mode 100644 index 00000000..d58ad9cd --- /dev/null +++ b/configs/tune.yaml @@ -0,0 +1,10 @@ +defaults: + - main + - _self_ + +trainer: + gpus: 1 # tuning with DDP is not yet supported. + +hydra: + run: + dir: ray_results/${model.name}/${now:%Y-%m-%d}_${now:%H-%M-%S} diff --git a/demo_images/art-01107.jpg b/demo_images/art-01107.jpg new file mode 100644 index 00000000..157b4072 Binary files /dev/null and b/demo_images/art-01107.jpg differ diff --git a/demo_images/coco-1166773.jpg b/demo_images/coco-1166773.jpg new file mode 100644 index 00000000..ecfad882 Binary files /dev/null and b/demo_images/coco-1166773.jpg differ diff --git a/demo_images/cute-184.jpg b/demo_images/cute-184.jpg new file mode 100644 index 00000000..62e9de81 Binary files /dev/null and b/demo_images/cute-184.jpg differ diff --git a/demo_images/ic13_word_256.png b/demo_images/ic13_word_256.png new file mode 100644 index 00000000..381b841f Binary files /dev/null and b/demo_images/ic13_word_256.png differ diff --git a/demo_images/ic15_word_26.png b/demo_images/ic15_word_26.png new file mode 100644 index 00000000..a638fb30 Binary files /dev/null and b/demo_images/ic15_word_26.png differ diff --git a/demo_images/uber-27491.jpg b/demo_images/uber-27491.jpg new file mode 100644 index 00000000..845f6c5b Binary files /dev/null and b/demo_images/uber-27491.jpg differ diff --git a/hubconf.py b/hubconf.py new file mode 100644 index 00000000..f8db8703 --- /dev/null +++ b/hubconf.py @@ -0,0 +1,130 @@ +from pathlib import PurePath + +import torch +import yaml + + +dependencies = ['torch', 'pytorch_lightning', 'timm'] + + +def _get_config(model: str, experiment: str = None, **kwargs): + """Emulates hydra config resolution""" + root = PurePath(__file__).parent + with open(root.joinpath('configs/main.yaml'), 'r') as f: + config = yaml.load(f, yaml.Loader)['model'] + with open(root.joinpath(f'configs/charset/94_full.yaml'), 'r') as f: + config.update(yaml.load(f, yaml.Loader)['model']) + with open(root.joinpath(f'configs/model/{model}.yaml'), 'r') as f: + config.update(yaml.load(f, yaml.Loader)) + if experiment is not None: + with open(root.joinpath(f'configs/experiment/{experiment}.yaml'), 'r') as f: + config.update(yaml.load(f, yaml.Loader)['model']) + config.update(kwargs) + return config + + +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 + """ + from strhub.models.parseq.system import PARSeq + config = _get_config('parseq', 'parseq-tiny', decode_ar=decode_ar, refine_iters=refine_iters, **kwargs) + model = PARSeq(**config) + if pretrained: + checkpoint = torch.hub.load_state_dict_from_url( + url='https://github.com/baudm/parseq/releases/download/v1.0.0/parseq_tiny-e7a21b54.pt', + map_location='cpu', check_hash=True + ) + model.load_state_dict(checkpoint) + return model + + +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 + """ + from strhub.models.parseq.system import PARSeq + config = _get_config('parseq', decode_ar=decode_ar, refine_iters=refine_iters, **kwargs) + model = PARSeq(**config) + if pretrained: + checkpoint = torch.hub.load_state_dict_from_url( + url='https://github.com/baudm/parseq/releases/download/v1.0.0/parseq-bb5792a6.pt', + map_location='cpu', check_hash=True + ) + model.load_state_dict(checkpoint) + return model + + +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 + """ + from strhub.models.abinet.system import ABINet + config = _get_config('abinet', iter_size=iter_size, **kwargs) + model = ABINet(**config) + if pretrained: + checkpoint = torch.hub.load_state_dict_from_url( + url='https://github.com/baudm/parseq/releases/download/v1.0.0/abinet-1d1e373e.pt', + map_location='cpu', check_hash=True + ) + model.load_state_dict(checkpoint) + return model + + +def trba(pretrained: bool = False, **kwargs): + """ + TRBA model (img_size=128x32) + @param pretrained: (bool) Use pretrained weights + """ + from strhub.models.trba.system import TRBA + config = _get_config('trba', **kwargs) + model = TRBA(**config) + if pretrained: + checkpoint = torch.hub.load_state_dict_from_url( + url='https://github.com/baudm/parseq/releases/download/v1.0.0/trba-cfaed284.pt', + map_location='cpu', check_hash=True + ) + model.load_state_dict(checkpoint) + return model + + +def vitstr(pretrained: bool = False, **kwargs): + """ + ViTSTR small model (img_size=128x32, patch_size=8x4, d_model=384) + @param pretrained: (bool) Use pretrained weights + """ + from strhub.models.vitstr.system import ViTSTR + config = _get_config('vitstr', **kwargs) + model = ViTSTR(**config) + if pretrained: + checkpoint = torch.hub.load_state_dict_from_url( + url='https://github.com/baudm/parseq/releases/download/v1.0.0/vitstr-26d0fcf4.pt', + map_location='cpu', check_hash=True + ) + model.load_state_dict(checkpoint) + return model + + +def crnn(pretrained: bool = False, **kwargs): + """ + CRNN model (img_size=128x32) + @param pretrained: (bool) Use pretrained weights + """ + from strhub.models.crnn.system import CRNN + config = _get_config('crnn', **kwargs) + model = CRNN(**config) + if pretrained: + checkpoint = torch.hub.load_state_dict_from_url( + url='https://github.com/baudm/parseq/releases/download/v1.0.0/crnn-679d0e31.pt', + map_location='cpu', check_hash=True + ) + model.load_state_dict(checkpoint) + return model diff --git a/read.py b/read.py new file mode 100755 index 00000000..d9e7377c --- /dev/null +++ b/read.py @@ -0,0 +1,49 @@ +#!/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 + +from strhub.data.module import SceneTextDataModule +from strhub.models.utils import load_from_checkpoint, parse_model_args + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('checkpoint', help='Model checkpoint') + 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) + model.freeze() # disable autograd + 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/requirements.txt b/requirements.txt new file mode 100644 index 00000000..0e2110ee --- /dev/null +++ b/requirements.txt @@ -0,0 +1,15 @@ +torch==1.10.2 +torchtext==0.11.2 +torchvision==0.11.3 +pytorch-lightning==1.4.9 +torchmetrics==0.6.2 +timm==0.4.12 +nltk==3.6.5 +lmdb==1.2.1 +opencv-python==4.5.4.58 +imgaug==0.4.0 +hydra-core==1.1.1 +fvcore==0.1.5.post20211023 +ray==1.7.1 +ax-platform==0.2.2 +SQLAlchemy==1.4.26 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 00000000..268bbb91 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,43 @@ +[tool:pytest] +norecursedirs = + .git + dist + build +addopts = + --strict + --doctest-modules + --durations=0 + +[coverage:report] +exclude_lines = + pragma: no-cover + pass + +[flake8] +max-line-length = 120 +exclude = .tox,*.egg,build,temp +select = E,W,F +doctests = True +verbose = 2 +# https://pep8.readthedocs.io/en/latest/intro.html#error-codes +format = pylint +# see: https://www.flake8rules.com/ +ignore = + E731 # Do not assign a lambda expression, use a def + W504 # Line break occurred after a binary operator + F401 # Module imported but unused + F841 # Local variable name is assigned to but never used + W605 # Invalid escape sequence 'x' + +# setup.cfg or tox.ini +[check-manifest] +ignore = + *.yml + .github + .github/* + +[metadata] +license_file = LICENSE +description-file = README.md +# long_description = file:README.md +# long_description_content_type = text/markdown diff --git a/setup.py b/setup.py new file mode 100644 index 00000000..05945655 --- /dev/null +++ b/setup.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python + +from setuptools import setup, find_packages + +setup( + name='strhub', + version='0.1.0', + description='Scene Text Recognition Model Hub: A collection of deep learning models for Scene Text Recognition', + author='Darwin Bautista', + author_email='baudm@users.noreply.github.com', + url='https://github.com/baudm/parseq', + install_requires=['torch~=1.10.2', 'pytorch-lightning~=1.4.9', 'timm~=0.4.12'], + packages=find_packages(), +) diff --git a/strhub/__init__.py b/strhub/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/strhub/data/__init__.py b/strhub/data/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/strhub/data/aa_overrides.py b/strhub/data/aa_overrides.py new file mode 100644 index 00000000..524afc23 --- /dev/null +++ b/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 _MAX_LEVEL, _randomly_negate, LEVEL_TO_ARG, NAME_TO_OP, 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 / _MAX_LEVEL) * 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.), + '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/strhub/data/augment.py b/strhub/data/augment.py new file mode 100644 index 00000000..160aa653 --- /dev/null +++ b/strhub/data/augment.py @@ -0,0 +1,111 @@ +# 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 ImageFilter, Image +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._MAX_LEVEL + 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, transforms=_RAND_TRANSFORMS) + # Supply weights to disable replacement in random selection (i.e. avoid applying the same op twice) + choice_weights = [1. / len(ra_ops) for _ in range(len(ra_ops))] + return auto_augment.RandAugment(ra_ops, num_layers, choice_weights) diff --git a/strhub/data/dataset.py b/strhub/data/dataset.py new file mode 100644 index 00000000..e36bc31a --- /dev/null +++ b/strhub/data/dataset.py @@ -0,0 +1,126 @@ +# 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 Dataset, ConcatDataset + +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.joinpath('**/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, + normalize_unicode: bool = True, unlabelled: bool = False, transform: Optional[Callable] = None, + num_workers: int = 1): + self.env = lmdb.open(root, max_readers=num_workers, max_spare_txns=num_workers, + readonly=True, create=False, readahead=False, meminit=False, lock=False) + self.max_label_len = max_label_len + self.min_image_dim = min_image_dim + self.normalize_unicode = normalize_unicode + self.unlabelled = unlabelled + self.transform = transform + self.labels = [] + self.filtered_index_list = [] + self.num_samples = self._preprocess_labels(charset) + + def __del__(self): + self.env.close() + + def _preprocess_labels(self, charset): + charset_adapter = CharsetAdapter(charset) + with self.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() + # There shouldn't be any whitespace in the labels but try to remove them for good measure + label = ''.join(label.split()) + # Normalize unicode composites (if any) and convert to compatible ASCII characters + if self.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) > self.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 self.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/strhub/data/module.py b/strhub/data/module.py new file mode 100644 index 00000000..8bf3473b --- /dev/null +++ b/strhub/data/module.py @@ -0,0 +1,102 @@ +# 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 Optional, Callable, Sequence + +import pytorch_lightning as pl +from torch.utils.data import DataLoader +from torchvision import transforms as T + +from .augment import rand_augment_transform +from .dataset import build_tree_dataset, LmdbDataset + + +class SceneTextDataModule(pl.LightningDataModule): + TEST_ABINET = ('IIIT5k', 'SVT', 'IC13_857', 'IC15_1811', 'SVTP', 'CUTE80') + TEST_TRBA = ('IIIT5k', 'SVT', 'IC13_1015', 'IC15_2077', 'SVTP', 'CUTE80') + TEST_NEW = ('ArT', 'COCOv1.4', 'Uber') + TEST_ALL = tuple(set(TEST_ABINET + TEST_TRBA + 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, + 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.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: + 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, + transform=transform, num_workers=self.num_workers) + 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, + transform=transform, num_workers=self.num_workers) + return self._val_dataset + + def train_dataloader(self): + return DataLoader(self.train_dataset, batch_size=self.batch_size, + num_workers=self.num_workers, shuffle=True, + 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, + 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.joinpath(s)), self.charset_test, self.max_label_length, + 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/strhub/data/utils.py b/strhub/data/utils.py new file mode 100644 index 00000000..7fb77bd7 --- /dev/null +++ b/strhub/data/utils.py @@ -0,0 +1,145 @@ +# 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 List, 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 = 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 = re.sub(self.unsupported, '', 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]) -> str: + return ''.join([self._itos[i] for i in token_ids]) + + @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) -> tuple[list[str], list[Tensor]]: + """Decode a batch of token distributions. + + Args: + token_dists: softmax probabilities over the token distribution. Shape: N, L, C + + 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 + probs, ids = self._filter(probs, ids) + tokens = self._ids2tok(ids) + batch_tokens.append(tokens) + batch_probs.append(probs) + return batch_tokens, batch_probs + + +class Tokenizer(BaseTokenizer): + BOS = '' + EOS = '' + PAD = '' + + 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 = '' + + 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/strhub/models/__init__.py b/strhub/models/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/strhub/models/abinet/LICENSE b/strhub/models/abinet/LICENSE new file mode 100644 index 00000000..2f1d4adb --- /dev/null +++ b/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/strhub/models/abinet/__init__.py b/strhub/models/abinet/__init__.py new file mode 100644 index 00000000..60481103 --- /dev/null +++ b/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/strhub/models/abinet/attention.py b/strhub/models/abinet/attention.py new file mode 100644 index 00000000..eab942cf --- /dev/null +++ b/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/strhub/models/abinet/backbone.py b/strhub/models/abinet/backbone.py new file mode 100644 index 00000000..debcabd7 --- /dev/null +++ b/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/strhub/models/abinet/model.py b/strhub/models/abinet/model.py new file mode 100644 index 00000000..cc0cd143 --- /dev/null +++ b/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/strhub/models/abinet/model_abinet_iter.py b/strhub/models/abinet/model_abinet_iter.py new file mode 100644 index 00000000..1a8523ff --- /dev/null +++ b/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/strhub/models/abinet/model_alignment.py b/strhub/models/abinet/model_alignment.py new file mode 100644 index 00000000..9ccfa95e --- /dev/null +++ b/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/strhub/models/abinet/model_language.py b/strhub/models/abinet/model_language.py new file mode 100644 index 00000000..659d4465 --- /dev/null +++ b/strhub/models/abinet/model_language.py @@ -0,0 +1,50 @@ +import torch.nn as nn +from torch.nn import TransformerDecoder + +from .model import Model +from .transformer import PositionalEncoding, TransformerDecoderLayer + + +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/strhub/models/abinet/model_vision.py b/strhub/models/abinet/model_vision.py new file mode 100644 index 00000000..3190677c --- /dev/null +++ b/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, *args): + 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/strhub/models/abinet/resnet.py b/strhub/models/abinet/resnet.py new file mode 100644 index 00000000..59bf3889 --- /dev/null +++ b/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/strhub/models/abinet/system.py b/strhub/models/abinet/system.py new file mode 100644 index 00000000..ed6eea03 --- /dev/null +++ b/strhub/models/abinet/system.py @@ -0,0 +1,170 @@ +# 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 + +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 add_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.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. + return self.global_step < (8 / 18) * self.num_training_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 add_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.devices) * self.batch_size / 256. + 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, math.ceil(self.num_training_steps / agb), + 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: 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, dataloader_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/strhub/models/abinet/transformer.py b/strhub/models/abinet/transformer.py new file mode 100644 index 00000000..a920805d --- /dev/null +++ b/strhub/models/abinet/transformer.py @@ -0,0 +1,143 @@ +import math + +import torch +import torch.nn.functional as F +from torch import nn +from torch.nn.modules.transformer import _get_activation_fn + + +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/strhub/models/base.py b/strhub/models/base.py new file mode 100644 index 00000000..4bdd4f03 --- /dev/null +++ b/strhub/models/base.py @@ -0,0 +1,219 @@ +# 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 + +import pytorch_lightning as pl +import torch +import torch.nn.functional as F +from nltk import edit_distance +from pytorch_lightning.utilities.types import EPOCH_OUTPUT, STEP_OUTPUT +from timm.optim import create_optimizer_v2 +from torch import Tensor +from torch.optim import Optimizer +from torch.optim.lr_scheduler import OneCycleLR + +from strhub.data.utils import CharsetAdapter, CTCTokenizer, Tokenizer, BaseTokenizer + + +@dataclass +class BatchResult: + num_samples: int + correct: int + ned: float + confidence: float + label_length: int + loss: Tensor + loss_numel: int + + +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._num_training_steps = None + + @abstractmethod + def forward(self, images: Tensor, max_length: int = None) -> Tensor: + """Inference + + Args: + images: Batch of images. Shape: N, C, 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, C, 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 + + @property + def num_training_steps(self) -> int: + """Total training steps inferred from datamodule and devices.""" + if self._num_training_steps is None: + if self.trainer.max_steps is not None: + max_steps = self.trainer.max_steps + else: + loader = self.train_dataloader() + # We have no access to the actual DistributedSampler instance, but the default is drop_last == False + samples_per_replica = math.ceil(len(loader.dataset) / self.trainer.devices) + epoch_steps = samples_per_replica / loader.batch_size + epoch_steps = int(epoch_steps) if loader.drop_last else math.ceil(epoch_steps) + limit = self.trainer.limit_train_batches + epoch_steps = min(epoch_steps, limit) if isinstance(limit, int) else int(limit * epoch_steps) + max_steps = epoch_steps * self.trainer.max_epochs + self._num_training_steps = max_steps + return self._num_training_steps + + 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.devices) * self.batch_size / 256. + lr = lr_scale * self.lr + optim = create_optimizer_v2(self, 'adamw', lr, self.weight_decay) + sched = OneCycleLR(optim, lr, math.ceil(self.num_training_steps / agb), 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, optimizer_idx: int): + 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]: + 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]: + return self._eval_step(batch, True) + + def validation_epoch_end(self, outputs: EPOCH_OUTPUT) -> None: + acc, ned, loss = self._aggregate_results(outputs) + 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, ABC): + + 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, ABC): + + 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/strhub/models/crnn/LICENSE b/strhub/models/crnn/LICENSE new file mode 100644 index 00000000..f98687be --- /dev/null +++ b/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/strhub/models/crnn/__init__.py b/strhub/models/crnn/__init__.py new file mode 100644 index 00000000..a4535947 --- /dev/null +++ b/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/strhub/models/crnn/model.py b/strhub/models/crnn/model.py new file mode 100644 index 00000000..1a71845f --- /dev/null +++ b/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('conv{0}'.format(i), + nn.Conv2d(nIn, nOut, ks[i], ss[i], ps[i], bias=not batchNormalization)) + if batchNormalization: + cnn.add_module('batchnorm{0}'.format(i), nn.BatchNorm2d(nOut)) + if leaky_relu: + cnn.add_module('relu{0}'.format(i), + nn.LeakyReLU(0.2, inplace=True)) + else: + cnn.add_module('relu{0}'.format(i), nn.ReLU(True)) + + convRelu(0) + cnn.add_module('pooling{0}'.format(0), nn.MaxPool2d(2, 2)) # 64x16x64 + convRelu(1) + cnn.add_module('pooling{0}'.format(1), nn.MaxPool2d(2, 2)) # 128x8x32 + convRelu(2, True) + convRelu(3) + cnn.add_module('pooling{0}'.format(2), + nn.MaxPool2d((2, 2), (2, 1), (0, 1))) # 256x4x16 + convRelu(4, True) + convRelu(5) + cnn.add_module('pooling{0}'.format(3), + 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/strhub/models/crnn/system.py b/strhub/models/crnn/system.py new file mode 100644 index 00000000..ad40d0f0 --- /dev/null +++ b/strhub/models/crnn/system.py @@ -0,0 +1,43 @@ +# 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 Sequence + +from pytorch_lightning.utilities.types import STEP_OUTPUT +from torch import Tensor + +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: 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/strhub/models/modules.py b/strhub/models/modules.py new file mode 100644 index 00000000..a89d05f6 --- /dev/null +++ b/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/strhub/models/parseq/__init__.py b/strhub/models/parseq/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/strhub/models/parseq/modules.py b/strhub/models/parseq/modules.py new file mode 100644 index 00000000..0038381d --- /dev/null +++ b/strhub/models/parseq/modules.py @@ -0,0 +1,133 @@ +# 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 nn as nn, Tensor +from torch.nn import functional as F +from torch.nn.modules import transformer + +from timm.models.vision_transformer import VisionTransformer, PatchEmbed + + +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=None, content_mask=None, content_key_padding_mask=None, + update_content=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=None, content_mask=None, content_key_padding_mask=None): + for mod in self.layers: + last = mod == 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., + qkv_bias=True, drop_rate=0., attn_drop_rate=0., drop_path_rate=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) + # Only allocate position embeddings for the image tokens (none for cls nor dist) + self.pos_embed = nn.Parameter(torch.zeros(1, self.patch_embed.num_patches, embed_dim)) + nn.init.trunc_normal_(self.pos_embed, std=.02) + # Delete unused modules + del self.pre_logits, self.head, self.head_dist, self.cls_token, self.dist_token + + def forward(self, x): + # Essentially forward_features() but returns all tokens + x = self.patch_embed(x) + x = self.pos_drop(x + self.pos_embed) + x = self.blocks(x) + x = self.norm(x) + return 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/strhub/models/parseq/system.py b/strhub/models/parseq/system.py new file mode 100644 index 00000000..9577df7c --- /dev/null +++ b/strhub/models/parseq/system.py @@ -0,0 +1,258 @@ +# 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 functools import partial +from itertools import permutations +from typing import Sequence, Any + +import numpy as np +import torch +import torch.nn as nn +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 +from strhub.models.utils import init_weights +from .modules import DecoderLayer, Decoder, Encoder, TokenEmbedding + + +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.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)) + + # 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 + + # We don't predict nor + self.head = nn.Linear(embed_dim, len(self.tokenizer) - 2) + self.text_embed = TokenEmbedding(len(self.tokenizer), 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=.02) + + @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=None, tgt_padding_mask=None, tgt_query=None, + tgt_query_mask=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, images: Tensor, max_length: int = None) -> Tensor: + testing = max_length is None + max_length = self.max_label_length if testing 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.full((num_steps, num_steps), float('-inf'), device=self.device), 1) + + if self.decode_ar: + tgt_in = torch.full((bs, num_steps), self.pad_id, dtype=torch.long, device=self.device) + tgt_in[:, 0] = self.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 == self.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), self.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), self.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) + tgt_padding_mask = ((tgt_in == self.eos_id).cumsum(-1) > 0) # mask tokens beyond the first EOS token. + tgt_out = self.decode(tgt_in, memory, tgt_mask, tgt_padding_mask, + tgt_query=pos_queries, tgt_query_mask=query_mask[:, :tgt_in.shape[1]]) + logits = self.head(tgt_out) + + return logits + + 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 + 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), device=self.device) + for i in range(sz): + query_idx = perm[i] + masked_keys = perm[i + 1:] + mask[query_idx, masked_keys] = float('-inf') + content_mask = mask[:-1, :-1].clone() + mask[torch.eye(sz, dtype=torch.bool, device=self.device)] = float('-inf') # 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.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.decode(tgt_in, memory, tgt_mask, tgt_padding_mask, tgt_query_mask=query_mask) + logits = self.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/strhub/models/trba/__init__.py b/strhub/models/trba/__init__.py new file mode 100644 index 00000000..a574a8af --- /dev/null +++ b/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/strhub/models/trba/feature_extraction.py b/strhub/models/trba/feature_extraction.py new file mode 100644 index 00000000..17646e3f --- /dev/null +++ b/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/strhub/models/trba/model.py b/strhub/models/trba/model.py new file mode 100644 index 00000000..41161a4d --- /dev/null +++ b/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/strhub/models/trba/prediction.py b/strhub/models/trba/prediction.py new file mode 100644 index 00000000..5609398a --- /dev/null +++ b/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/strhub/models/trba/system.py b/strhub/models/trba/system.py new file mode 100644 index 00000000..655b4390 --- /dev/null +++ b/strhub/models/trba/system.py @@ -0,0 +1,87 @@ +# 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 Sequence, Any + +import torch +import torch.nn.functional as F +from pytorch_lightning.utilities.types import STEP_OUTPUT +from timm.models.helpers import named_apply +from torch import Tensor + +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: 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: 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/strhub/models/trba/transformation.py b/strhub/models/trba/transformation.py new file mode 100644 index 00000000..960419d1 --- /dev/null +++ b/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/strhub/models/utils.py b/strhub/models/utils.py new file mode 100644 index 00000000..2e05d776 --- /dev/null +++ b/strhub/models/utils.py @@ -0,0 +1,78 @@ +import os.path +from typing import Sequence + +import torch +from pytorch_lightning.core.saving import ModelIO +from torch import nn + + +def _load_pl_checkpoint(checkpoint, **kwargs): + hparams = checkpoint[ModelIO.CHECKPOINT_HYPER_PARAMS_KEY] + hparams.update(kwargs) + name = hparams['name'] + if name.startswith('abinet'): + from .abinet.system import ABINet as ModelClass + elif name.startswith('crnn'): + from .crnn.system import CRNN as ModelClass + elif name.startswith('parseq'): + from .parseq.system import PARSeq as ModelClass + elif name.startswith('trba'): + from .trba.system import TRBA as ModelClass + elif name.startswith('trbc'): + from .trba.system import TRBC as ModelClass + elif name.startswith('vitstr'): + from .vitstr.system import ViTSTR as ModelClass + else: + raise RuntimeError('Unable to load correct model class') + model = ModelClass._load_model_state(checkpoint, strict=True, **kwargs) + return model + + +def _load_torch_model(checkpoint_path, checkpoint, **kwargs): + import hubconf + name = os.path.basename(checkpoint_path).split('-')[0] + model_factory = getattr(hubconf, name) + model = model_factory(**kwargs) + model.load_state_dict(checkpoint) + return model + + +def load_from_checkpoint(checkpoint_path: str, **kwargs): + checkpoint = torch.load(checkpoint_path, map_location='cpu') + try: + model = _load_pl_checkpoint(checkpoint, **kwargs) + except KeyError: + model = _load_torch_model(checkpoint_path, checkpoint, **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=.02) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.trunc_normal_(module.weight, std=.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/strhub/models/vitstr/__init__.py b/strhub/models/vitstr/__init__.py new file mode 100644 index 00000000..19e98567 --- /dev/null +++ b/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/strhub/models/vitstr/model.py b/strhub/models/vitstr/model.py new file mode 100644 index 00000000..9543d2c5 --- /dev/null +++ b/strhub/models/vitstr/model.py @@ -0,0 +1,53 @@ +''' +Implementation of ViTSTR based on timm VisionTransformer. + +TODO: +1) distilled deit backbone +2) base deit backbone + +Copyright 2021 Rowel Atienza +''' + +import torch +import torch.nn as nn + +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 __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def reset_classifier(self, num_classes): + self.num_classes = num_classes + self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() + + def forward_features(self, x): + B = x.shape[0] + x = self.patch_embed(x) + + cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks + x = torch.cat((cls_tokens, x), dim=1) + x = x + self.pos_embed + x = self.pos_drop(x) + + for blk in self.blocks: + x = blk(x) + + x = self.norm(x) + return x + + def forward(self, x, seqlen=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/strhub/models/vitstr/system.py b/strhub/models/vitstr/system.py new file mode 100644 index 00000000..c72b312b --- /dev/null +++ b/strhub/models/vitstr/system.py @@ -0,0 +1,58 @@ +# 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 Sequence, Any + +import torch +from pytorch_lightning.utilities.types import STEP_OUTPUT +from torch import Tensor + +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: 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/test.py b/test.py new file mode 100755 index 00000000..8a8d32e9 --- /dev/null +++ b/test.py @@ -0,0 +1,129 @@ +#!/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 + +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) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('checkpoint', help='Model checkpoint') + 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) + model.freeze() # disable autograd + hp = model.hparams + datamodule = SceneTextDataModule('data', '_unused_', hp.img_size, hp.max_label_length, hp.charset_train, hp.charset_test, + args.batch_size, args.num_workers, False, args.rotation) + + test_set = SceneTextDataModule.TEST_ABINET + SceneTextDataModule.TEST_TRBA + 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 = { + 'ABINet': SceneTextDataModule.TEST_ABINET, + 'TRBA': SceneTextDataModule.TEST_TRBA + } + 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/tools/art_converter.py b/tools/art_converter.py new file mode 100755 index 00000000..f61e0b54 --- /dev/null +++ b/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/tools/case_sensitive_str_datasets_converter.py b/tools/case_sensitive_str_datasets_converter.py new file mode 100755 index 00000000..7ce7c0dd --- /dev/null +++ b/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/tools/coco_2_converter.py b/tools/coco_2_converter.py new file mode 100755 index 00000000..2a2d614c --- /dev/null +++ b/tools/coco_2_converter.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +import argparse +import html +import math +import os +import os.path as osp +from functools import partial + +import mmcv +from PIL import Image +from mmocr.utils.fileio import list_to_file + + +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 multi-processing + 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/tools/coco_text_converter.py b/tools/coco_text_converter.py new file mode 100755 index 00000000..09d130db --- /dev/null +++ b/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/tools/create_lmdb_dataset.py b/tools/create_lmdb_dataset.py new file mode 100755 index 00000000..82dd3f4d --- /dev/null +++ b/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/tools/filter_lmdb.py b/tools/filter_lmdb.py new file mode 100755 index 00000000..0d1b4451 --- /dev/null +++ b/tools/filter_lmdb.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +import io +import os +from argparse import ArgumentParser + +import numpy as np +import lmdb +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/tools/lsvt_converter.py b/tools/lsvt_converter.py new file mode 100755 index 00000000..e16c10bd --- /dev/null +++ b/tools/lsvt_converter.py @@ -0,0 +1,107 @@ +#!/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 PIL import Image +from mmocr.utils.fileio import list_to_file + + +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 multi-processing + 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/tools/mlt19_converter.py b/tools/mlt19_converter.py new file mode 100755 index 00000000..665d497f --- /dev/null +++ b/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/tools/openvino_converter.py b/tools/openvino_converter.py new file mode 100755 index 00000000..333a12b6 --- /dev/null +++ b/tools/openvino_converter.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +import math +import os +import os.path as osp +from argparse import ArgumentParser +from functools import partial + +import mmcv +from PIL import Image + +from mmocr.utils.fileio import list_to_file + + +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 multi-processing + 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/tools/test_abinet_lm_acc.py b/tools/test_abinet_lm_acc.py new file mode 100755 index 00000000..00c26665 --- /dev/null +++ b/tools/test_abinet_lm_acc.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +import argparse +import string +import sys + +import torch +import torch.nn.functional as F +from torch import Tensor +from torch.nn.utils.rnn import pad_sequence + +from tqdm import tqdm + +from strhub.data.module import SceneTextDataModule +from strhub.models.abinet.system import ABINet + +sys.path.insert(0, '.') +from hubconf import _get_config +from test import Result, print_results_table + + +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('--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('data', '_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_TRBA + 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 = { + 'TRBA': SceneTextDataModule.TEST_TRBA + } + 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/tools/textocr_converter.py b/tools/textocr_converter.py new file mode 100755 index 00000000..6a9d7150 --- /dev/null +++ b/tools/textocr_converter.py @@ -0,0 +1,142 @@ +#!/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 PIL import Image +from mmocr.utils.fileio import list_to_file + + +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 multi-processing + 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/train.py b/train.py new file mode 100755 index 00000000..8a7fb621 --- /dev/null +++ b/train.py @@ -0,0 +1,73 @@ +#!/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. + +from pathlib import Path + +import hydra +from omegaconf import DictConfig, open_dict +from pytorch_lightning import Trainer +from pytorch_lightning.callbacks import ModelCheckpoint, StochasticWeightAveraging +from pytorch_lightning.loggers import TensorBoardLogger +from pytorch_lightning.plugins import DDPPlugin + +from strhub.data.module import SceneTextDataModule +from strhub.models.base import BaseSystem + + +@hydra.main(config_path='configs', config_name='main') +def main(config: DictConfig): + trainer_plugins = None + with open_dict(config): + # Resolve absolute path to data.root_dir + config.data.root_dir = hydra.utils.to_absolute_path(config.data.root_dir) + if config.trainer.get('resume_from_checkpoint', None) is not None: + config.trainer.resume_from_checkpoint = hydra.utils.to_absolute_path(config.trainer.resume_from_checkpoint) + # Special handling for GPU-affected config + gpus = config.trainer.get('gpus', 0) + if gpus: + # Use mixed-precision training + config.trainer.precision = 16 + if gpus > 1: + # Use DDP + config.trainer.accelerator = 'ddp' + # DDP optimizations + trainer_plugins = DDPPlugin(find_unused_parameters=False, gradient_as_bucket_view=True) + # Scale steps-based config + config.trainer.val_check_interval //= gpus + if config.trainer.get('max_steps', 0): + config.trainer.max_steps //= gpus + + # 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) + model.summarize(max_depth=1 if config.model.name.startswith('parseq') else 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 = StochasticWeightAveraging(swa_epoch_start=0.75) + cwd = Path.cwd() + trainer: Trainer = hydra.utils.instantiate(config.trainer, logger=TensorBoardLogger(str(cwd.parent), '', cwd.name), + plugins=trainer_plugins, weights_summary=None, + callbacks=[checkpoint, swa]) + trainer.fit(model, datamodule=datamodule) + + +if __name__ == '__main__': + main() diff --git a/tune.py b/tune.py new file mode 100755 index 00000000..222ba868 --- /dev/null +++ b/tune.py @@ -0,0 +1,194 @@ +#!/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 omegaconf import DictConfig, open_dict +from pytorch_lightning import Trainer, LightningModule +from pytorch_lightning.loggers import TensorBoardLogger +from ray import tune +from ray.tune import CLIReporter +from ray.tune.integration.pytorch_lightning import TuneReportCheckpointCallback +from ray.tune.ray_trial_executor import RayTrialExecutor +from ray.tune.schedulers import MedianStoppingRule +from ray.tune.suggest.ax import AxSearch + +from strhub.data.module import SceneTextDataModule +from strhub.models.base import BaseSystem +from tests.test_tune import test_train + +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.): + 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): + self._checkpoint._handle(trainer, pl_module) + # Prune older checkpoints + for old in sorted(Path(tune.get_trial_dir()).glob('checkpoint_epoch=*-step=*'), key=os.path.getmtime)[:-1]: + log.info(f'Deleting old checkpoint: {old}') + shutil.rmtree(old) + self._report._handle(trainer, pl_module) + + +def train(hparams, config, checkpoint_dir=None): + with open_dict(config): + config.model.lr = hparams['lr'] + # config.model.weight_decay = hparams['wd'] + if checkpoint_dir is not None: + config.trainer.resume_from_checkpoint = os.path.join(checkpoint_dir, 'checkpoint') + + 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' + }) + trainer: Trainer = hydra.utils.instantiate(config.trainer, progress_bar_refresh_rate=0, checkpoint_callback=False, + logger=TensorBoardLogger(save_dir=tune.get_trial_dir(), name='', + version='.'), + callbacks=[tune_callback]) + trainer.fit(model, datamodule=datamodule) + + +@hydra.main(config_path='configs', config_name='tune') +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 + # We handle NaN here to terminate trials cleanly + config.trainer.terminate_on_nan = False + # Resolve absolute path to data.root_dir + config.data.root_dir = hydra.utils.to_absolute_path(config.data.root_dir) + + test = config.get('test', False) + tune_config = config.get('tune', {}) + lr = tune_config.get('lr', {}) + # wd = tune_config.get('wd', {}) + hparams = { + 'lr': tune.loguniform(lr.get('min', 1e-4), lr.get('max', 2e-3)), + # 'wd': tune.loguniform(wd.get('min', 1e-4), wd.get('max', 1e-1)), + } + + steps_per_epoch = int(3e6) if test else 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']) + + train_fn = test_train if test else train + analysis = tune.run( + tune.with_parameters(train_fn, config=config), + name='trials', # required. otherwise some of Ray's checks will fail. + metric='NED', + mode='max', + stop=MetricTracker('NED', max_t), + config=hparams, + resources_per_trial={ + 'cpu': 1, + 'gpu': tune_config.get('gpus_per_trial', 1) + }, + num_samples=tune_config.get('num_samples', 10), + local_dir=str(Path.cwd()), + search_alg=search_alg, + scheduler=scheduler, + progress_reporter=reporter, + resume=tune_config.get('resume', False), + trial_executor=RayTrialExecutor(result_buffer_length=0) # disable result buffering + ) + + print('Best hyperparameters found were: ', analysis.best_config) + + +if __name__ == '__main__': + main()