From f066814a238ef65140973358da5d11d0e183bd04 Mon Sep 17 00:00:00 2001
From: tuanlv
Date: Fri, 5 Jan 2024 16:20:38 +0700
Subject: [PATCH] modify dockerfile: install from sdskvu/external/sdsvocr
---
cope2n-ai-fi/Dockerfile | 7 +-
cope2n-ai-fi/api/sdsap_sbt/prediction_sbt.py | 15 +-
cope2n-ai-fi/configs/sdsap_sbt/configs.py | 4 +-
cope2n-ai-fi/modules/ocr_engine/.gitignore | 6 -
cope2n-ai-fi/modules/ocr_engine/README.md | 47 -
cope2n-ai-fi/modules/ocr_engine/TODO.todo | 10 -
cope2n-ai-fi/modules/ocr_engine/__init__.py | 19 -
.../externals/sdsv_dewarp/.gitignore | 9 -
.../externals/sdsv_dewarp/README.md | 29 -
.../externals/sdsv_dewarp/config/cls.yaml | 3 -
.../externals/sdsv_dewarp/config/det.yaml | 8 -
.../externals/sdsv_dewarp/requirements.txt | 7 -
.../sdsv_dewarp/sdsv_dewarp.egg-info/PKG-INFO | 45 -
.../sdsv_dewarp.egg-info/SOURCES.txt | 15 -
.../sdsv_dewarp.egg-info/dependency_links.txt | 1 -
.../sdsv_dewarp.egg-info/not-zip-safe | 1 -
.../sdsv_dewarp.egg-info/requires.txt | 6 -
.../sdsv_dewarp.egg-info/top_level.txt | 1 -
.../sdsv_dewarp/sdsv_dewarp/__init__.py | 0
.../externals/sdsv_dewarp/sdsv_dewarp/api.py | 200 ----
.../sdsv_dewarp/sdsv_dewarp/config.py | 41 -
.../sdsv_dewarp/sdsv_dewarp/factory.py | 75 --
.../sdsv_dewarp/sdsv_dewarp/models.py | 73 --
.../sdsv_dewarp/sdsv_dewarp/utils.py | 212 ----
.../sdsv_dewarp/sdsv_dewarp/version.py | 1 -
.../ocr_engine/externals/sdsv_dewarp/setup.py | 187 ----
.../ocr_engine/externals/sdsv_dewarp/test.py | 47 -
.../ocr_engine/externals/sdsvtd/.gitignore | 6 -
.../ocr_engine/externals/sdsvtd/LICENSE | 674 -------------
.../ocr_engine/externals/sdsvtd/README.md | 76 --
.../externals/sdsvtd/requirements.txt | 2 -
.../externals/sdsvtd/sdsvtd/__init__.py | 3 -
.../ocr_engine/externals/sdsvtd/sdsvtd/api.py | 35 -
.../externals/sdsvtd/sdsvtd/backbone.py | 395 --------
.../externals/sdsvtd/sdsvtd/bbox_head.py | 288 ------
.../externals/sdsvtd/sdsvtd/factory.py | 75 --
.../externals/sdsvtd/sdsvtd/model.py | 151 ---
.../externals/sdsvtd/sdsvtd/neck.py | 140 ---
.../externals/sdsvtd/sdsvtd/priors.py | 225 -----
.../externals/sdsvtd/sdsvtd/transform.py | 81 --
.../externals/sdsvtd/sdsvtd/version.py | 1 -
.../ocr_engine/externals/sdsvtd/setup.py | 186 ----
.../ocr_engine/externals/sdsvtr/.gitignore | 6 -
.../ocr_engine/externals/sdsvtr/LICENSE | 674 -------------
.../ocr_engine/externals/sdsvtr/README.md | 76 --
.../externals/sdsvtr/requirements.txt | 3 -
.../externals/sdsvtr/sdsvtr/__init__.py | 3 -
.../ocr_engine/externals/sdsvtr/sdsvtr/api.py | 106 --
.../externals/sdsvtr/sdsvtr/backbone.py | 159 ---
.../externals/sdsvtr/sdsvtr/conv.py | 173 ----
.../externals/sdsvtr/sdsvtr/converter.py | 152 ---
.../externals/sdsvtr/sdsvtr/decoder.py | 278 ------
.../externals/sdsvtr/sdsvtr/encoder.py | 317 ------
.../externals/sdsvtr/sdsvtr/factory.py | 57 --
.../externals/sdsvtr/sdsvtr/fp16_utils.py | 78 --
.../externals/sdsvtr/sdsvtr/transform.py | 33 -
.../externals/sdsvtr/sdsvtr/version.py | 1 -
.../ocr_engine/externals/sdsvtr/setup.py | 187 ----
.../ocr_engine/externals/sdsvtr/test.py | 12 -
.../modules/ocr_engine/requirements.txt | 82 --
cope2n-ai-fi/modules/ocr_engine/run.py | 200 ----
.../modules/ocr_engine/scripts/run_deskew.sh | 9 -
.../modules/ocr_engine/scripts/run_ocr.sh | 49 -
cope2n-ai-fi/modules/ocr_engine/settings.yml | 36 -
cope2n-ai-fi/modules/ocr_engine/src/dto.py | 534 -----------
cope2n-ai-fi/modules/ocr_engine/src/ocr.py | 258 -----
cope2n-ai-fi/modules/ocr_engine/src/utils.py | 369 -------
.../modules/ocr_engine/src/word_formation.py | 903 ------------------
docker-compose-dev.yml | 9 +-
69 files changed, 14 insertions(+), 8157 deletions(-)
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/.gitignore
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/README.md
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/TODO.todo
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/__init__.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/.gitignore
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/README.md
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/config/cls.yaml
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/config/det.yaml
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/requirements.txt
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/PKG-INFO
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/SOURCES.txt
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/dependency_links.txt
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/not-zip-safe
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/requires.txt
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/top_level.txt
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/__init__.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/api.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/config.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/factory.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/models.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/utils.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/version.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/setup.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/test.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/.gitignore
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/LICENSE
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/README.md
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/requirements.txt
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/__init__.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/api.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/backbone.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/bbox_head.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/factory.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/model.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/neck.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/priors.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/transform.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/version.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/setup.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/.gitignore
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/LICENSE
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/README.md
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/requirements.txt
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/__init__.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/api.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/backbone.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/conv.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/converter.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/decoder.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/encoder.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/factory.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/fp16_utils.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/transform.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/version.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/setup.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/test.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/requirements.txt
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/run.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/scripts/run_deskew.sh
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/scripts/run_ocr.sh
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/settings.yml
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/src/dto.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/src/ocr.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/src/utils.py
delete mode 100755 cope2n-ai-fi/modules/ocr_engine/src/word_formation.py
diff --git a/cope2n-ai-fi/Dockerfile b/cope2n-ai-fi/Dockerfile
index 13ba941..2a1f54d 100755
--- a/cope2n-ai-fi/Dockerfile
+++ b/cope2n-ai-fi/Dockerfile
@@ -22,9 +22,10 @@ RUN python -m pip install 'git+https://github.com/facebookresearch/detectron2.gi
# Install SDSV packages
COPY . /workspace/cope2n-ai-fi
-RUN cd /workspace/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp && pip3 install -v -e . --no-cache-dir
-RUN cd /workspace/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd && pip3 install -v -e . --no-cache-dir
-RUN cd /workspace/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr && pip3 install -v -e . --no-cache-dir
+RUN cd /workspace/cope2n-ai-fi/modules/sdsvkvu/sdsvkvu/externals/sdsvocr/externals/sdsv_dewarp && pip3 install -v -e . --no-cache-dir
+RUN cd /workspace/cope2n-ai-fi/modules/sdsvkvu/sdsvkvu/externals/sdsvocr/externals/sdsvtd && pip3 install -v -e . --no-cache-dir
+RUN cd /workspace/cope2n-ai-fi/modules/sdsvkvu/sdsvkvu/externals/sdsvocr/externals/sdsvtr && pip3 install -v -e . --no-cache-dir
+
# COPY ./modules/sdsvkvu/sdsvkvu/externals/sdsvocr/externals/sdsv_dewarp /tmp/sdsv_dewarp
# RUN cd /tmp/sdsv_dewarp && pip install -v -e . --no-cache-dir
diff --git a/cope2n-ai-fi/api/sdsap_sbt/prediction_sbt.py b/cope2n-ai-fi/api/sdsap_sbt/prediction_sbt.py
index 7039c2b..49038d9 100755
--- a/cope2n-ai-fi/api/sdsap_sbt/prediction_sbt.py
+++ b/cope2n-ai-fi/api/sdsap_sbt/prediction_sbt.py
@@ -12,17 +12,8 @@ sys.path.append(cur_dir)
nltk.data.path.append(os.path.join((os.getcwd() + '/nltk_data')))
from modules.sdsvkvu import load_engine, process_img
-from modules.ocr_engine import OcrEngine
from configs.sdsap_sbt import device, ocr_cfg, kvu_cfg
-
-def load_ocr_engine(opt) -> OcrEngine:
- print("[INFO] Loading engine...")
- engine = OcrEngine(**opt)
- print("[INFO] Engine loaded")
- return engine
-
-
print("OCR engine configfs: \n", ocr_cfg)
print("KVU configfs: \n", kvu_cfg)
@@ -43,13 +34,13 @@ def sbt_predict(image_url, engine) -> None:
save_dir = "./tmp_results"
# image_path = os.path.join(save_dir, f"{image_url}.jpg")
+ os.makedirs(save_dir, exist_ok = True)
tmp_image_path = os.path.join(save_dir, f"{uuid.uuid4()}.jpg")
- cv2.imwrite(tmp_image_path, img)
-
+ cv2.imwrite(tmp_image_path, img)
outputs = process_img(img_path=tmp_image_path,
save_dir=save_dir,
engine=engine,
- export_all=False,
+ export_all=False, # False
option=option)
os.remove(tmp_image_path)
return outputs
diff --git a/cope2n-ai-fi/configs/sdsap_sbt/configs.py b/cope2n-ai-fi/configs/sdsap_sbt/configs.py
index 3a41be0..402c836 100755
--- a/cope2n-ai-fi/configs/sdsap_sbt/configs.py
+++ b/cope2n-ai-fi/configs/sdsap_sbt/configs.py
@@ -12,11 +12,11 @@ ocr_engine = {
"deskew": {
"enable": True,
"text_detector": {
- "config": "/workspace/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/config/det.yaml",
+ "config": "/workspace/cope2n-ai-fi/weights/models/ocr_engine/sdsv_dewarp/det.yaml",
"weight": "/workspace/cope2n-ai-fi/weights/models/ocr_engine/sdsv_dewarp/ch_PP-OCRv3_det_infer"
},
"text_cls": {
- "config": "/workspace/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/config/cls.yaml",
+ "config": "/workspace/cope2n-ai-fi/weights/models/ocr_engine/sdsv_dewarp/cls.yaml",
"weight": "/workspace/cope2n-ai-fi/weights/models/ocr_engine/sdsv_dewarp/ch_ppocr_mobile_v2.0_cls_infer"
},
"device": device
diff --git a/cope2n-ai-fi/modules/ocr_engine/.gitignore b/cope2n-ai-fi/modules/ocr_engine/.gitignore
deleted file mode 100755
index 1250e95..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-__pycache__/
-visualize/
-results/
-*.jpeg
-*.jpg
-*.png
diff --git a/cope2n-ai-fi/modules/ocr_engine/README.md b/cope2n-ai-fi/modules/ocr_engine/README.md
deleted file mode 100755
index ca1b349..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/README.md
+++ /dev/null
@@ -1,47 +0,0 @@
-# OCR Engine
-
-OCR Engine is a Python package that combines text detection and recognition models from [mmdet](https://github.com/open-mmlab/mmdetection) and [mmocr](https://github.com/open-mmlab/mmocr) to perform Optical Character Recognition (OCR) on various inputs. The package currently supports three types of input: a single image, a recursive directory, or a csv file.
-
-## Installation
-
-To install OCR Engine, clone the repository and install the required packages:
-
-```bash
-git clone git@github.com:mrlasdt/ocr-engine.git
-cd ocr-engine
-pip install -r requirements.txt
-
-```
-
-
-## Usage
-
-To use OCR Engine, simply run the `ocr_engine.py` script with the desired input type and input path. For example, to perform OCR on a single image:
-
-```css
-python ocr_engine.py --input_type image --input_path /path/to/image.jpg
-```
-
-To perform OCR on a recursive directory:
-
-```css
-python ocr_engine.py --input_type directory --input_path /path/to/directory/
-
-```
-
-To perform OCR on a csv file:
-
-
-```
-python ocr_engine.py --input_type csv --input_path /path/to/file.csv
-```
-
-OCR Engine will automatically detect and recognize text in the input and output the results in a CSV file named `ocr_results.csv`.
-
-## Contributing
-
-If you would like to contribute to OCR Engine, please fork the repository and submit a pull request. We welcome contributions of all types, including bug fixes, new features, and documentation improvements.
-
-## License
-
-OCR Engine is released under the [MIT License](https://opensource.org/licenses/MIT). See the LICENSE file for more information.
diff --git a/cope2n-ai-fi/modules/ocr_engine/TODO.todo b/cope2n-ai-fi/modules/ocr_engine/TODO.todo
deleted file mode 100755
index 34df095..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/TODO.todo
+++ /dev/null
@@ -1,10 +0,0 @@
-☐ refactor argument parser of run.py
-☐ add timer level, logging level and write_mode to argumments
-☐ add paddleocr deskew to the code
-☐ fix the deskew code to resize the image only for detecting the angle, we want to feed the original size image to the text detection pipeline so that the bounding boxes would be mapped back to the original size
-☐ ocr engine import took too long
-☐ add word level to write_mode
-☐ add word group and line
-change max_x_dist from pixel to percentage of box width
-☐ visualization: adjust fontsize dynamically
-
diff --git a/cope2n-ai-fi/modules/ocr_engine/__init__.py b/cope2n-ai-fi/modules/ocr_engine/__init__.py
deleted file mode 100755
index 433d5ff..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/__init__.py
+++ /dev/null
@@ -1,19 +0,0 @@
-# # Define package-level variables
-# __version__ = '0.0'
-
-import os
-import sys
-from pathlib import Path
-cur_dir = str(Path(__file__).parents[0])
-sys.path.append(cur_dir)
-sys.path.append(os.path.join(cur_dir, "externals"))
-
-# Import modules
-from .run import load_engine
-from .src.ocr import OcrEngine
-# from .src.word_formation import words_to_lines
-from .src.word_formation import words_to_lines_tesseract as words_to_lines
-from .src.utils import ImageReader, read_ocr_result_from_txt
-from .src.dto import Word, Line, Page, Document, Box
-# Expose package contents
-__all__ = ["OcrEngine", "Box", "Word", "Line", "Page", "Document", "words_to_lines", "ImageReader", "read_ocr_result_from_txt"]
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/.gitignore b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/.gitignore
deleted file mode 100755
index e56dbb2..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/.gitignore
+++ /dev/null
@@ -1,9 +0,0 @@
-output*
-*.pyc
-*.jpg
-check
-weights/
-workdirs/
-__pycache__*
-test_hungbnt.py
-libs*
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/README.md b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/README.md
deleted file mode 100755
index d1b9637..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/README.md
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
Dewarp
-
-
-***Feature***
-- Align document
-
-
-## I. Setup
-***Dependencies***
-- Python: 3.8
-- Torch: 1.10.2
-- CUDA: 11.6
-- transformers: 4.28.1
-### 1. Install PaddlePaddle
-```
-python -m pip install paddlepaddle-gpu==2.4.2.post116 -f https://www.paddlepaddle.org.cn/whl/linux/mkl/avx/stable.html
-```
-
-### 2. Install sdsv_dewarp
-```
-pip install -v -e .
-```
-
-
-## II. Test
-```
-python test.py --input samples --out demo/outputs --device 'cuda'
-```
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/config/cls.yaml b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/config/cls.yaml
deleted file mode 100755
index 4c4cfdc..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/config/cls.yaml
+++ /dev/null
@@ -1,3 +0,0 @@
-model_dir: /mnt/hdd4T/OCR/tuanlv/01-BasicOCR/ocr-engine-deskew/externals/sdsv_dewarp/weights/ch_ppocr_mobile_v2.0_cls_infer
-gpu_mem: 3000
-max_batch_size: 32
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/config/det.yaml b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/config/det.yaml
deleted file mode 100755
index f218ef1..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/config/det.yaml
+++ /dev/null
@@ -1,8 +0,0 @@
-model_dir: /mnt/hdd4T/OCR/tuanlv/01-BasicOCR/ocr-engine-deskew/externals/sdsv_dewarp/weights/ch_PP-OCRv3_det_infer
-gpu_mem: 3000
-det_limit_side_len: 1560
-det_limit_type: max
-det_db_unclip_ratio: 1.85
-det_db_thresh: 0.3
-det_db_box_thresh: 0.5
-det_db_score_mode: fast
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/requirements.txt b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/requirements.txt
deleted file mode 100755
index 768fde9..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/requirements.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-
-paddleocr>=2.0.1
-opencv-contrib-python
-opencv-python
-numpy
-gdown==3.13.0
-imgaug==0.4.0
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/PKG-INFO b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/PKG-INFO
deleted file mode 100755
index 634708d..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/PKG-INFO
+++ /dev/null
@@ -1,45 +0,0 @@
-Metadata-Version: 2.1
-Name: sdsv-dewarp
-Version: 1.0.0
-Summary: Dewarp document
-Home-page:
-License: Apache License 2.0
-Classifier: Development Status :: 4 - Beta
-Classifier: License :: OSI Approved :: Apache Software License
-Classifier: Operating System :: OS Independent
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.6
-Classifier: Programming Language :: Python :: 3.7
-Classifier: Programming Language :: Python :: 3.8
-Classifier: Programming Language :: Python :: 3.9
-Description-Content-Type: text/markdown
-
-
-
Dewarp
-
-
-***Feature***
-- Align document
-
-
-## I. Setup
-***Dependencies***
-- Python: 3.8
-- Torch: 1.10.2
-- CUDA: 11.6
-- transformers: 4.28.1
-### 1. Install PaddlePaddle
-```
-python -m pip install paddlepaddle-gpu==2.4.2.post116 -f https://www.paddlepaddle.org.cn/whl/linux/mkl/avx/stable.html
-```
-
-### 2. Install sdsv_dewarp
-```
-pip install -v -e .
-```
-
-
-## II. Test
-```
-python test.py --input samples --out demo/outputs --device 'cuda'
-```
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/SOURCES.txt b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/SOURCES.txt
deleted file mode 100755
index 953a123..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/SOURCES.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-README.md
-setup.py
-sdsv_dewarp/__init__.py
-sdsv_dewarp/api.py
-sdsv_dewarp/config.py
-sdsv_dewarp/factory.py
-sdsv_dewarp/models.py
-sdsv_dewarp/utils.py
-sdsv_dewarp/version.py
-sdsv_dewarp.egg-info/PKG-INFO
-sdsv_dewarp.egg-info/SOURCES.txt
-sdsv_dewarp.egg-info/dependency_links.txt
-sdsv_dewarp.egg-info/not-zip-safe
-sdsv_dewarp.egg-info/requires.txt
-sdsv_dewarp.egg-info/top_level.txt
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/dependency_links.txt b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/dependency_links.txt
deleted file mode 100755
index 8b13789..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/not-zip-safe b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/not-zip-safe
deleted file mode 100755
index 8b13789..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/not-zip-safe
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/requires.txt b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/requires.txt
deleted file mode 100755
index 89816c8..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/requires.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-paddleocr>=2.0.1
-opencv-contrib-python
-opencv-python
-numpy
-gdown==3.13.0
-imgaug==0.4.0
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/top_level.txt b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/top_level.txt
deleted file mode 100755
index a5ce4e8..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp.egg-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-sdsv_dewarp
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/__init__.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/__init__.py
deleted file mode 100755
index e69de29..0000000
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/api.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/api.py
deleted file mode 100755
index d71ddc5..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/api.py
+++ /dev/null
@@ -1,200 +0,0 @@
-import math
-import numpy as np
-from typing import List
-import cv2
-import collections
-import logging
-import imgaug.augmenters as iaa
-from imgaug.augmentables.polys import Polygon, PolygonsOnImage
-
-from sdsv_dewarp.models import PaddleTextClassifier, PaddleTextDetector
-from sdsv_dewarp.config import Cfg
-from .utils import *
-
-
-MIN_LONG_EDGE = 40**2
-NUMBER_BOX_FOR_ALIGNMENT = 200
-MAX_ANGLE = 180
-MIN_ANGLE = 1
-MIN_NUM_BOX_TEXT = 3
-CROP_SIZE = 3000
-
-logging.basicConfig(level=logging.INFO)
-LOGGER = logging.getLogger(__name__)
-
-
-class AlignImage:
- """Rotate image to 0 degree
- Args:
- text_detector (deepmodel): Text detection model
- text_cls (deepmodel): Text classification model (0 or 180)
-
- Return:
- is_blank (bool): Blank image when haven't boxes text
- image_align: Image after alignment
- angle_align: Degree of angle alignment
- """
-
- def __init__(self, text_detector: dict, text_cls: dict, device: str = 'cpu'):
- self.text_detector = None
- self.text_cls = None
- self.use_gpu = True if device != 'cpu' else False
-
- self._init_model(text_detector, text_cls)
-
- def _init_model(self, text_detector, text_cls):
- det_config = Cfg.load_config_from_file(text_detector['config'])
- det_config['model_dir'] = text_detector['weight']
- cls_config = Cfg.load_config_from_file(text_cls['config'])
- cls_config['model_dir'] = text_cls['weight']
-
- self.text_detector = PaddleTextDetector(config=det_config, use_gpu=self.use_gpu)
- self.text_cls = PaddleTextClassifier(config=cls_config, use_gpu=self.use_gpu)
-
- def _cal_width(self, poly_box):
- """Calculate width of a polygon [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]"""
- tl, tr, br, bl = poly_box
- edge_s, edge_l = distance(tl, tr), distance(tr, br)
-
- return max(edge_s, edge_l)
-
- def _get_most_frequent(self, values):
- values = np.array(values)
- # create the histogram
- hist, bins = np.histogram(values, bins=np.arange(0, 181, 10))
-
- # get the index of the most frequent angle
- index = np.argmax(hist)
-
- # get the most frequent angle
- most_frequent_angle = (bins[index] + bins[index + 1]) / 2
-
- return most_frequent_angle
-
- def _cal_angle(self, poly_box):
- """Calculate the angle between two point"""
- a = poly_box[0]
- b = poly_box[1]
- c = poly_box[2]
-
- # Get the longer edge
- if distance(a, b) >= distance(b, c):
- x, y = a, b
- else:
- x, y = b, c
-
- angle = math.degrees(math.atan2(-(y[1] - x[1]), y[0] - x[0]))
-
- if angle < 0:
- angle = 180 - abs(angle)
-
- return angle
-
- def _reject_outliers(self, data, m=5.0):
- """Remove noise angle"""
- list_index = np.arange(len(data))
- d = np.abs(data - np.median(data))
- mdev = np.median(d)
- s = d / (mdev if mdev else 1.0)
-
- return list_index[s < m], data[s < m]
-
- def __call__(self, image):
- """image (np.ndarray): BGR image"""
-
- # Crop center image to increase speed of text detection
-
- image_resized = crop_image(image, crop_size=CROP_SIZE).copy() if max(image.shape) > CROP_SIZE else image.copy()
- poly_box_texts = self.text_detector(image_resized)
-
- # draw_img = vis_ocr(
- # image_resized,
- # poly_box_texts,
- # )
- # cv2.imwrite("draw_img.jpg", draw_img)
-
- is_blank = False
-
- # Check image is blank
- if len(poly_box_texts) <= MIN_NUM_BOX_TEXT:
- is_blank = True
- return image, is_blank, 0
-
- # # Crop document
- # poly_np = np.array(poly_box_texts)
- # min_x = poly_box_texts[:, 0].min()
- # max_x = poly_box_texts[:, 2].max()
- # min_y = poly_box_texts[:, 1].min()
- # max_y = poly_box_texts[:, 3].max()
-
- # Filter small poly
- poly_box_areas = [
- [self._cal_width(poly_box), id]
- for id, poly_box in enumerate(poly_box_texts)
- ]
-
- poly_box_areas = sorted(poly_box_areas)[-NUMBER_BOX_FOR_ALIGNMENT:]
- poly_box_areas = [poly_box_texts[id[1]] for id in poly_box_areas]
-
- # Calculate angle
- list_angle = [self._cal_angle(poly_box) for poly_box in poly_box_areas]
- list_angle = [angle if angle >= MIN_ANGLE else 180 for angle in list_angle]
-
- # LOGGER.info(f"List angle before reject outlier: {list_angle}")
- list_angle = np.array(list_angle)
- list_index, list_angle = self._reject_outliers(list_angle)
- # LOGGER.info(f"List angle after reject outlier: {list_angle}")
-
- if len(list_angle):
-
- frequent_angle = self._get_most_frequent(list_angle)
- list_angle = [angle for angle in list_angle if abs(angle - frequent_angle) <= 45]
- # LOGGER.info(f"List angle after reject angle: {list_angle}")
- angle = np.mean(list_angle)
- else:
- angle = 0
-
- # LOGGER.info(f"Avg angle: {angle}")
-
- # Reuse poly boxes detected by text detection
- polys_org = PolygonsOnImage(
- [Polygon(poly_box_areas[index]) for index in list_index],
- shape=image_resized.shape,
- )
- seq_augment = iaa.Sequential([iaa.Rotate(angle, fit_output=True, order=3)])
-
- # Rotate image by degree
- if angle >= MIN_ANGLE and angle <= MAX_ANGLE:
- image_resized, polys_aug = seq_augment(
- image=image_resized, polygons=polys_org
- )
- else:
- angle = 0
- image_resized, polys_aug = image_resized, polys_org
-
- # cv2.imwrite("image_resized.jpg", image_resized)
-
- # Classify image 0 or 180 degree
- list_poly = [poly.coords for poly in polys_aug]
-
- image_crop_list = [
- dewarp_by_polygon(image_resized, poly)[0] for poly in list_poly
- ]
-
- cls_res = self.text_cls(image_crop_list)
- cls_labels = [cls_[0] for cls_ in cls_res[1]]
- # LOGGER.info(f"Angle lines: {cls_labels}")
- counter = collections.Counter(cls_labels)
-
- angle_align = angle
- if counter["0"] <= counter["180"]:
- aug = iaa.Rotate(angle + 180, fit_output=True, order=3)
- angle_align = angle + 180
- else:
- aug = iaa.Rotate(angle, fit_output=True, order=3)
-
- # Rotate the image by degree
- image = aug.augment_image(image)
-
- return image, is_blank, angle_align
- # return image
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/config.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/config.py
deleted file mode 100755
index 204c2c0..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/config.py
+++ /dev/null
@@ -1,41 +0,0 @@
-import yaml
-import pprint
-import os
-import json
-
-
-def load_from_yaml(fname):
- with open(fname, encoding='utf-8') as f:
- base_config = yaml.safe_load(f)
- return base_config
-
-def load_from_json(fname):
- with open(fname, "r", encoding='utf-8') as f:
- base_config = json.load(f)
- return base_config
-
-class Cfg(dict):
- def __init__(self, config_dict):
- super(Cfg, self).__init__(**config_dict)
- self.__dict__ = self
-
- @staticmethod
- def load_config_from_file(fname, download_base=False):
- if not os.path.exists(fname):
- raise FileNotFoundError("Not found config at {}".format(fname))
- if fname.endswith(".yaml") or fname.endswith(".yml"):
- return Cfg(load_from_yaml(fname))
- elif fname.endswith(".json"):
- return Cfg(load_from_json(fname))
- else:
- raise Exception(f"{fname} not supported")
-
-
- def save(self, fname):
- with open(fname, 'w', encoding='utf-8') as outfile:
- yaml.dump(dict(self), outfile, default_flow_style=False, allow_unicode=True)
-
- # @property
- def pretty_text(self):
- return pprint.PrettyPrinter().pprint(self)
-
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/factory.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/factory.py
deleted file mode 100755
index 65e4bbd..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/factory.py
+++ /dev/null
@@ -1,75 +0,0 @@
-import os
-import shutil
-import hashlib
-import warnings
-
-def sha256sum(filename):
- h = hashlib.sha256()
- b = bytearray(128*1024)
- mv = memoryview(b)
- with open(filename, 'rb', buffering=0) as f:
- for n in iter(lambda : f.readinto(mv), 0):
- h.update(mv[:n])
- return h.hexdigest()
-
-
-online_model_factory = {
- 'yolox-s-general-text-pretrain-20221226': {
- 'url': 'https://github.com/moewiee/satrn-model-factory/raw/main/62j266xm8r.pth',
- 'hash': '89bff792685af454d0cfea5d6d673be6914d614e4c2044e786da6eddf36f8b50'},
- 'yolox-s-checkbox-20220726': {
- 'url': 'https://github.com/moewiee/satrn-model-factory/raw/main/1647d7eys7.pth',
- 'hash': '7c1e188b7375dcf0b7b9d317675ebd92a86fdc29363558002249867249ee10f8'},
- 'yolox-s-idcard-5c-20221027': {
- 'url': 'https://github.com/moewiee/satrn-model-factory/raw/main/jr0egad3ix.pth',
- 'hash': '73a7772594c1f6d3f6d6a98b6d6e4097af5026864e3bd50531ad9e635ae795a7'},
- 'yolox-s-handwritten-text-line-20230228': {
- 'url': 'https://github.com/moewiee/satrn-model-factory/raw/main/rb07rtwmgi.pth',
- 'hash': 'a31d1bf8fc880479d2e11463dad0b4081952a13e553a02919109b634a1190ef1'}
-}
-
-__hub_available_versions__ = online_model_factory.keys()
-
-def _get_from_hub(file_path, version, version_url):
- os.system(f'wget -O {file_path} {version_url}')
- assert os.path.exists(file_path), \
- 'wget failed while trying to retrieve from hub.'
- downloaded_hash = sha256sum(file_path)
- if downloaded_hash != online_model_factory[version]['hash']:
- os.remove(file_path)
- raise ValueError('sha256 hash doesnt match for version retrieved from hub.')
-
-def _get(version):
- use_online = version in __hub_available_versions__
-
- if not use_online and not os.path.exists(version):
- raise ValueError(f'Model version {version} not found online and not found local.')
-
- hub_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'hub')
- if not os.path.exists(hub_path):
- os.makedirs(hub_path)
- if use_online:
- version_url = online_model_factory[version]['url']
- file_path = os.path.join(hub_path, os.path.basename(version_url))
- else:
- file_path = os.path.join(hub_path, os.path.basename(version))
-
- if not os.path.exists(file_path):
- if use_online:
- _get_from_hub(file_path, version, version_url)
- else:
- shutil.copy2(version, file_path)
- else:
- if use_online:
- downloaded_hash = sha256sum(file_path)
- if downloaded_hash != online_model_factory[version]['hash']:
- os.remove(file_path)
- warnings.warn('existing hub version sha256 hash doesnt match, now re-download from hub.')
- _get_from_hub(file_path, version, version_url)
- else:
- if sha256sum(file_path) != sha256sum(version):
- os.remove(file_path)
- warnings.warn('existing local version sha256 hash doesnt match, now replace with new local version.')
- shutil.copy2(version, file_path)
-
- return
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/models.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/models.py
deleted file mode 100755
index 64cb88c..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/models.py
+++ /dev/null
@@ -1,73 +0,0 @@
-
-from paddleocr.tools.infer.predict_det import TextDetector
-from paddleocr.tools.infer.predict_cls import TextClassifier
-from paddleocr.paddleocr import parse_args
-from sdsv_dewarp.config import Cfg
-
-class PaddleTextDetector(object):
- def __init__(
- self,
- # config_path: str,
- config: dict,
- use_gpu=False
- ):
- # config = Cfg.load_config_from_file(config_path)
-
- self.args = parse_args(mMain=False)
- self.args.__dict__.update(
- det_model_dir=config['model_dir'],
- gpu_mem=config['gpu_mem'],
- use_gpu=use_gpu,
- use_zero_copy_run=True,
- max_batch_size=1,
- det_limit_side_len=config['det_limit_side_len'], #960
- det_limit_type=config['det_limit_type'], #'max'
- det_db_unclip_ratio=config['det_db_unclip_ratio'],
- det_db_thresh=config['det_db_thresh'],
- det_db_box_thresh=config['det_db_box_thresh'],
- det_db_score_mode=config['det_db_score_mode'],
- )
- self.text_detector = TextDetector(self.args)
-
- def __call__(self, image):
- """
-
- Args:
- image (np.ndarray): BGR images
-
- Returns:
- np.ndarray: numpy array of poly boxes - shape 4x2
- """
- dt_boxes, time_infer = self.text_detector(image)
- return dt_boxes
-
-
-class PaddleTextClassifier(object):
- def __init__(
- self,
- # config_path: str,
- config: str,
- use_gpu=False
- ):
- # config = Cfg.load_config_from_file(config_path)
-
- self.args = parse_args(mMain=False)
- self.args.__dict__.update(
- cls_model_dir=config['model_dir'],
- gpu_mem=config['gpu_mem'],
- use_gpu=use_gpu,
- use_zero_copy_run=True,
- cls_batch_num=config['max_batch_size'],
- )
- self.text_classifier = TextClassifier(self.args)
-
- def __call__(self, images):
- """
- Args:
- images (np.ndarray): list of BGR images
-
- Returns:
- img_list, cls_res, elapse : cls_res format = (label, conf)
- """
- out= self.text_classifier(images)
- return out
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/utils.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/utils.py
deleted file mode 100755
index ae02cc1..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/utils.py
+++ /dev/null
@@ -1,212 +0,0 @@
-import math
-import cv2
-import numpy as np
-from PIL import Image, ImageDraw, ImageFont
-import random
-
-
-def distance(p1, p2):
- """Calculate Euclid distance"""
- x1, y1 = p1
- x2, y2 = p2
- dist = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
-
- return dist
-
-
-def crop_image(image, crop_size=1280):
- """Crop center image"""
- h, w = image.shape[:2]
- x_center, y_center = w // 2, h // 2
- half_size = crop_size // 2
-
- xmin, ymin = x_center - half_size, y_center - half_size
- xmax, ymax = x_center + half_size, y_center + half_size
-
- xmin = max(xmin, 0)
- ymin = max(ymin, 0)
- xmax = min(xmax, w)
- ymax = min(ymax, h)
-
- return image[ymin:ymax, xmin:xmax]
-
-
-def _closest_point(corners, A):
- """Find closest A in corrers point"""
- distances = [distance(A, p) for p in corners]
- return corners[np.argmin(distances)]
-
-
-def _re_order_corners(image_size, corners) -> list:
- """Order by corners by clockwise angle"""
- h, w = image_size
- tl = _closest_point(corners, (0, 0))
- tr = _closest_point(corners, (w, 0))
- br = _closest_point(corners, (w, h))
- bl = _closest_point(corners, (0, h))
-
- return [tl, tr, br, bl]
-
-
-def _validate_corner(corners, ratio_thres=0.5, epsilon=1e-3) -> bool:
- """Check corners is valid
- Invalid: 3 points, duplicate points, ....
- """
- c_tl, c_tr, c_br, c_bl = corners
- e_top = distance(c_tl, c_tr)
- e_right = distance(c_tr, c_br)
- e_bottom = distance(c_br, c_bl)
- e_left = distance(c_bl, c_tl)
-
- min_tb = min(e_top, e_bottom)
- max_tb = max(e_top, e_bottom)
- min_lr = min(e_left, e_right)
- max_lr = max(e_left, e_right)
-
- # Nếu các điểm trùng nhau thì độ dài các cạnh sẽ bằng 0
- if min(max_tb, max_lr) < epsilon:
- return False
-
- ratio = min(min_tb / max_tb, min_lr / max_lr)
- if ratio < ratio_thres:
- return False
-
- return True
-
-
-def dewarp_by_polygon(
- image, corners, need_validate=False, need_reorder=True, trace_trans=None
-):
- """Crop and dewarp from 4 corners of images
-
- Args:
- image (np.array)
- corners (list): Ex : [(3347, 512), (3379, 2427), (638, 2524), (647, 495)]
- need_validate (bool, optional): validate 4 points. Defaults to False.
- need_reorder (bool, optional): validate 4 points. Defaults to True.
-
- Returns:
- dewarped: image after dewarp
- corners: location of 4 corners after reorder
- """
- h, w = image.shape[:2]
-
- if need_reorder:
- corners = _re_order_corners((h, w), corners)
-
- dewarped = image
-
- if need_validate:
- validate = _validate_corner(corners)
- else:
- validate = True
-
- if validate:
- # perform dewarp
- target_w = int(
- max(distance(corners[0], corners[1]), distance(corners[2], corners[3]))
- )
- target_h = int(
- max(distance(corners[0], corners[3]), distance(corners[1], corners[2]))
- )
- target_corners = [
- [0, 0],
- [target_w, 0],
- [target_w, target_h],
- [0, target_h],
- ]
-
- pts1 = np.float32(corners)
- pts2 = np.float32(target_corners)
- transform_matrix = cv2.getPerspectiveTransform(pts1, pts2)
-
- dewarped = cv2.warpPerspective(image, transform_matrix, (target_w, target_h))
- if trace_trans is not None:
- trace_trans["dewarp_method"]["polygon"][
- "transform_matrix"
- ] = transform_matrix
-
- return (dewarped, corners, trace_trans)
-
-
-def vis_ocr(image, boxes, txts=[], scores=None, drop_score=0.5):
- """
- Args:
- image (np.ndarray / PIL): BGR image or PIL image
- boxes (list / np.ndarray): list of polygon boxes
- txts (list): list of text labels
- scores (list, optional): probality. Defaults to None.
- drop_score (float, optional): . Defaults to 0.5.
- font_path (str, optional): Path of font. Defaults to "test/fonts/latin.ttf".
- Returns:
- np.ndarray: BGR image
- """
-
- if len(txts) == 0:
- txts = [""] * len(boxes)
-
- if isinstance(image, np.ndarray):
- image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
- if isinstance(boxes, list):
- boxes = np.array(boxes)
-
- h, w = image.height, image.width
- img_left = image.copy()
- img_right = Image.new("RGB", (w, h), (255, 255, 255))
- draw_left = ImageDraw.Draw(img_left)
- draw_right = ImageDraw.Draw(img_right)
- for idx, (box, txt) in enumerate(zip(boxes, txts)):
- if scores is not None and scores[idx] < drop_score:
- continue
- color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
- draw_left.polygon(
- [
- box[0][0],
- box[0][1],
- box[1][0],
- box[1][1],
- box[2][0],
- box[2][1],
- box[3][0],
- box[3][1],
- ],
- fill=color,
- )
- draw_right.polygon(
- [
- box[0][0],
- box[0][1],
- box[1][0],
- box[1][1],
- box[2][0],
- box[2][1],
- box[3][0],
- box[3][1],
- ],
- outline=color,
- )
- box_height = math.sqrt(
- (box[0][0] - box[3][0]) ** 2 + (box[0][1] - box[3][1]) ** 2
- )
- box_width = math.sqrt(
- (box[0][0] - box[1][0]) ** 2 + (box[0][1] - box[1][1]) ** 2
- )
- if box_height > 2 * box_width:
- font_size = max(int(box_width * 0.9), 10)
- font = ImageFont.load_default()
- cur_y = box[0][1]
- for c in txt:
- char_size = font.getsize(c)
- draw_right.text((box[0][0] + 3, cur_y), c, fill=(0, 0, 0), font=font)
- cur_y += char_size[1]
- else:
- font_size = max(int(box_height * 0.8), 10)
- font = ImageFont.load_default()
- draw_right.text([box[0][0], box[0][1]], txt, fill=(0, 0, 0), font=font)
- img_left = Image.blend(image, img_left, 0.5)
-
- img_show = Image.new("RGB", (w * 2, h), (255, 255, 255))
- img_show.paste(img_left, (0, 0, w, h))
- img_show.paste(img_right, (w, 0, w * 2, h))
- img_show = cv2.cvtColor(np.array(img_show), cv2.COLOR_RGB2BGR)
- return img_show
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/version.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/version.py
deleted file mode 100755
index a1570ac..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/sdsv_dewarp/version.py
+++ /dev/null
@@ -1 +0,0 @@
-__version__="1.0.0"
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/setup.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/setup.py
deleted file mode 100755
index 7887e8f..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/setup.py
+++ /dev/null
@@ -1,187 +0,0 @@
-import os
-import os.path as osp
-import shutil
-import sys
-import warnings
-from setuptools import find_packages, setup
-
-
-def readme():
- with open('README.md', encoding='utf-8') as f:
- content = f.read()
- return content
-
-
-version_file = 'sdsv_dewarp/version.py'
-is_windows = sys.platform == 'win32'
-
-
-def add_mim_extention():
- """Add extra files that are required to support MIM into the package.
-
- These files will be added by creating a symlink to the originals if the
- package is installed in `editable` mode (e.g. pip install -e .), or by
- copying from the originals otherwise.
- """
-
- # parse installment mode
- if 'develop' in sys.argv:
- # installed by `pip install -e .`
- mode = 'symlink'
- elif 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
- # installed by `pip install .`
- # or create source distribution by `python setup.py sdist`
- mode = 'copy'
- else:
- return
-
- filenames = ['tools', 'configs', 'model-index.yml']
- repo_path = osp.dirname(__file__)
- mim_path = osp.join(repo_path, 'mmocr', '.mim')
- os.makedirs(mim_path, exist_ok=True)
-
- for filename in filenames:
- if osp.exists(filename):
- src_path = osp.join(repo_path, filename)
- tar_path = osp.join(mim_path, filename)
-
- if osp.isfile(tar_path) or osp.islink(tar_path):
- os.remove(tar_path)
- elif osp.isdir(tar_path):
- shutil.rmtree(tar_path)
-
- if mode == 'symlink':
- src_relpath = osp.relpath(src_path, osp.dirname(tar_path))
- try:
- os.symlink(src_relpath, tar_path)
- except OSError:
- # Creating a symbolic link on windows may raise an
- # `OSError: [WinError 1314]` due to privilege. If
- # the error happens, the src file will be copied
- mode = 'copy'
- warnings.warn(
- f'Failed to create a symbolic link for {src_relpath}, '
- f'and it will be copied to {tar_path}')
- else:
- continue
-
- if mode == 'copy':
- if osp.isfile(src_path):
- shutil.copyfile(src_path, tar_path)
- elif osp.isdir(src_path):
- shutil.copytree(src_path, tar_path)
- else:
- warnings.warn(f'Cannot copy file {src_path}.')
- else:
- raise ValueError(f'Invalid mode {mode}')
-
-
-def get_version():
- with open(version_file, 'r') as f:
- exec(compile(f.read(), version_file, 'exec'))
- import sys
-
- # return short version for sdist
- if 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
- return locals()['short_version']
- else:
- return locals()['__version__']
-
-
-def parse_requirements(fname='requirements.txt', with_version=True):
- """Parse the package dependencies listed in a requirements file but strip
- specific version information.
-
- Args:
- fname (str): Path to requirements file.
- with_version (bool, default=False): If True, include version specs.
- Returns:
- info (list[str]): List of requirements items.
- CommandLine:
- python -c "import setup; print(setup.parse_requirements())"
- """
- import re
- import sys
- from os.path import exists
- require_fpath = fname
-
- def parse_line(line):
- """Parse information from a line in a requirements text file."""
- if line.startswith('-r '):
- # Allow specifying requirements in other files
- target = line.split(' ')[1]
- for info in parse_require_file(target):
- yield info
- else:
- info = {'line': line}
- if line.startswith('-e '):
- info['package'] = line.split('#egg=')[1]
- else:
- # Remove versioning from the package
- pat = '(' + '|'.join(['>=', '==', '>']) + ')'
- parts = re.split(pat, line, maxsplit=1)
- parts = [p.strip() for p in parts]
-
- info['package'] = parts[0]
- if len(parts) > 1:
- op, rest = parts[1:]
- if ';' in rest:
- # Handle platform specific dependencies
- # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
- version, platform_deps = map(str.strip,
- rest.split(';'))
- info['platform_deps'] = platform_deps
- else:
- version = rest # NOQA
- info['version'] = (op, version)
- yield info
-
- def parse_require_file(fpath):
- with open(fpath, 'r') as f:
- for line in f.readlines():
- line = line.strip()
- if line and not line.startswith('#'):
- for info in parse_line(line):
- yield info
-
- def gen_packages_items():
- if exists(require_fpath):
- for info in parse_require_file(require_fpath):
- parts = [info['package']]
- if with_version and 'version' in info:
- parts.extend(info['version'])
- if not sys.version.startswith('3.4'):
- # apparently package_deps are broken in 3.4
- platform_deps = info.get('platform_deps')
- if platform_deps is not None:
- parts.append(';' + platform_deps)
- item = ''.join(parts)
- yield item
-
- packages = list(gen_packages_items())
- return packages
-
-
-if __name__ == '__main__':
- setup(
- name='sdsv_dewarp',
- version=get_version(),
- description='Dewarp document',
- long_description=readme(),
- long_description_content_type='text/markdown',
- packages=find_packages(exclude=('configs', 'tools', 'demo')),
- include_package_data=True,
- url='',
- classifiers=[
- 'Development Status :: 4 - Beta',
- 'License :: OSI Approved :: Apache Software License',
- 'Operating System :: OS Independent',
- 'Programming Language :: Python :: 3',
- 'Programming Language :: Python :: 3.6',
- 'Programming Language :: Python :: 3.7',
- 'Programming Language :: Python :: 3.8',
- 'Programming Language :: Python :: 3.9',
- ],
- license='Apache License 2.0',
- install_requires=parse_requirements('requirements.txt'),
- zip_safe=False)
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/test.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/test.py
deleted file mode 100755
index 4bfdbc7..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/test.py
+++ /dev/null
@@ -1,47 +0,0 @@
-from sdsv_dewarp.api import AlignImage
-import cv2
-import glob
-import os
-import tqdm
-import time
-import argparse
-
-
-
-if __name__ == "__main__":
- parser = argparse.ArgumentParser()
- parser.add_argument("--input")
- parser.add_argument("--out")
- parser.add_argument("--device", type=str, default="cuda:1")
-
- args = parser.parse_args()
- model = AlignImage(device=args.device)
-
-
- img_dir = args.input
- out_dir = args.out
- if not os.path.exists(out_dir):
- os.makedirs(out_dir)
-
- img_paths = glob.glob(img_dir + "/*")
-
- times = []
- for img_path in tqdm.tqdm(img_paths):
- t1 = time.time()
- img = cv2.imread(img_path)
- if img is None:
- print(img_path)
- continue
-
- aligned_img, is_blank, angle_align = model(img)
-
- times.append(time.time() - t1)
-
- if not is_blank:
- cv2.imwrite(os.path.join(out_dir, os.path.basename(img_path)), aligned_img)
- else:
- cv2.imwrite(os.path.join(out_dir, os.path.basename(img_path)), img)
-
-
- times = times[1:]
- print("Avg time: ", sum(times) / len(times))
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/.gitignore b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/.gitignore
deleted file mode 100755
index a8c1759..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-# Builds
-*.egg-info
-__pycache__
-
-# Checkpoint
-hub
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/LICENSE b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/LICENSE
deleted file mode 100755
index 9e419e0..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/LICENSE
+++ /dev/null
@@ -1,674 +0,0 @@
-GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc.
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Use with the GNU Affero General Public License.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C)
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
-
-Also add information on how to contact you by electronic and paper mail.
-
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- Copyright (C)
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-.
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/README.md b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/README.md
deleted file mode 100755
index 4de145b..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/README.md
+++ /dev/null
@@ -1,76 +0,0 @@
-## Introduction
-This repo serve as source code storage for the Standalone YoloX Detection packages.
-Installing this package requires 2 additional packages: PyTorch and MMCV.
-
-
-## Installation
-```shell
-conda create -n sdsvtd-env python=3.8
-conda activate sdsvtd-env
-conda install pytorch torchvision pytorch-cuda=11.6 -c pytorch -c nvidia
-pip install mmcv-full
-git clone https://github.com/moewiee/sdsvtd.git
-cd sdsvtd
-pip install -v -e .
-```
-
-## Basic Usage
-```python
-from sdsvtd import StandaloneYOLOXRunner
-runner = StandaloneYOLOXRunner(version='yolox-s-general-text-pretrain-20221226', device='cpu')
-```
-
-The `version` parameter accepts version names declared in `sdsvtd.factory.online_model_factory` or a local path such as `$DIR\model.pth`. To check for available versions in the hub, run:
-```python
-import sdsvtd
-print(sdsvtd.__hub_available_versions__)
-```
-
-Naturally, a `StandaloneYOLOXRunner` instance assumes the input to be an instance of `np.ndarray` or an instance of `str` (batch inferece is not supported), for examples:
-```python
-import numpy as np
-from sdsvtd import StandaloneYOLOXRunner
-runner = StandaloneYOLOXRunner(version='yolox-s-general-text-pretrain-20221226', device='cpu')
-
-dummy_input = np.ndarray(500, 500, 3)
-result = runner(dummy_input)
-```
-
-**Note:** Output of `StandaloneYOLOXRunner` instance will be in format `List[np.ndarray]` with each list element corresponds to one class. Each `np.ndarray` will be a 5-d vector `[x1 y1 x2 y2 confident]` with coordinates rescaled to fit the original image size.
-
-**AutoRotation:**
-From version 0.1.0, `sdsvtd` support *AutoRotation* feature which accept a `np.ndarray/str` as input and return an straight rotated image (only available rotation degrees are 90, 180 and 270) of type `np.ndarray` and its bounding boxes of type `List[np.ndarray]`. Usage:
-```python
-import numpy as np
-from sdsvtd import StandaloneYOLOXRunner
-runner = StandaloneYOLOXRunner(version='yolox-s-general-text-pretrain-20221226', device='cpu', auto_rotate=True)
-
-rotated_image, result = runner(cv2.imread('path-to-image')) # or
-rotated_image, result = runner(np.ndarray)
-```
-
-## Version Changelog
-* **[0.0.1]**
-Initial version with specified features.
-
-* **[0.0.2]**
-Update more versions in model hub.
-
-* **[0.0.3]**
-Update feature to specify running device while initialize runner. [Issue](https://github.com/moewiee/sdsvtd/issues/2)
-
-* **[0.0.4]**
-Fix a minor bugs when existing hub/local version != current hub/local version.
-
-* **[0.0.5]**
-Update model hub with handwritten text line detection version.
-
-* **[0.1.0]**
-Update new feature: Auto Rotation.
-
-* **[0.1.1]**
-Fix a bug in API inference class where return double result with auto_rotate=False.
-
-* **[0.1.2]**
-Fix a bug in rotate feature where rotator_version was ignored.
-
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/requirements.txt b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/requirements.txt
deleted file mode 100755
index 10f4b05..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-torch
-mmcv-full
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/__init__.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/__init__.py
deleted file mode 100755
index a3fb997..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from .api import StandaloneYOLOXRunner
-from .version import __version__
-from .factory import __hub_available_versions__
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/api.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/api.py
deleted file mode 100755
index 7deca24..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/api.py
+++ /dev/null
@@ -1,35 +0,0 @@
-from .model import SingleStageDetector, AutoRotateDetector
-import numpy as np
-
-class StandaloneYOLOXRunner:
-
- def __init__(self,
- version,
- device,
- auto_rotate=False,
- rotator_version=None):
- self.model = SingleStageDetector(version,
- device)
- self.auto_rotate = auto_rotate
- if self.auto_rotate:
- if rotator_version is None:
- rotator_version = version
- self.rotator = AutoRotateDetector(rotator_version,
- device)
-
- self.warmup_()
-
- def warmup_(self):
- ''' Call on dummpy input to warm up instance '''
- x = np.ndarray((1280, 1280, 3)).astype(np.uint8)
- self.model(x)
- if self.auto_rotate:
- self.rotator(x)
-
-
- def __call__(self, img):
- if self.auto_rotate:
- img = self.rotator(img)
- result = self.model(img)
-
- return result if not self.auto_rotate else (img, result)
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/backbone.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/backbone.py
deleted file mode 100755
index 5aadded..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/backbone.py
+++ /dev/null
@@ -1,395 +0,0 @@
-import torch
-import torch.nn as nn
-from mmcv.cnn import ConvModule
-from torch.nn.modules.batchnorm import _BatchNorm
-
-
-class DarknetBottleneck(nn.Module):
- """The basic bottleneck block used in Darknet.
-
- Each ResBlock consists of two ConvModules and the input is added to the
- final output. Each ConvModule is composed of Conv, BN, and LeakyReLU.
- The first convLayer has filter size of 1x1 and the second one has the
- filter size of 3x3.
-
- Args:
- in_channels (int): The input channels of this Module.
- out_channels (int): The output channels of this Module.
- expansion (int): The kernel size of the convolution. Default: 0.5
- add_identity (bool): Whether to add identity to the out.
- Default: True
- use_depthwise (bool): Whether to use depthwise separable convolution.
- Default: False
- conv_cfg (dict): Config dict for convolution layer. Default: None,
- which means using conv2d.
- norm_cfg (dict): Config dict for normalization layer.
- Default: dict(type='BN').
- act_cfg (dict): Config dict for activation layer.
- Default: dict(type='Swish').
- """
-
- def __init__(self,
- in_channels,
- out_channels,
- expansion=0.5,
- add_identity=True,
- use_depthwise=False,
- conv_cfg=None,
- norm_cfg=dict(type='BN', momentum=0.03, eps=0.001),
- act_cfg=dict(type='Swish')):
- super().__init__()
- hidden_channels = int(out_channels * expansion)
- self.conv1 = ConvModule(
- in_channels,
- hidden_channels,
- 1,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg)
- self.conv2 = ConvModule(
- hidden_channels,
- out_channels,
- 3,
- stride=1,
- padding=1,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg)
- self.add_identity = \
- add_identity and in_channels == out_channels
-
- def forward(self, x):
- identity = x
- out = self.conv1(x)
- out = self.conv2(out)
-
- if self.add_identity:
- return out + identity
- else:
- return out
-
-
-class CSPLayer(nn.Module):
- """Cross Stage Partial Layer.
-
- Args:
- in_channels (int): The input channels of the CSP layer.
- out_channels (int): The output channels of the CSP layer.
- expand_ratio (float): Ratio to adjust the number of channels of the
- hidden layer. Default: 0.5
- num_blocks (int): Number of blocks. Default: 1
- add_identity (bool): Whether to add identity in blocks.
- Default: True
- use_depthwise (bool): Whether to depthwise separable convolution in
- blocks. Default: False
- conv_cfg (dict, optional): Config dict for convolution layer.
- Default: None, which means using conv2d.
- norm_cfg (dict): Config dict for normalization layer.
- Default: dict(type='BN')
- act_cfg (dict): Config dict for activation layer.
- Default: dict(type='Swish')
- """
-
- def __init__(self,
- in_channels,
- out_channels,
- expand_ratio=0.5,
- num_blocks=1,
- add_identity=True,
- use_depthwise=False,
- conv_cfg=None,
- norm_cfg=dict(type='BN', momentum=0.03, eps=0.001),
- act_cfg=dict(type='Swish')):
- super().__init__()
- mid_channels = int(out_channels * expand_ratio)
- self.main_conv = ConvModule(
- in_channels,
- mid_channels,
- 1,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg)
- self.short_conv = ConvModule(
- in_channels,
- mid_channels,
- 1,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg)
- self.final_conv = ConvModule(
- 2 * mid_channels,
- out_channels,
- 1,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg)
-
- self.blocks = nn.Sequential(*[
- DarknetBottleneck(
- mid_channels,
- mid_channels,
- 1.0,
- add_identity,
- use_depthwise,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg) for _ in range(num_blocks)
- ])
-
- def forward(self, x):
- x_short = self.short_conv(x)
-
- x_main = self.main_conv(x)
- x_main = self.blocks(x_main)
-
- x_final = torch.cat((x_main, x_short), dim=1)
- return self.final_conv(x_final)
-
-
-
-class Focus(nn.Module):
- """Focus width and height information into channel space.
-
- Args:
- in_channels (int): The input channels of this Module.
- out_channels (int): The output channels of this Module.
- kernel_size (int): The kernel size of the convolution. Default: 1
- stride (int): The stride of the convolution. Default: 1
- conv_cfg (dict): Config dict for convolution layer. Default: None,
- which means using conv2d.
- norm_cfg (dict): Config dict for normalization layer.
- Default: dict(type='BN', momentum=0.03, eps=0.001).
- act_cfg (dict): Config dict for activation layer.
- Default: dict(type='Swish').
- """
-
- def __init__(self,
- in_channels,
- out_channels,
- kernel_size=1,
- stride=1,
- conv_cfg=None,
- norm_cfg=dict(type='BN', momentum=0.03, eps=0.001),
- act_cfg=dict(type='Swish')):
- super().__init__()
- self.conv = ConvModule(
- in_channels * 4,
- out_channels,
- kernel_size,
- stride,
- padding=(kernel_size - 1) // 2,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg)
-
- def forward(self, x):
- # shape of x (b,c,w,h) -> y(b,4c,w/2,h/2)
- patch_top_left = x[..., ::2, ::2]
- patch_top_right = x[..., ::2, 1::2]
- patch_bot_left = x[..., 1::2, ::2]
- patch_bot_right = x[..., 1::2, 1::2]
- x = torch.cat(
- (
- patch_top_left,
- patch_bot_left,
- patch_top_right,
- patch_bot_right,
- ),
- dim=1,
- )
- return self.conv(x)
-
-
-class SPPBottleneck(nn.Module):
- """Spatial pyramid pooling layer used in YOLOv3-SPP.
-
- Args:
- in_channels (int): The input channels of this Module.
- out_channels (int): The output channels of this Module.
- kernel_sizes (tuple[int]): Sequential of kernel sizes of pooling
- layers. Default: (5, 9, 13).
- conv_cfg (dict): Config dict for convolution layer. Default: None,
- which means using conv2d.
- norm_cfg (dict): Config dict for normalization layer.
- Default: dict(type='BN').
- act_cfg (dict): Config dict for activation layer.
- Default: dict(type='Swish').
- init_cfg (dict or list[dict], optional): Initialization config dict.
- Default: None.
- """
-
- def __init__(self,
- in_channels,
- out_channels,
- kernel_sizes=(5, 9, 13),
- conv_cfg=None,
- norm_cfg=dict(type='BN', momentum=0.03, eps=0.001),
- act_cfg=dict(type='Swish')):
- super().__init__()
- mid_channels = in_channels // 2
- self.conv1 = ConvModule(
- in_channels,
- mid_channels,
- 1,
- stride=1,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg)
- self.poolings = nn.ModuleList([
- nn.MaxPool2d(kernel_size=ks, stride=1, padding=ks // 2)
- for ks in kernel_sizes
- ])
- conv2_channels = mid_channels * (len(kernel_sizes) + 1)
- self.conv2 = ConvModule(
- conv2_channels,
- out_channels,
- 1,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg)
-
- def forward(self, x):
- x = self.conv1(x)
- x = torch.cat([x] + [pooling(x) for pooling in self.poolings], dim=1)
- x = self.conv2(x)
- return x
-
-
-class CSPDarknet(nn.Module):
- """CSP-Darknet backbone used in YOLOv5 and YOLOX.
-
- Args:
- arch (str): Architecture of CSP-Darknet, from {P5, P6}.
- Default: P5.
- deepen_factor (float): Depth multiplier, multiply number of
- blocks in CSP layer by this amount. Default: 1.0.
- widen_factor (float): Width multiplier, multiply number of
- channels in each layer by this amount. Default: 1.0.
- out_indices (Sequence[int]): Output from which stages.
- Default: (2, 3, 4).
- frozen_stages (int): Stages to be frozen (stop grad and set eval
- mode). -1 means not freezing any parameters. Default: -1.
- use_depthwise (bool): Whether to use depthwise separable convolution.
- Default: False.
- arch_ovewrite(list): Overwrite default arch settings. Default: None.
- spp_kernal_sizes: (tuple[int]): Sequential of kernel sizes of SPP
- layers. Default: (5, 9, 13).
- conv_cfg (dict): Config dict for convolution layer. Default: None.
- norm_cfg (dict): Dictionary to construct and config norm layer.
- Default: dict(type='BN', requires_grad=True).
- act_cfg (dict): Config dict for activation layer.
- Default: dict(type='LeakyReLU', negative_slope=0.1).
- norm_eval (bool): Whether to set norm layers to eval mode, namely,
- freeze running stats (mean and var). Note: Effect on Batch Norm
- and its variants only.
- """
- # From left to right:
- # in_channels, out_channels, num_blocks, add_identity, use_spp
- arch_settings = {
- 'P5': [[64, 128, 3, True, False], [128, 256, 9, True, False],
- [256, 512, 9, True, False], [512, 1024, 3, False, True]],
- 'P6': [[64, 128, 3, True, False], [128, 256, 9, True, False],
- [256, 512, 9, True, False], [512, 768, 3, True, False],
- [768, 1024, 3, False, True]]
- }
-
- def __init__(self,
- arch='P5',
- deepen_factor=1.0,
- widen_factor=1.0,
- out_indices=(2, 3, 4),
- frozen_stages=-1,
- use_depthwise=False,
- arch_ovewrite=None,
- spp_kernal_sizes=(5, 9, 13),
- conv_cfg=None,
- norm_cfg=dict(type='BN', momentum=0.03, eps=0.001),
- act_cfg=dict(type='Swish'),
- norm_eval=False):
- super().__init__()
- arch_setting = self.arch_settings[arch]
- if arch_ovewrite:
- arch_setting = arch_ovewrite
- assert set(out_indices).issubset(
- i for i in range(len(arch_setting) + 1))
- if frozen_stages not in range(-1, len(arch_setting) + 1):
- raise ValueError('frozen_stages must be in range(-1, '
- 'len(arch_setting) + 1). But received '
- f'{frozen_stages}')
-
- self.out_indices = out_indices
- self.frozen_stages = frozen_stages
- self.use_depthwise = use_depthwise
- self.norm_eval = norm_eval
-
- self.stem = Focus(
- 3,
- int(arch_setting[0][0] * widen_factor),
- kernel_size=3,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg)
- self.layers = ['stem']
-
- for i, (in_channels, out_channels, num_blocks, add_identity,
- use_spp) in enumerate(arch_setting):
- in_channels = int(in_channels * widen_factor)
- out_channels = int(out_channels * widen_factor)
- num_blocks = max(round(num_blocks * deepen_factor), 1)
- stage = []
- conv_layer = ConvModule(
- in_channels,
- out_channels,
- 3,
- stride=2,
- padding=1,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg)
- stage.append(conv_layer)
- if use_spp:
- spp = SPPBottleneck(
- out_channels,
- out_channels,
- kernel_sizes=spp_kernal_sizes,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg)
- stage.append(spp)
- csp_layer = CSPLayer(
- out_channels,
- out_channels,
- num_blocks=num_blocks,
- add_identity=add_identity,
- use_depthwise=use_depthwise,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg)
- stage.append(csp_layer)
- self.add_module(f'stage{i + 1}', nn.Sequential(*stage))
- self.layers.append(f'stage{i + 1}')
-
- def _freeze_stages(self):
- if self.frozen_stages >= 0:
- for i in range(self.frozen_stages + 1):
- m = getattr(self, self.layers[i])
- m.eval()
- for param in m.parameters():
- param.requires_grad = False
-
- def train(self, mode=True):
- super(CSPDarknet, self).train(mode)
- self._freeze_stages()
- if mode and self.norm_eval:
- for m in self.modules():
- if isinstance(m, _BatchNorm):
- m.eval()
-
- def forward(self, x):
- outs = []
- for i, layer_name in enumerate(self.layers):
- layer = getattr(self, layer_name)
- x = layer(x)
- if i in self.out_indices:
- outs.append(x)
- return tuple(outs)
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/bbox_head.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/bbox_head.py
deleted file mode 100755
index bb485f2..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/bbox_head.py
+++ /dev/null
@@ -1,288 +0,0 @@
-import torch
-import torch.nn as nn
-from mmcv.cnn import ConvModule
-from mmcv.ops.nms import batched_nms
-from mmcv.runner import force_fp32
-from functools import partial
-from .priors import MlvlPointGenerator
-
-
-def multi_apply(func, *args, **kwargs):
- """Apply function to a list of arguments.
-
- Note:
- This function applies the ``func`` to multiple inputs and
- map the multiple outputs of the ``func`` into different
- list. Each list contains the same type of outputs corresponding
- to different inputs.
-
- Args:
- func (Function): A function that will be applied to a list of
- arguments
-
- Returns:
- tuple(list): A tuple containing multiple list, each list contains \
- a kind of returned results by the function
- """
- pfunc = partial(func, **kwargs) if kwargs else func
- map_results = map(pfunc, *args)
- return tuple(map(list, zip(*map_results)))
-
-
-class YOLOXHead(nn.Module):
- """YOLOXHead head used in `YOLOX `_.
-
- Args:
- num_classes (int): Number of categories excluding the background
- category.
- in_channels (int): Number of channels in the input feature map.
- feat_channels (int): Number of hidden channels in stacking convs.
- Default: 256
- stacked_convs (int): Number of stacking convs of the head.
- Default: 2.
- strides (tuple): Downsample factor of each feature map.
- use_depthwise (bool): Whether to depthwise separable convolution in
- blocks. Default: False
- dcn_on_last_conv (bool): If true, use dcn in the last layer of
- towers. Default: False.
- conv_bias (bool | str): If specified as `auto`, it will be decided by
- the norm_cfg. Bias of conv will be set as True if `norm_cfg` is
- None, otherwise False. Default: "auto".
- conv_cfg (dict): Config dict for convolution layer. Default: None.
- norm_cfg (dict): Config dict for normalization layer. Default: None.
- act_cfg (dict): Config dict for activation layer. Default: None.
- """
-
- def __init__(self,
- num_classes,
- in_channels,
- feat_channels=256,
- stacked_convs=2,
- strides=[8, 16, 32],
- use_depthwise=False,
- dcn_on_last_conv=False,
- conv_bias='auto',
- conv_cfg=None,
- norm_cfg=dict(type='BN', momentum=0.03, eps=0.001),
- act_cfg=dict(type='Swish'),
- nms_score_thr=0.3,
- nms_iou_threshold=0.1):
-
- super().__init__()
- self.nms_config = dict(score_thr=nms_score_thr, nms=dict(iou_threshold=nms_iou_threshold))
- self.num_classes = num_classes
- self.cls_out_channels = num_classes
- self.in_channels = in_channels
- self.feat_channels = feat_channels
- self.stacked_convs = stacked_convs
- self.strides = strides
- self.use_depthwise = use_depthwise
- self.dcn_on_last_conv = dcn_on_last_conv
- assert conv_bias == 'auto' or isinstance(conv_bias, bool)
- self.conv_bias = conv_bias
- self.use_sigmoid_cls = True
-
- self.conv_cfg = conv_cfg
- self.norm_cfg = norm_cfg
- self.act_cfg = act_cfg
-
- self.prior_generator = MlvlPointGenerator(strides, offset=0)
-
- self.fp16_enabled = False
- self._init_layers()
-
- def _init_layers(self):
- self.multi_level_cls_convs = nn.ModuleList()
- self.multi_level_reg_convs = nn.ModuleList()
- self.multi_level_conv_cls = nn.ModuleList()
- self.multi_level_conv_reg = nn.ModuleList()
- self.multi_level_conv_obj = nn.ModuleList()
- for _ in self.strides:
- self.multi_level_cls_convs.append(self._build_stacked_convs())
- self.multi_level_reg_convs.append(self._build_stacked_convs())
- conv_cls, conv_reg, conv_obj = self._build_predictor()
- self.multi_level_conv_cls.append(conv_cls)
- self.multi_level_conv_reg.append(conv_reg)
- self.multi_level_conv_obj.append(conv_obj)
-
- def _build_stacked_convs(self):
- """Initialize conv layers of a single level head."""
- conv = ConvModule
- stacked_convs = []
- for i in range(self.stacked_convs):
- chn = self.in_channels if i == 0 else self.feat_channels
- if self.dcn_on_last_conv and i == self.stacked_convs - 1:
- conv_cfg = dict(type='DCNv2')
- else:
- conv_cfg = self.conv_cfg
- stacked_convs.append(
- conv(
- chn,
- self.feat_channels,
- 3,
- stride=1,
- padding=1,
- conv_cfg=conv_cfg,
- norm_cfg=self.norm_cfg,
- act_cfg=self.act_cfg,
- bias=self.conv_bias))
- return nn.Sequential(*stacked_convs)
-
- def _build_predictor(self):
- """Initialize predictor layers of a single level head."""
- conv_cls = nn.Conv2d(self.feat_channels, self.cls_out_channels, 1)
- conv_reg = nn.Conv2d(self.feat_channels, 4, 1)
- conv_obj = nn.Conv2d(self.feat_channels, 1, 1)
- return conv_cls, conv_reg, conv_obj
-
- def forward_single(self, x, cls_convs, reg_convs, conv_cls, conv_reg,
- conv_obj):
- """Forward feature of a single scale level."""
-
- cls_feat = cls_convs(x)
- reg_feat = reg_convs(x)
-
- cls_score = conv_cls(cls_feat)
- bbox_pred = conv_reg(reg_feat)
- objectness = conv_obj(reg_feat)
-
- return cls_score, bbox_pred, objectness
-
- def forward(self, feats):
- """Forward features from the upstream network.
-
- Args:
- feats (tuple[Tensor]): Features from the upstream network, each is
- a 4D-tensor.
- Returns:
- tuple[Tensor]: A tuple of multi-level predication map, each is a
- 4D-tensor of shape (batch_size, 5+num_classes, height, width).
- """
-
- return multi_apply(self.forward_single, feats,
- self.multi_level_cls_convs,
- self.multi_level_reg_convs,
- self.multi_level_conv_cls,
- self.multi_level_conv_reg,
- self.multi_level_conv_obj)
-
- @force_fp32(apply_to=('cls_scores', 'bbox_preds', 'objectnesses'))
- def get_bboxes(self,
- cls_scores,
- bbox_preds,
- objectnesses,
- cfg=None):
- """Transform network outputs of a batch into bbox results.
- Args:
- cls_scores (list[Tensor]): Classification scores for all
- scale levels, each is a 4D-tensor, has shape
- (batch_size, num_priors * num_classes, H, W).
- bbox_preds (list[Tensor]): Box energies / deltas for all
- scale levels, each is a 4D-tensor, has shape
- (batch_size, num_priors * 4, H, W).
- objectnesses (list[Tensor], Optional): Score factor for
- all scale level, each is a 4D-tensor, has shape
- (batch_size, 1, H, W).
- cfg (mmcv.Config, Optional): Test / postprocessing configuration,
- if None, test_cfg would be used. Default None.
- rescale (bool): If True, return boxes in original image space.
- Default False.
- with_nms (bool): If True, do nms before return boxes.
- Default True.
- Returns:
- list[list[Tensor, Tensor]]: Each item in result_list is 2-tuple.
- The first item is an (n, 5) tensor, where the first 4 columns
- are bounding box positions (tl_x, tl_y, br_x, br_y) and the
- 5-th column is a score between 0 and 1. The second item is a
- (n,) tensor where each item is the predicted class label of
- the corresponding box.
- """
- assert len(cls_scores) == len(bbox_preds) == len(objectnesses)
- cfg = self.nms_config if cfg is None else cfg
-
- featmap_sizes = [cls_score.shape[2:] for cls_score in cls_scores]
- mlvl_priors = self.prior_generator.grid_priors(
- featmap_sizes,
- dtype=cls_scores[0].dtype,
- device=cls_scores[0].device,
- with_stride=True)
-
- # flatten cls_scores, bbox_preds and objectness
- flatten_cls_scores = [
- cls_score.permute(0, 2, 3, 1).reshape(1, -1,
- self.cls_out_channels)
- for cls_score in cls_scores
- ]
- flatten_bbox_preds = [
- bbox_pred.permute(0, 2, 3, 1).reshape(1, -1, 4)
- for bbox_pred in bbox_preds
- ]
- flatten_objectness = [
- objectness.permute(0, 2, 3, 1).reshape(1, -1)
- for objectness in objectnesses
- ]
-
- flatten_cls_scores = torch.cat(flatten_cls_scores, dim=1).sigmoid()
- flatten_bbox_preds = torch.cat(flatten_bbox_preds, dim=1)
- flatten_objectness = torch.cat(flatten_objectness, dim=1).sigmoid()
- flatten_priors = torch.cat(mlvl_priors)
-
- flatten_bboxes = self._bbox_decode(flatten_priors, flatten_bbox_preds)
-
- result_list = []
- for img_id in range(1):
- cls_scores = flatten_cls_scores[img_id]
- score_factor = flatten_objectness[img_id]
- bboxes = flatten_bboxes[img_id]
-
- result_list.append(
- self._bboxes_nms(cls_scores, bboxes, score_factor, cfg))
-
- return result_list
-
- def _bbox_decode(self, priors, bbox_preds):
- xys = (bbox_preds[..., :2] * priors[:, 2:]) + priors[:, :2]
- whs = bbox_preds[..., 2:].exp() * priors[:, 2:]
-
- tl_x = (xys[..., 0] - whs[..., 0] / 2)
- tl_y = (xys[..., 1] - whs[..., 1] / 2)
- br_x = (xys[..., 0] + whs[..., 0] / 2)
- br_y = (xys[..., 1] + whs[..., 1] / 2)
-
- decoded_bboxes = torch.stack([tl_x, tl_y, br_x, br_y], -1)
- return decoded_bboxes
-
- def _bboxes_nms(self, cls_scores, bboxes, score_factor, cfg):
- max_scores, labels = torch.max(cls_scores, 1)
- valid_mask = score_factor * max_scores >= cfg['score_thr']
- bboxes = bboxes[valid_mask]
- scores = max_scores[valid_mask] * score_factor[valid_mask]
- labels = labels[valid_mask]
-
- if labels.numel() == 0:
- return bboxes, labels
- else:
- dets, keep = batched_nms(bboxes.float(), scores.float(), labels, cfg['nms'])
- return dets, labels[keep]
-
- def simple_test_bboxes(self, feats):
- """Test det bboxes without test-time augmentation, can be applied in
- DenseHead except for ``RPNHead`` and its variants, e.g., ``GARPNHead``,
- etc.
-
- Args:
- feats (tuple[torch.Tensor]): Multi-level features from the
- upstream network, each is a 4D-tensor.
- rescale (bool, optional): Whether to rescale the results.
- Defaults to False.
-
- Returns:
- list[tuple[Tensor, Tensor]]: Each item in result_list is 2-tuple.
- The first item is ``bboxes`` with shape (n, 5),
- where 5 represent (tl_x, tl_y, br_x, br_y, score).
- The shape of the second tensor in the tuple is ``labels``
- with shape (n,)
- """
- outs = self.forward(feats)
- results_list = self.get_bboxes(*outs)
- return results_list
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/factory.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/factory.py
deleted file mode 100755
index 2b6068f..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/factory.py
+++ /dev/null
@@ -1,75 +0,0 @@
-import os
-import shutil
-import hashlib
-import warnings
-
-def sha256sum(filename):
- h = hashlib.sha256()
- b = bytearray(128*1024)
- mv = memoryview(b)
- with open(filename, 'rb', buffering=0) as f:
- for n in iter(lambda : f.readinto(mv), 0):
- h.update(mv[:n])
- return h.hexdigest()
-
-
-online_model_factory = {
- 'yolox-s-general-text-pretrain-20221226': {
- 'url': 'https://github.com/moewiee/satrn-model-factory/raw/main/62j266xm8r.pth',
- 'hash': '89bff792685af454d0cfea5d6d673be6914d614e4c2044e786da6eddf36f8b50'},
- 'yolox-s-checkbox-20220726': {
- 'url': 'https://github.com/moewiee/satrn-model-factory/raw/main/1647d7eys7.pth',
- 'hash': '7c1e188b7375dcf0b7b9d317675ebd92a86fdc29363558002249867249ee10f8'},
- 'yolox-s-idcard-5c-20221027': {
- 'url': 'https://github.com/moewiee/satrn-model-factory/raw/main/jr0egad3ix.pth',
- 'hash': '73a7772594c1f6d3f6d6a98b6d6e4097af5026864e3bd50531ad9e635ae795a7'},
- 'yolox-s-handwritten-text-line-20230228': {
- 'url': 'https://github.com/moewiee/satrn-model-factory/raw/main/rb07rtwmgi.pth',
- 'hash': 'a31d1bf8fc880479d2e11463dad0b4081952a13e553a02919109b634a1190ef1'}
-}
-
-__hub_available_versions__ = online_model_factory.keys()
-
-def _get_from_hub(file_path, version, version_url):
- os.system(f'wget -O {file_path} {version_url}')
- assert os.path.exists(file_path), \
- 'wget failed while trying to retrieve from hub.'
- downloaded_hash = sha256sum(file_path)
- if downloaded_hash != online_model_factory[version]['hash']:
- os.remove(file_path)
- raise ValueError('sha256 hash doesnt match for version retrieved from hub.')
-
-def _get(version):
- use_online = version in __hub_available_versions__
-
- if not use_online and not os.path.exists(version):
- raise ValueError(f'Model version {version} not found online and not found local.')
-
- hub_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'hub')
- if not os.path.exists(hub_path):
- os.makedirs(hub_path)
- if use_online:
- version_url = online_model_factory[version]['url']
- file_path = os.path.join(hub_path, os.path.basename(version_url))
- else:
- file_path = os.path.join(hub_path, os.path.basename(version))
-
- if not os.path.exists(file_path):
- if use_online:
- _get_from_hub(file_path, version, version_url)
- else:
- shutil.copy2(version, file_path)
- else:
- if use_online:
- downloaded_hash = sha256sum(file_path)
- if downloaded_hash != online_model_factory[version]['hash']:
- os.remove(file_path)
- warnings.warn('existing hub version sha256 hash doesnt match, now re-download from hub.')
- _get_from_hub(file_path, version, version_url)
- else:
- if sha256sum(file_path) != sha256sum(version):
- os.remove(file_path)
- warnings.warn('existing local version sha256 hash doesnt match, now replace with new local version.')
- shutil.copy2(version, file_path)
-
- return file_path
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/model.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/model.py
deleted file mode 100755
index 69a26ef..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/model.py
+++ /dev/null
@@ -1,151 +0,0 @@
-import torch
-import torch.nn as nn
-import numpy as np
-from .backbone import CSPDarknet
-from .neck import YOLOXPAFPN
-from .bbox_head import YOLOXHead
-from .transform import DetectorDataPipeline, AutoRotateDetectorDataPipeline
-from .factory import _get as get_version
-
-
-def bbox2result(bboxes, labels, num_classes):
- """Convert detection results to a list of numpy arrays.
-
- Args:
- bboxes (torch.Tensor | np.ndarray): shape (n, 5)
- labels (torch.Tensor | np.ndarray): shape (n, )
- num_classes (int): class number, including background class
-
- Returns:
- list(ndarray): bbox results of each class
- """
- if bboxes.shape[0] == 0:
- return [np.zeros((0, 5), dtype=np.float32) for i in range(num_classes)]
- else:
- if isinstance(bboxes, torch.Tensor):
- bboxes = bboxes.detach().cpu().numpy()
- labels = labels.detach().cpu().numpy()
- return [bboxes[labels == i, :] for i in range(num_classes)]
-
-
-def normalize_bbox(bboxes, scale):
- for i in range(len(bboxes)):
- bboxes[i][:,:4] /= scale
- return bboxes
-
-
-class SingleStageDetector(nn.Module):
-
- def __init__(self,
- version,
- device):
- super(SingleStageDetector, self).__init__()
-
- assert 'cpu' in device or 'cuda' in device
-
- checkpoint = get_version(version)
- pt = torch.load(checkpoint, 'cpu')
-
- self.pipeline = DetectorDataPipeline(**pt['pipeline_args'], device=device)
- self.backbone = CSPDarknet(**pt['backbone_args'])
- self.neck = YOLOXPAFPN(**pt['neck_args'])
- self.bbox_head = YOLOXHead(**pt['bbox_head_args'])
- self.load_state_dict(pt['state_dict'], strict=True)
-
- self.eval()
- for param in self.parameters():
- param.requires_grad = False
-
- self = self.to(device=device)
-
- print(f'Text detection load from version {version}.')
-
- def extract_feat(self, img):
- """Directly extract features from the backbone + neck."""
-
- x = self.backbone(img)
- x = self.neck(x)
- return x
-
- def forward(self, img):
- """Test function without test-time augmentation.
-
- Args:
- img (np.ndarray): Images with shape (H, W, C) or
- img (str): Path to image.
-
- Returns:
- list[list[np.ndarray]]: BBox results of each image and classes.
- The list corresponds to each class.
- """
- img, origin_shape, new_shape = self.pipeline(img)
- scale = min(new_shape / origin_shape)
- feat = self.extract_feat(img)
- results_list = self.bbox_head.simple_test_bboxes(feat)
- bbox_results = [
- bbox2result(det_bboxes, det_labels, self.bbox_head.num_classes)
- for det_bboxes, det_labels in results_list
- ][0]
- bbox_results = normalize_bbox(bbox_results, scale)
- return bbox_results
-
-
-class AutoRotateDetector(nn.Module):
- def __init__(self,
- version,
- device):
- super(AutoRotateDetector, self).__init__()
-
- assert 'cpu' in device or 'cuda' in device
-
- checkpoint = get_version(version)
- pt = torch.load(checkpoint, 'cpu')
-
- self.pipeline = AutoRotateDetectorDataPipeline(**pt['pipeline_args'], device=device)
- self.backbone = CSPDarknet(**pt['backbone_args'])
- self.neck = YOLOXPAFPN(**pt['neck_args'])
- self.bbox_head = YOLOXHead(**pt['bbox_head_args'], nms_score_thr=0.8)
- self.load_state_dict(pt['state_dict'], strict=True)
-
- self.eval()
- for param in self.parameters():
- param.requires_grad = False
-
- self = self.to(device=device)
-
- print(f'Auto rotate detector load from version {version}.')
-
- def extract_feat(self, img):
- """Directly extract features from the backbone + neck."""
-
- x = self.backbone(img)
- x = self.neck(x)
- return x
-
- def forward(self, img):
- """Test function without test-time augmentation.
-
- Args:
- img (np.ndarray): Images with shape (H, W, C) or
- img (str): Path to image.
-
- Returns:
- np.ndarray: Straight rotated image.
- """
- imgs, imgs_np = self.pipeline(img)
- maxCount = -1
- maxCountRot = None
- for idx, img in enumerate(imgs):
- currentCount = 0
- feat = self.extract_feat(img)
- results_list = self.bbox_head.simple_test_bboxes(feat)
- bbox_results = [
- bbox2result(det_bboxes, det_labels, self.bbox_head.num_classes)
- for det_bboxes, det_labels in results_list
- ][0]
- for class_result in bbox_results:
- currentCount += len(class_result)
- if currentCount > maxCount:
- maxCount = currentCount
- maxCountRot = idx
- return imgs_np[maxCountRot]
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/neck.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/neck.py
deleted file mode 100755
index 2b11e36..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/neck.py
+++ /dev/null
@@ -1,140 +0,0 @@
-import torch
-import torch.nn as nn
-from mmcv.cnn import ConvModule
-from .backbone import CSPLayer
-
-
-class YOLOXPAFPN(nn.Module):
- """Path Aggregation Network used in YOLOX.
-
- Args:
- in_channels (List[int]): Number of input channels per scale.
- out_channels (int): Number of output channels (used at each scale)
- num_csp_blocks (int): Number of bottlenecks in CSPLayer. Default: 3
- use_depthwise (bool): Whether to depthwise separable convolution in
- blocks. Default: False
- upsample_cfg (dict): Config dict for interpolate layer.
- Default: `dict(scale_factor=2, mode='nearest')`
- conv_cfg (dict, optional): Config dict for convolution layer.
- Default: None, which means using conv2d.
- norm_cfg (dict): Config dict for normalization layer.
- Default: dict(type='BN')
- act_cfg (dict): Config dict for activation layer.
- Default: dict(type='Swish')
- init_cfg (dict or list[dict], optional): Initialization config dict.
- Default: None.
- """
-
- def __init__(self,
- in_channels,
- out_channels,
- num_csp_blocks=3,
- use_depthwise=False,
- upsample_cfg=dict(scale_factor=2, mode='nearest'),
- conv_cfg=None,
- norm_cfg=dict(type='BN', momentum=0.03, eps=0.001),
- act_cfg=dict(type='Swish')):
- super(YOLOXPAFPN, self).__init__()
- self.in_channels = in_channels
- self.out_channels = out_channels
-
- # build top-down blocks
- self.upsample = nn.Upsample(**upsample_cfg)
- self.reduce_layers = nn.ModuleList()
- self.top_down_blocks = nn.ModuleList()
- for idx in range(len(in_channels) - 1, 0, -1):
- self.reduce_layers.append(
- ConvModule(
- in_channels[idx],
- in_channels[idx - 1],
- 1,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg))
- self.top_down_blocks.append(
- CSPLayer(
- in_channels[idx - 1] * 2,
- in_channels[idx - 1],
- num_blocks=num_csp_blocks,
- add_identity=False,
- use_depthwise=use_depthwise,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg))
-
- # build bottom-up blocks
- self.downsamples = nn.ModuleList()
- self.bottom_up_blocks = nn.ModuleList()
- for idx in range(len(in_channels) - 1):
- self.downsamples.append(
- ConvModule(
- in_channels[idx],
- in_channels[idx],
- 3,
- stride=2,
- padding=1,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg))
- self.bottom_up_blocks.append(
- CSPLayer(
- in_channels[idx] * 2,
- in_channels[idx + 1],
- num_blocks=num_csp_blocks,
- add_identity=False,
- use_depthwise=use_depthwise,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg))
-
- self.out_convs = nn.ModuleList()
- for i in range(len(in_channels)):
- self.out_convs.append(
- ConvModule(
- in_channels[i],
- out_channels,
- 1,
- conv_cfg=conv_cfg,
- norm_cfg=norm_cfg,
- act_cfg=act_cfg))
-
- def forward(self, inputs):
- """
- Args:
- inputs (tuple[Tensor]): input features.
-
- Returns:
- tuple[Tensor]: YOLOXPAFPN features.
- """
- assert len(inputs) == len(self.in_channels)
-
- # top-down path
- inner_outs = [inputs[-1]]
- for idx in range(len(self.in_channels) - 1, 0, -1):
- feat_heigh = inner_outs[0]
- feat_low = inputs[idx - 1]
- feat_heigh = self.reduce_layers[len(self.in_channels) - 1 - idx](
- feat_heigh)
- inner_outs[0] = feat_heigh
-
- upsample_feat = self.upsample(feat_heigh)
-
- inner_out = self.top_down_blocks[len(self.in_channels) - 1 - idx](
- torch.cat([upsample_feat, feat_low], 1))
- inner_outs.insert(0, inner_out)
-
- # bottom-up path
- outs = [inner_outs[0]]
- for idx in range(len(self.in_channels) - 1):
- feat_low = outs[-1]
- feat_height = inner_outs[idx + 1]
- downsample_feat = self.downsamples[idx](feat_low)
- out = self.bottom_up_blocks[idx](
- torch.cat([downsample_feat, feat_height], 1))
- outs.append(out)
-
- # out convs
- for idx, conv in enumerate(self.out_convs):
- outs[idx] = conv(outs[idx])
-
- return tuple(outs)
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/priors.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/priors.py
deleted file mode 100755
index 8eb2fde..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/priors.py
+++ /dev/null
@@ -1,225 +0,0 @@
-import torch
-import numpy as np
-from torch.nn.modules.utils import _pair
-
-
-class MlvlPointGenerator:
- """Standard points generator for multi-level (Mlvl) feature maps in 2D
- points-based detectors.
-
- Args:
- strides (list[int] | list[tuple[int, int]]): Strides of anchors
- in multiple feature levels in order (w, h).
- offset (float): The offset of points, the value is normalized with
- corresponding stride. Defaults to 0.5.
- """
-
- def __init__(self, strides, offset=0.5):
- self.strides = [_pair(stride) for stride in strides]
- self.offset = offset
-
- @property
- def num_levels(self):
- """int: number of feature levels that the generator will be applied"""
- return len(self.strides)
-
- @property
- def num_base_priors(self):
- """list[int]: The number of priors (points) at a point
- on the feature grid"""
- return [1 for _ in range(len(self.strides))]
-
- def _meshgrid(self, x, y, row_major=True):
- yy, xx = torch.meshgrid(y, x)
- if row_major:
- # warning .flatten() would cause error in ONNX exporting
- # have to use reshape here
- return xx.flatten(), yy.flatten()
-
- else:
- return yy.flatten(), xx.flatten()
-
- def grid_priors(self,
- featmap_sizes,
- dtype=torch.float32,
- device='cuda',
- with_stride=False):
- """Generate grid points of multiple feature levels.
-
- Args:
- featmap_sizes (list[tuple]): List of feature map sizes in
- multiple feature levels, each size arrange as
- as (h, w).
- dtype (:obj:`dtype`): Dtype of priors. Default: torch.float32.
- device (str): The device where the anchors will be put on.
- with_stride (bool): Whether to concatenate the stride to
- the last dimension of points.
-
- Return:
- list[torch.Tensor]: Points of multiple feature levels.
- The sizes of each tensor should be (N, 2) when with stride is
- ``False``, where N = width * height, width and height
- are the sizes of the corresponding feature level,
- and the last dimension 2 represent (coord_x, coord_y),
- otherwise the shape should be (N, 4),
- and the last dimension 4 represent
- (coord_x, coord_y, stride_w, stride_h).
- """
-
- assert self.num_levels == len(featmap_sizes)
- multi_level_priors = []
- for i in range(self.num_levels):
- priors = self.single_level_grid_priors(
- featmap_sizes[i],
- level_idx=i,
- dtype=dtype,
- device=device,
- with_stride=with_stride)
- multi_level_priors.append(priors)
- return multi_level_priors
-
- def single_level_grid_priors(self,
- featmap_size,
- level_idx,
- dtype=torch.float32,
- device='cuda',
- with_stride=False):
- """Generate grid Points of a single level.
-
- Note:
- This function is usually called by method ``self.grid_priors``.
-
- Args:
- featmap_size (tuple[int]): Size of the feature maps, arrange as
- (h, w).
- level_idx (int): The index of corresponding feature map level.
- dtype (:obj:`dtype`): Dtype of priors. Default: torch.float32.
- device (str, optional): The device the tensor will be put on.
- Defaults to 'cuda'.
- with_stride (bool): Concatenate the stride to the last dimension
- of points.
-
- Return:
- Tensor: Points of single feature levels.
- The shape of tensor should be (N, 2) when with stride is
- ``False``, where N = width * height, width and height
- are the sizes of the corresponding feature level,
- and the last dimension 2 represent (coord_x, coord_y),
- otherwise the shape should be (N, 4),
- and the last dimension 4 represent
- (coord_x, coord_y, stride_w, stride_h).
- """
- feat_h, feat_w = featmap_size
- stride_w, stride_h = self.strides[level_idx]
- shift_x = (torch.arange(0, feat_w, device=device) +
- self.offset) * stride_w
- # keep featmap_size as Tensor instead of int, so that we
- # can convert to ONNX correctly
- shift_x = shift_x.to(dtype)
-
- shift_y = (torch.arange(0, feat_h, device=device) +
- self.offset) * stride_h
- # keep featmap_size as Tensor instead of int, so that we
- # can convert to ONNX correctly
- shift_y = shift_y.to(dtype)
- shift_xx, shift_yy = self._meshgrid(shift_x, shift_y)
- if not with_stride:
- shifts = torch.stack([shift_xx, shift_yy], dim=-1)
- else:
- # use `shape[0]` instead of `len(shift_xx)` for ONNX export
- stride_w = shift_xx.new_full((shift_xx.shape[0], ),
- stride_w).to(dtype)
- stride_h = shift_xx.new_full((shift_yy.shape[0], ),
- stride_h).to(dtype)
- shifts = torch.stack([shift_xx, shift_yy, stride_w, stride_h],
- dim=-1)
- all_points = shifts.to(device)
- return all_points
-
- def valid_flags(self, featmap_sizes, pad_shape, device='cuda'):
- """Generate valid flags of points of multiple feature levels.
-
- Args:
- featmap_sizes (list(tuple)): List of feature map sizes in
- multiple feature levels, each size arrange as
- as (h, w).
- pad_shape (tuple(int)): The padded shape of the image,
- arrange as (h, w).
- device (str): The device where the anchors will be put on.
-
- Return:
- list(torch.Tensor): Valid flags of points of multiple levels.
- """
- assert self.num_levels == len(featmap_sizes)
- multi_level_flags = []
- for i in range(self.num_levels):
- point_stride = self.strides[i]
- feat_h, feat_w = featmap_sizes[i]
- h, w = pad_shape[:2]
- valid_feat_h = min(int(np.ceil(h / point_stride[1])), feat_h)
- valid_feat_w = min(int(np.ceil(w / point_stride[0])), feat_w)
- flags = self.single_level_valid_flags((feat_h, feat_w),
- (valid_feat_h, valid_feat_w),
- device=device)
- multi_level_flags.append(flags)
- return multi_level_flags
-
- def single_level_valid_flags(self,
- featmap_size,
- valid_size,
- device='cuda'):
- """Generate the valid flags of points of a single feature map.
-
- Args:
- featmap_size (tuple[int]): The size of feature maps, arrange as
- as (h, w).
- valid_size (tuple[int]): The valid size of the feature maps.
- The size arrange as as (h, w).
- device (str, optional): The device where the flags will be put on.
- Defaults to 'cuda'.
-
- Returns:
- torch.Tensor: The valid flags of each points in a single level \
- feature map.
- """
- feat_h, feat_w = featmap_size
- valid_h, valid_w = valid_size
- assert valid_h <= feat_h and valid_w <= feat_w
- valid_x = torch.zeros(feat_w, dtype=torch.bool, device=device)
- valid_y = torch.zeros(feat_h, dtype=torch.bool, device=device)
- valid_x[:valid_w] = 1
- valid_y[:valid_h] = 1
- valid_xx, valid_yy = self._meshgrid(valid_x, valid_y)
- valid = valid_xx & valid_yy
- return valid
-
- def sparse_priors(self,
- prior_idxs,
- featmap_size,
- level_idx,
- dtype=torch.float32,
- device='cuda'):
- """Generate sparse points according to the ``prior_idxs``.
-
- Args:
- prior_idxs (Tensor): The index of corresponding anchors
- in the feature map.
- featmap_size (tuple[int]): feature map size arrange as (w, h).
- level_idx (int): The level index of corresponding feature
- map.
- dtype (obj:`torch.dtype`): Date type of points. Defaults to
- ``torch.float32``.
- device (obj:`torch.device`): The device where the points is
- located.
- Returns:
- Tensor: Anchor with shape (N, 2), N should be equal to
- the length of ``prior_idxs``. And last dimension
- 2 represent (coord_x, coord_y).
- """
- height, width = featmap_size
- x = (prior_idxs % width + self.offset) * self.strides[level_idx][0]
- y = ((prior_idxs // width) % height +
- self.offset) * self.strides[level_idx][1]
- prioris = torch.stack([x, y], 1).to(dtype)
- prioris = prioris.to(device)
- return prioris
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/transform.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/transform.py
deleted file mode 100755
index fda7ab9..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/transform.py
+++ /dev/null
@@ -1,81 +0,0 @@
-import mmcv
-import numpy as np
-import cv2
-import torch
-
-
-class DetectorDataPipeline:
-
- def __init__(self,
- img_scale,
- device):
- self.scale = img_scale
- self.device = device
-
- def load(self, img):
- if isinstance(img, str):
- return cv2.imread(img)
- elif isinstance(img, np.ndarray):
- return img
- else:
- raise ValueError(f'img input must be a str/np.ndarray, got {type(img)}')
-
- def resize(self, img):
- origin_shape = img.shape[:2]
- img = mmcv.imrescale(img,
- self.scale,
- return_scale=False,
- interpolation='bilinear',
- backend='cv2')
-
- return img, origin_shape, np.array(self.scale)
-
- def pad(self, img):
- if self.scale is not None:
- width = max(self.scale[1] - img.shape[1], 0)
- height = max(self.scale[0] - img.shape[0], 0)
- padding = (0, 0, width, height)
-
- img = cv2.copyMakeBorder(img,
- padding[1],
- padding[3],
- padding[0],
- padding[2],
- cv2.BORDER_CONSTANT,
- value=(114, 114, 114,))
-
- return img
-
- def to_tensor(self, img):
-
- img = torch.from_numpy(img.astype(np.float32)).permute(2,0,1).unsqueeze(0)
- img = img.to(device=self.device)
-
- return img
-
- def __call__(self, img):
- img = self.load(img)
- img, origin_shape, new_shape = self.resize(img)
- img = self.pad(img)
- img = self.to_tensor(img)
-
- return img, origin_shape, new_shape
-
-
-class AutoRotateDetectorDataPipeline(DetectorDataPipeline):
-
- def __call__(self, img):
- img = self.load(img)
- imgs = []
- imgs_np = []
-
- for flag in (None, cv2.ROTATE_90_CLOCKWISE, cv2.ROTATE_180, cv2.ROTATE_90_COUNTERCLOCKWISE):
- img_t = img if flag is None else cv2.rotate(img, flag)
- imgs_np.append(img_t)
- img_t, _, _ = self.resize(img_t)
- img_t = self.pad(img_t)
- img_t = self.to_tensor(img_t)
-
- imgs.append(img_t)
-
- return imgs, imgs_np
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/version.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/version.py
deleted file mode 100755
index 10939f0..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/sdsvtd/version.py
+++ /dev/null
@@ -1 +0,0 @@
-__version__ = '0.1.2'
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/setup.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/setup.py
deleted file mode 100755
index a2e04db..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtd/setup.py
+++ /dev/null
@@ -1,186 +0,0 @@
-import os
-import os.path as osp
-import shutil
-import sys
-import warnings
-from setuptools import find_packages, setup
-
-
-def readme():
- with open('README.md', encoding='utf-8') as f:
- content = f.read()
- return content
-
-
-version_file = 'sdsvtd/version.py'
-is_windows = sys.platform == 'win32'
-
-
-def add_mim_extention():
- """Add extra files that are required to support MIM into the package.
-
- These files will be added by creating a symlink to the originals if the
- package is installed in `editable` mode (e.g. pip install -e .), or by
- copying from the originals otherwise.
- """
-
- # parse installment mode
- if 'develop' in sys.argv:
- # installed by `pip install -e .`
- mode = 'symlink'
- elif 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
- # installed by `pip install .`
- # or create source distribution by `python setup.py sdist`
- mode = 'copy'
- else:
- return
-
- filenames = ['tools', 'configs', 'model-index.yml']
- repo_path = osp.dirname(__file__)
- mim_path = osp.join(repo_path, 'mmocr', '.mim')
- os.makedirs(mim_path, exist_ok=True)
-
- for filename in filenames:
- if osp.exists(filename):
- src_path = osp.join(repo_path, filename)
- tar_path = osp.join(mim_path, filename)
-
- if osp.isfile(tar_path) or osp.islink(tar_path):
- os.remove(tar_path)
- elif osp.isdir(tar_path):
- shutil.rmtree(tar_path)
-
- if mode == 'symlink':
- src_relpath = osp.relpath(src_path, osp.dirname(tar_path))
- try:
- os.symlink(src_relpath, tar_path)
- except OSError:
- # Creating a symbolic link on windows may raise an
- # `OSError: [WinError 1314]` due to privilege. If
- # the error happens, the src file will be copied
- mode = 'copy'
- warnings.warn(
- f'Failed to create a symbolic link for {src_relpath}, '
- f'and it will be copied to {tar_path}')
- else:
- continue
-
- if mode == 'copy':
- if osp.isfile(src_path):
- shutil.copyfile(src_path, tar_path)
- elif osp.isdir(src_path):
- shutil.copytree(src_path, tar_path)
- else:
- warnings.warn(f'Cannot copy file {src_path}.')
- else:
- raise ValueError(f'Invalid mode {mode}')
-
-
-def get_version():
- with open(version_file, 'r') as f:
- exec(compile(f.read(), version_file, 'exec'))
- import sys
-
- # return short version for sdist
- if 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
- return locals()['short_version']
- else:
- return locals()['__version__']
-
-
-def parse_requirements(fname='requirements.txt', with_version=True):
- """Parse the package dependencies listed in a requirements file but strip
- specific version information.
-
- Args:
- fname (str): Path to requirements file.
- with_version (bool, default=False): If True, include version specs.
- Returns:
- info (list[str]): List of requirements items.
- CommandLine:
- python -c "import setup; print(setup.parse_requirements())"
- """
- import re
- import sys
- from os.path import exists
- require_fpath = fname
-
- def parse_line(line):
- """Parse information from a line in a requirements text file."""
- if line.startswith('-r '):
- # Allow specifying requirements in other files
- target = line.split(' ')[1]
- for info in parse_require_file(target):
- yield info
- else:
- info = {'line': line}
- if line.startswith('-e '):
- info['package'] = line.split('#egg=')[1]
- else:
- # Remove versioning from the package
- pat = '(' + '|'.join(['>=', '==', '>']) + ')'
- parts = re.split(pat, line, maxsplit=1)
- parts = [p.strip() for p in parts]
-
- info['package'] = parts[0]
- if len(parts) > 1:
- op, rest = parts[1:]
- if ';' in rest:
- # Handle platform specific dependencies
- # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
- version, platform_deps = map(str.strip,
- rest.split(';'))
- info['platform_deps'] = platform_deps
- else:
- version = rest # NOQA
- info['version'] = (op, version)
- yield info
-
- def parse_require_file(fpath):
- with open(fpath, 'r') as f:
- for line in f.readlines():
- line = line.strip()
- if line and not line.startswith('#'):
- for info in parse_line(line):
- yield info
-
- def gen_packages_items():
- if exists(require_fpath):
- for info in parse_require_file(require_fpath):
- parts = [info['package']]
- if with_version and 'version' in info:
- parts.extend(info['version'])
- if not sys.version.startswith('3.4'):
- # apparently package_deps are broken in 3.4
- platform_deps = info.get('platform_deps')
- if platform_deps is not None:
- parts.append(';' + platform_deps)
- item = ''.join(parts)
- yield item
-
- packages = list(gen_packages_items())
- return packages
-
-
-if __name__ == '__main__':
- setup(
- name='sdsvtd',
- version=get_version(),
- description='SDSV OCR Team Text Detection',
- long_description=readme(),
- long_description_content_type='text/markdown',
- packages=find_packages(exclude=('configs', 'tools', 'demo')),
- include_package_data=True,
- classifiers=[
- 'Development Status :: 4 - Beta',
- 'License :: OSI Approved :: Apache Software License',
- 'Operating System :: OS Independent',
- 'Programming Language :: Python :: 3',
- 'Programming Language :: Python :: 3.6',
- 'Programming Language :: Python :: 3.7',
- 'Programming Language :: Python :: 3.8',
- 'Programming Language :: Python :: 3.9',
- ],
- license='Apache License 2.0',
- install_requires=parse_requirements('requirements.txt'),
- zip_safe=False)
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/.gitignore b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/.gitignore
deleted file mode 100755
index a8c1759..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-# Builds
-*.egg-info
-__pycache__
-
-# Checkpoint
-hub
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/LICENSE b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/LICENSE
deleted file mode 100755
index 92b370f..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/LICENSE
+++ /dev/null
@@ -1,674 +0,0 @@
-GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc.
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Use with the GNU Affero General Public License.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C)
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
-
-Also add information on how to contact you by electronic and paper mail.
-
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- Copyright (C)
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-.
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/README.md b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/README.md
deleted file mode 100755
index 2cabc83..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/README.md
+++ /dev/null
@@ -1,76 +0,0 @@
-## Introduction
-This repo serve as source code storage for the Standalone SATRN Text Recognizer packages.
-Installing this package requires 3 additional packages: PyTorch, MMCV, and colorama.
-
-
-## Installation
-```shell
-conda create -n sdsvtr-env python=3.8
-conda activate sdsvtr-env
-conda install pytorch torchvision pytorch-cuda=11.6 -c pytorch -c nvidia
-pip install -U openmim
-mim install mmcv-full
-pip install colorama
-git clone https://github.com/moewiee/sdsvtr.git
-cd sdsvtr
-pip install -v -e .
-```
-
-## Basic Usage
-```python
-from sdsvtr import StandaloneSATRNRunner
-runner = StandaloneSATRNRunner(version='satrn-lite-general-pretrain-20230106', return_confident=False, use_cuda=False)
-```
-
-The `version` parameter accepts version names declared in `sdsvtr.factory.online_model_factory` or a local path such as `$DIR\model.pth`. To check for available versions in the hub, run:
-```python
-import sdsvtr
-print(sdsvtr.__hub_available_versions__)
-```
-
-Naturally, a `StandaloneSATRNRunner` instance assumes the input to be one of the following: an instance of `np.ndarray`, an instance of `str`, a list of `np.ndarray`, or a list of `str`, for examples:
-```python
-import numpy as np
-from sdsvtr import StandaloneSATRNRunner
-runner = StandaloneSATRNRunner(version='satrn-lite-general-pretrain-20230106', return_confident=False, use_cuda=False)
-
-dummy_list = [np.ndarray((32,128,3)) for _ in range(100)]
-result = runner(dummy_list)
-```
-
-To run with a specific batchsize, try:
-```python
-import numpy as np
-from sdsvtr import StandaloneSATRNRunner
-runner = StandaloneSATRNRunner(version='satrn-lite-general-pretrain-20230106', return_confident=False, device='cuda:0')
-
-dummy_list = [np.ndarray(1,3,32,128) for _ in range(100)]
-bs = min(32, len(imageFiles)) # batchsize = 32
-
-all_results = []
-while len(dummy_list) > 0:
- dummy_batch = dummy_list[:bs]
- dummy_list = dummy_list[bs:]
- all_results += runner(dummy_batch)
-```
-
-## Version Changelog
-* **[0.0.1]**
-Initial version with specified features.
-
-
-* **[0.0.2]**
-Update online model hub.
-
-
-* **[0.0.3]**
-Update API now able to inference with 4 types of inputs: list/instance of `np.ndarray`/`str`
-Update API interface with `return_confident` parameter.
-Update `wget` check and `sha256` check for model hub retrieval.
-
-* **[0.0.4]**
-Update decoder module with EarlyStopping mechanism to possibly improve inference speed on short sequences.
-Update API interface with optional argument `max_seq_len_overwrite` to overwrite checkpoint's `max_seq_len` config.
-
-* **[0.0.5]**
-Allow inference on a specific device
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/requirements.txt b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/requirements.txt
deleted file mode 100755
index f4a74db..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/requirements.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-torch
-colorama
-mmcv-full
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/__init__.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/__init__.py
deleted file mode 100755
index dd8470d..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from .api import StandaloneSATRNRunner
-from .version import __version__
-from .factory import __hub_available_versions__
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/api.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/api.py
deleted file mode 100755
index 566a904..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/api.py
+++ /dev/null
@@ -1,106 +0,0 @@
-
-import torch
-import torch.nn as nn
-
-from colorama import Fore, Style
-
-from .converter import AttnConvertor
-from .backbone import ResNetABI
-from .encoder import SatrnEncoder
-from .decoder import NRTRDecoder
-from .transform import DataPipelineSATRN
-from .fp16_utils import patch_norm_fp32
-from .factory import _get as get_version
-
-
-class SATRN(nn.Module):
- """Standalone implementation for SATRN encode-decode recognizer."""
-
- def __init__(self,
- version,
- return_confident=False,
- device='cpu',
- max_seq_len_overwrite=None):
-
- super().__init__()
-
- checkpoint = get_version(version)
-
- pt = torch.load(checkpoint, 'cpu')
- if device == 'cpu':
- print(Fore.RED + 'Warning: You are using CPU inference method. Init with device=cuda: to run with CUDA method.' + Style.RESET_ALL)
-
- self.pipeline = DataPipelineSATRN(**pt['pipeline_args'], device=device)
-
- # Convertor
- self.label_convertor = AttnConvertor(**pt['label_convertor_args'], return_confident=return_confident)
-
- # Backbone
- self.backbone = ResNetABI(**pt['backbone_args'])
-
- # Encoder module
- self.encoder = SatrnEncoder(**pt['encoder_args'])
-
- # Decoder module
- decoder_max_seq_len = max_seq_len_overwrite if max_seq_len_overwrite is not None else pt['max_seq_len']
- self.decoder = NRTRDecoder(
- **pt['decoder_args'],
- max_seq_len=decoder_max_seq_len,
- num_classes=self.label_convertor.num_classes(),
- start_idx=self.label_convertor.start_idx,
- padding_idx=self.label_convertor.padding_idx,
- return_confident=return_confident,
- end_idx=self.label_convertor.end_idx
- )
-
- self.load_state_dict(pt['state_dict'], strict=True)
- print(f'Text recognition from version {version}.')
-
- if device != 'cpu':
- self = self.to(device)
- self = self.half()
- patch_norm_fp32(self)
-
- self.eval()
- for param in self.parameters():
- param.requires_grad = False
-
- def extract_feat(self, img):
- x = self.backbone(img)
-
- return x
-
- def forward(self, img):
- """Test function with test time augmentation.
-
- Args:
- imgs (torch.Tensor): Image input tensor.
-
- Returns:
- list[str]: Text label result of each image.
- """
- img = self.pipeline(img)
- feat = self.extract_feat(img)
- out_enc = self.encoder(feat)
- out_dec = self.decoder(out_enc).cpu().numpy()
- label_strings = self.label_convertor(out_dec)
-
- return label_strings
-
-
-class StandaloneSATRNRunner:
- def __init__(self,
- version,
- return_confident,
- device='cpu',
- max_seq_len_overwrite=None):
- self.device = device
- self.model = SATRN(version=version,
- return_confident=return_confident,
- device=self.device,
- max_seq_len_overwrite=max_seq_len_overwrite)
-
- def __call__(self, imgs):
- results = self.model(imgs)
-
- return results
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/backbone.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/backbone.py
deleted file mode 100755
index 29c2509..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/backbone.py
+++ /dev/null
@@ -1,159 +0,0 @@
-import torch.nn as nn
-
-def conv3x3(in_planes, out_planes, stride=1):
- """3x3 convolution with padding."""
- return nn.Conv2d(
- in_planes,
- out_planes,
- kernel_size=3,
- stride=stride,
- padding=1,
- bias=False)
-
-
-def conv1x1(in_planes, out_planes):
- """1x1 convolution with padding."""
- return nn.Conv2d(
- in_planes, out_planes, kernel_size=1, stride=1, padding=0, bias=False)
-
-
-class BasicBlock(nn.Module):
-
- expansion = 1
-
- def __init__(self,
- inplanes,
- planes,
- stride=1,
- downsample=None,
- use_conv1x1=False):
- super(BasicBlock, self).__init__()
-
- if use_conv1x1:
- self.conv1 = conv1x1(inplanes, planes)
- self.conv2 = conv3x3(planes, planes * self.expansion, stride)
- else:
- self.conv1 = conv3x3(inplanes, planes, stride)
- self.conv2 = conv3x3(planes, planes * self.expansion)
-
- self.planes = planes
- self.bn1 = nn.BatchNorm2d(planes)
- self.relu = nn.ReLU(inplace=True)
- self.bn2 = nn.BatchNorm2d(planes * self.expansion)
- self.downsample = downsample
- self.stride = stride
-
- def forward(self, x):
- residual = x
- out = self.conv1(x)
- out = self.bn1(out)
- out = self.relu(out)
- out = self.conv2(out)
- out = self.bn2(out)
- if self.downsample is not None:
- residual = self.downsample(x)
- out += residual
- out = self.relu(out)
-
- return out
-
-class ResNetABI(nn.Module):
- """Implement ResNet backbone for text recognition, modified from `ResNet.
-
- `_ and
- ``_
-
- Args:
- in_channels (int): Number of channels of input image tensor.
- stem_channels (int): Number of stem channels.
- base_channels (int): Number of base channels.
- arch_settings (list[int]): List of BasicBlock number for each stage.
- strides (Sequence[int]): Strides of the first block of each stage.
- out_indices (None | Sequence[int]): Indices of output stages. If not
- specified, only the last stage will be returned.
- last_stage_pool (bool): If True, add `MaxPool2d` layer to last stage.
- """
-
- def __init__(self,
- in_channels=3,
- stem_channels=32,
- base_channels=32,
- arch_settings=[3, 4, 6, 6, 3],
- strides=[2, 1, 2, 1, 1],
- out_indices=None,
- last_stage_pool=False):
- super().__init__()
-
- self.out_indices = out_indices
- self.last_stage_pool = last_stage_pool
- self.block = BasicBlock
- self.inplanes = stem_channels
-
- self._make_stem_layer(in_channels, stem_channels)
-
- self.res_layers = []
- planes = base_channels
- for i, num_blocks in enumerate(arch_settings):
- stride = strides[i]
- res_layer = self._make_layer(
- block=self.block,
- inplanes=self.inplanes,
- planes=planes,
- blocks=num_blocks,
- stride=stride)
- self.inplanes = planes * self.block.expansion
- planes *= 2
- layer_name = f'layer{i + 1}'
- self.add_module(layer_name, res_layer)
- self.res_layers.append(layer_name)
-
- def _make_layer(self, block, inplanes, planes, blocks, stride=1):
- layers = []
- downsample = None
- if stride != 1 or inplanes != planes:
- downsample = nn.Sequential(
- nn.Conv2d(inplanes, planes, 1, stride, bias=False),
- nn.BatchNorm2d(planes),
- )
- layers.append(
- block(
- inplanes,
- planes,
- use_conv1x1=True,
- stride=stride,
- downsample=downsample))
- inplanes = planes
- for _ in range(1, blocks):
- layers.append(block(inplanes, planes, use_conv1x1=True))
-
- return nn.Sequential(*layers)
-
- def _make_stem_layer(self, in_channels, stem_channels):
- self.conv1 = nn.Conv2d(
- in_channels, stem_channels, kernel_size=3, stride=1, padding=1)
- self.bn1 = nn.BatchNorm2d(stem_channels)
- self.relu1 = nn.ReLU(inplace=True)
-
- def forward(self, x):
- """
- Args:
- x (Tensor): Image tensor of shape :math:`(N, 3, H, W)`.
-
- Returns:
- Tensor or list[Tensor]: Feature tensor. Its shape depends on
- ResNetABI's config. It can be a list of feature outputs at specific
- layers if ``out_indices`` is specified.
- """
-
- x = self.conv1(x)
- x = self.bn1(x)
- x = self.relu1(x)
-
- outs = []
- for i, layer_name in enumerate(self.res_layers):
- res_layer = getattr(self, layer_name)
- x = res_layer(x)
- if self.out_indices and i in self.out_indices:
- outs.append(x)
-
- return tuple(outs) if self.out_indices else x
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/conv.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/conv.py
deleted file mode 100755
index 950ec0c..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/conv.py
+++ /dev/null
@@ -1,173 +0,0 @@
-import warnings
-import torch.nn as nn
-from torch.nn.modules.instancenorm import _InstanceNorm
-from torch.nn.modules.batchnorm import _BatchNorm
-from mmcv.cnn import build_padding_layer, build_conv_layer, build_norm_layer, build_activation_layer
-
-class ConvModule(nn.Module):
- """A conv block that bundles conv/norm/activation layers.
-
- This block simplifies the usage of convolution layers, which are commonly
- used with a norm layer (e.g., BatchNorm) and activation layer (e.g., ReLU).
- It is based upon three build methods: `build_conv_layer()`,
- `build_norm_layer()` and `build_activation_layer()`.
-
- Besides, we add some additional features in this module.
- 1. Automatically set `bias` of the conv layer.
- 2. Spectral norm is supported.
- 3. More padding modes are supported. Before PyTorch 1.5, nn.Conv2d only
- supports zero and circular padding, and we add "reflect" padding mode.
-
- Args:
- in_channels (int): Number of channels in the input feature map.
- Same as that in ``nn._ConvNd``.
- out_channels (int): Number of channels produced by the convolution.
- Same as that in ``nn._ConvNd``.
- kernel_size (int | tuple[int]): Size of the convolving kernel.
- Same as that in ``nn._ConvNd``.
- stride (int | tuple[int]): Stride of the convolution.
- Same as that in ``nn._ConvNd``.
- padding (int | tuple[int]): Zero-padding added to both sides of
- the input. Same as that in ``nn._ConvNd``.
- dilation (int | tuple[int]): Spacing between kernel elements.
- Same as that in ``nn._ConvNd``.
- groups (int): Number of blocked connections from input channels to
- output channels. Same as that in ``nn._ConvNd``.
- bias (bool | str): If specified as `auto`, it will be decided by the
- norm_cfg. Bias will be set as True if `norm_cfg` is None, otherwise
- False. Default: "auto".
- conv_cfg (dict): Config dict for convolution layer. Default: None,
- which means using conv2d.
- norm_cfg (dict): Config dict for normalization layer. Default: None.
- act_cfg (dict): Config dict for activation layer.
- Default: dict(type='ReLU').
- inplace (bool): Whether to use inplace mode for activation.
- Default: True.
- with_spectral_norm (bool): Whether use spectral norm in conv module.
- Default: False.
- padding_mode (str): If the `padding_mode` has not been supported by
- current `Conv2d` in PyTorch, we will use our own padding layer
- instead. Currently, we support ['zeros', 'circular'] with official
- implementation and ['reflect'] with our own implementation.
- Default: 'zeros'.
- order (tuple[str]): The order of conv/norm/activation layers. It is a
- sequence of "conv", "norm" and "act". Common examples are
- ("conv", "norm", "act") and ("act", "conv", "norm").
- Default: ('conv', 'norm', 'act').
- """
-
- _abbr_ = 'conv_block'
-
- def __init__(self,
- in_channels,
- out_channels,
- kernel_size,
- stride=1,
- padding=0,
- dilation=1,
- groups=1,
- bias='auto',
- conv_cfg=None,
- norm_cfg=None,
- act_cfg=dict(type='ReLU'),
- inplace=True,
- with_spectral_norm=False,
- padding_mode='zeros',
- order=('conv', 'norm', 'act')):
- super(ConvModule, self).__init__()
- assert conv_cfg is None or isinstance(conv_cfg, dict)
- assert norm_cfg is None or isinstance(norm_cfg, dict)
- assert act_cfg is None or isinstance(act_cfg, dict)
- official_padding_mode = ['zeros', 'circular']
- self.conv_cfg = conv_cfg
- self.norm_cfg = norm_cfg
- self.act_cfg = act_cfg
- self.inplace = inplace
- self.with_spectral_norm = with_spectral_norm
- self.with_explicit_padding = padding_mode not in official_padding_mode
- self.order = order
- assert isinstance(self.order, tuple) and len(self.order) == 3
- assert set(order) == set(['conv', 'norm', 'act'])
-
- self.with_norm = norm_cfg is not None
- self.with_activation = act_cfg is not None
- # if the conv layer is before a norm layer, bias is unnecessary.
- if bias == 'auto':
- bias = not self.with_norm
- self.with_bias = bias
-
- if self.with_explicit_padding:
- pad_cfg = dict(type=padding_mode)
- self.padding_layer = build_padding_layer(pad_cfg, padding)
-
- # reset padding to 0 for conv module
- conv_padding = 0 if self.with_explicit_padding else padding
- # build convolution layer
- self.conv = build_conv_layer(
- conv_cfg,
- in_channels,
- out_channels,
- kernel_size,
- stride=stride,
- padding=conv_padding,
- dilation=dilation,
- groups=groups,
- bias=bias)
- # export the attributes of self.conv to a higher level for convenience
- self.in_channels = self.conv.in_channels
- self.out_channels = self.conv.out_channels
- self.kernel_size = self.conv.kernel_size
- self.stride = self.conv.stride
- self.padding = padding
- self.dilation = self.conv.dilation
- self.transposed = self.conv.transposed
- self.output_padding = self.conv.output_padding
- self.groups = self.conv.groups
-
- if self.with_spectral_norm:
- self.conv = nn.utils.spectral_norm(self.conv)
-
- # build normalization layers
- if self.with_norm:
- # norm layer is after conv layer
- if order.index('norm') > order.index('conv'):
- norm_channels = out_channels
- else:
- norm_channels = in_channels
- self.norm_name, norm = build_norm_layer(norm_cfg, norm_channels)
- self.add_module(self.norm_name, norm)
- if self.with_bias:
- if isinstance(norm, (_BatchNorm, _InstanceNorm)):
- warnings.warn(
- 'Unnecessary conv bias before batch/instance norm')
- else:
- self.norm_name = None
-
- # build activation layer
- if self.with_activation:
- act_cfg_ = act_cfg.copy()
- # nn.Tanh has no 'inplace' argument
- if act_cfg_['type'] not in [
- 'Tanh', 'PReLU', 'Sigmoid', 'HSigmoid', 'Swish'
- ]:
- act_cfg_.setdefault('inplace', inplace)
- self.activate = build_activation_layer(act_cfg_)
-
- @property
- def norm(self):
- if self.norm_name:
- return getattr(self, self.norm_name)
- else:
- return None
-
- def forward(self, x, activate=True, norm=True):
- for layer in self.order:
- if layer == 'conv':
- if self.with_explicit_padding:
- x = self.padding_layer(x)
- x = self.conv(x)
- elif layer == 'norm' and norm and self.with_norm:
- x = self.norm(x)
- elif layer == 'act' and activate and self.with_activation:
- x = self.activate(x)
- return x
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/converter.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/converter.py
deleted file mode 100755
index 4d9bf82..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/converter.py
+++ /dev/null
@@ -1,152 +0,0 @@
-import torch
-import numpy as np
-
-class BaseConvertor:
- """Convert between text, index and tensor for text recognize pipeline.
-
- Args:
- dict_type (str): Type of dict, options are 'DICT36', 'DICT37', 'DICT90'
- and 'DICT91'.
- dict_file (None|str): Character dict file path. If not none,
- the dict_file is of higher priority than dict_type.
- dict_list (None|list[str]): Character list. If not none, the list
- is of higher priority than dict_type, but lower than dict_file.
- """
- start_idx = end_idx = padding_idx = 0
- unknown_idx = None
- lower = False
-
- DICT36 = tuple('0123456789abcdefghijklmnopqrstuvwxyz')
- DICT63 = tuple('0123456789abcdefghijklmnopqrstuvwxyz'
- 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
- DICT90 = tuple('0123456789abcdefghijklmnopqrstuvwxyz'
- 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()'
- '*+,-./:;<=>?@[\\]_`~')
- DICT131 = tuple('0123456789abcdefghijklmnopqrstuvwxyz'
- '!"#$%&\'()'
- '*+,-./:;<=>?@[\\]_`~'
- 'ạảãàáâậầấẩẫăắằặẳẵóòọõỏôộổỗồốơờớợởỡéèẻẹẽêếềệểễúùụủũưựữửừứíìịỉĩýỳỷỵỹđ')
- DICT224 = tuple('0123456789abcdefghijklmnopqrstuvwxyz'
- 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()'
- '*+,-./:;<=>?@[\\]_`~{}|^ ̂'
- 'ạảãàáâậầấẩẫăắằặẳẵóòọõỏôộổỗồốơờớợởỡéèẻẹẽêếềệểễúùụủũưựữửừứíìịỉĩýỳỷỵỹđ'
- 'ẠẢÃÀÁÂẬẦẤẨẪĂẮẰẶẲẴÓÒỌÕỎÔỘỔỖỒỐƠỜỚỢỞỠÉÈẺẸẼÊẾỀỆỂỄÚÙỤỦŨƯỰỮỬỪỨÍÌỊỈĨÝỲỶỴỸĐ✪')
-
- def __init__(self, dict_type='DICT90'):
- assert dict_type in ('DICT36', 'DICT63', 'DICT90', 'DICT131', 'DICT224')
- self.idx2char = []
-
- if dict_type == 'DICT36':
- self.idx2char = list(self.DICT36)
- elif dict_type == 'DICT63':
- self.idx2char = list(self.DICT63)
- elif dict_type == 'DICT90':
- self.idx2char = list(self.DICT90)
- elif dict_type == 'DICT131':
- self.idx2char = list(self.DICT131)
- elif dict_type == 'DICT224':
- self.idx2char = list(self.DICT224)
- else:
- raise ('Dictonary not implemented')
-
- assert len(set(self.idx2char)) == len(self.idx2char), \
- 'Invalid dictionary: Has duplicated characters.'
-
- self.char2idx = {char: idx for idx, char in enumerate(self.idx2char)}
-
- def num_classes(self):
- """Number of output classes."""
- return len(self.idx2char)
-
-
-class AttnConvertor(BaseConvertor):
- """Convert between text, index and tensor for encoder-decoder based
- pipeline.
-
- Args:
- dict_type (str): Type of dict, should be one of {'DICT36', 'DICT90'}.
- dict_file (None|str): Character dict file path. If not none,
- higher priority than dict_type.
- dict_list (None|list[str]): Character list. If not none, higher
- priority than dict_type, but lower than dict_file.
- with_unknown (bool): If True, add `UKN` token to class.
- max_seq_len (int): Maximum sequence length of label.
- lower (bool): If True, convert original string to lower case.
- start_end_same (bool): Whether use the same index for
- start and end token or not. Default: True.
- """
-
- def __init__(self,
- dict_type='DICT90',
- with_unknown=True,
- max_seq_len=40,
- lower=False,
- start_end_same=True,
- return_confident=False,
- **kwargs):
- super().__init__(dict_type)
- assert isinstance(with_unknown, bool)
- assert isinstance(max_seq_len, int)
- assert isinstance(lower, bool)
-
- self.with_unknown = with_unknown
- self.max_seq_len = max_seq_len
- self.lower = lower
- self.start_end_same = start_end_same
- self.return_confident = return_confident
-
- self.update_dict()
-
- def update_dict(self):
- start_end_token = ''
- unknown_token = ''
- padding_token = ''
-
- # unknown
- self.unknown_idx = None
- if self.with_unknown:
- self.idx2char.append(unknown_token)
- self.unknown_idx = len(self.idx2char) - 1
-
- # BOS/EOS
- self.idx2char.append(start_end_token)
- self.start_idx = len(self.idx2char) - 1
- if not self.start_end_same:
- self.idx2char.append(start_end_token)
- self.end_idx = len(self.idx2char) - 1
-
- # padding
- self.idx2char.append(padding_token)
- self.padding_idx = len(self.idx2char) - 1
-
- # update char2idx
- self.char2idx = {}
- for idx, char in enumerate(self.idx2char):
- self.char2idx[char] = idx
-
- def __call__(self, indexes):
- strings = []
- confidents = []
- if self.return_confident:
- b,sq,_ = indexes.shape
- for idx in range(b):
- index = indexes[idx, :, :]
- chars = index.argmax(-1)
- confident = index.max(-1)
- i = 0
- while i < sq and chars[i] != self.end_idx and chars[i] != self.padding_idx: i += 1
- chars = chars[:i]
- confident = confident[:i].min()
- string = [self.idx2char[i] for i in chars]
- strings.append(''.join(string))
- confidents.append(confident)
-
- return strings, confidents
- else:
- for index in indexes:
- i, l = 0, len(index)
- while i < l and index[i] != self.end_idx and index[i] != self.padding_idx: i += 1
- index = index[:i]
- string = [self.idx2char[i] for i in index]
- strings.append(''.join(string))
- return strings
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/decoder.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/decoder.py
deleted file mode 100755
index b4ec51a..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/decoder.py
+++ /dev/null
@@ -1,278 +0,0 @@
-import torch
-import torch.nn as nn
-import torch.nn.functional as F
-import math
-import numpy as np
-from .encoder import MultiHeadAttention
-
-
-class PositionwiseFeedForward(nn.Module):
- """Two-layer feed-forward module.
-
- Args:
- d_in (int): The dimension of the input for feedforward
- network model.
- d_hid (int): The dimension of the feedforward
- network model.
- dropout (float): Dropout layer on feedforward output.
- act_cfg (dict): Activation cfg for feedforward module.
- """
-
- def __init__(self, d_in, d_hid, dropout=0.1):
- super().__init__()
- self.w_1 = nn.Linear(d_in, d_hid)
- self.w_2 = nn.Linear(d_hid, d_in)
- self.act = nn.GELU()
- self.dropout = nn.Dropout(dropout)
-
- def forward(self, x):
- x = self.w_1(x)
- x = self.act(x)
- x = self.w_2(x)
- x = self.dropout(x)
-
- return x
-
-
-class PositionalEncoding(nn.Module):
- """Fixed positional encoding with sine and cosine functions."""
-
- def __init__(self, d_hid=512, n_position=200):
- super().__init__()
-
- # Not a parameter
- # Position table of shape (1, n_position, d_hid)
- self.register_buffer(
- 'position_table',
- self._get_sinusoid_encoding_table(n_position, d_hid))
-
- def _get_sinusoid_encoding_table(self, n_position, d_hid):
- """Sinusoid position encoding table."""
- denominator = torch.Tensor([
- 1.0 / np.power(10000, 2 * (hid_j // 2) / d_hid)
- for hid_j in range(d_hid)
- ])
- denominator = denominator.view(1, -1)
- pos_tensor = torch.arange(n_position).unsqueeze(-1).float()
- sinusoid_table = pos_tensor * denominator
- sinusoid_table[:, 0::2] = torch.sin(sinusoid_table[:, 0::2])
- sinusoid_table[:, 1::2] = torch.cos(sinusoid_table[:, 1::2])
-
- return sinusoid_table.unsqueeze(0)
-
- def forward(self, x):
- """
- Args:
- x (Tensor): Tensor of shape (batch_size, pos_len, d_hid, ...)
- """
- self.device = x.device
- x = x + self.position_table[:, :x.size(1)].clone().detach()
- return x
-
-
-
-class TFDecoderLayer(nn.Module):
- """Transformer Decoder Layer.
-
- Args:
- d_model (int): The number of expected features
- in the decoder inputs (default=512).
- d_inner (int): The dimension of the feedforward
- network model (default=256).
- n_head (int): The number of heads in the
- multiheadattention models (default=8).
- d_k (int): Total number of features in key.
- d_v (int): Total number of features in value.
- dropout (float): Dropout layer on attn_output_weights.
- qkv_bias (bool): Add bias in projection layer. Default: False.
- act_cfg (dict): Activation cfg for feedforward module.
- operation_order (tuple[str]): The execution order of operation
- in transformer. Such as ('self_attn', 'norm', 'enc_dec_attn',
- 'norm', 'ffn', 'norm') or ('norm', 'self_attn', 'norm',
- 'enc_dec_attn', 'norm', 'ffn').
- Default:None.
- """
-
- def __init__(self,
- d_model=512,
- d_inner=256,
- n_head=8,
- d_k=64,
- d_v=64,
- dropout=0.1,
- qkv_bias=False):
- super().__init__()
-
- self.norm1 = nn.LayerNorm(d_model)
- self.norm2 = nn.LayerNorm(d_model)
- self.norm3 = nn.LayerNorm(d_model)
-
- self.self_attn = MultiHeadAttention(
- n_head, d_model, d_k, d_v, dropout=dropout, qkv_bias=qkv_bias)
-
- self.enc_attn = MultiHeadAttention(
- n_head, d_model, d_k, d_v, dropout=dropout, qkv_bias=qkv_bias)
-
- self.mlp = PositionwiseFeedForward(
- d_model, d_inner, dropout=dropout)
-
- def forward(self,
- dec_input,
- enc_output,
- self_attn_mask=None,
- dec_enc_attn_mask=None):
- dec_input_norm = self.norm1(dec_input)
- dec_attn_out = self.self_attn(dec_input_norm, dec_input_norm,
- dec_input_norm, self_attn_mask)
- dec_attn_out += dec_input
-
- enc_dec_attn_in = self.norm2(dec_attn_out)
- enc_dec_attn_out = self.enc_attn(enc_dec_attn_in, enc_output,
- enc_output, dec_enc_attn_mask)
- enc_dec_attn_out += dec_attn_out
-
- mlp_out = self.mlp(self.norm3(enc_dec_attn_out))
- mlp_out += enc_dec_attn_out
-
- return mlp_out
-
-class NRTRDecoder(nn.Module):
- """Transformer Decoder block with self attention mechanism.
-
- Args:
- n_layers (int): Number of attention layers.
- d_embedding (int): Language embedding dimension.
- n_head (int): Number of parallel attention heads.
- d_k (int): Dimension of the key vector.
- d_v (int): Dimension of the value vector.
- d_model (int): Dimension :math:`D_m` of the input from previous model.
- d_inner (int): Hidden dimension of feedforward layers.
- n_position (int): Length of the positional encoding vector. Must be
- greater than ``max_seq_len``.
- dropout (float): Dropout rate.
- num_classes (int): Number of output classes :math:`C`.
- max_seq_len (int): Maximum output sequence length :math:`T`.
- start_idx (int): The index of ``.
- padding_idx (int): The index of ``.
- init_cfg (dict or list[dict], optional): Initialization configs.
-
- Warning:
- This decoder will not predict the final class which is assumed to be
- ``. Therefore, its output size is always :math:`C - 1`. ``
- is also ignored by loss as specified in
- :obj:`mmocr.models.textrecog.recognizer.EncodeDecodeRecognizer`.
- """
-
- def __init__(self,
- n_layers=6,
- d_embedding=512,
- n_head=8,
- d_k=64,
- d_v=64,
- d_model=512,
- d_inner=256,
- n_position=200,
- dropout=0.1,
- num_classes=93,
- max_seq_len=40,
- start_idx=1,
- padding_idx=92,
- return_confident=False,
- end_idx=None,
- **kwargs):
- super().__init__()
-
- self.padding_idx = padding_idx
- self.start_idx = start_idx
- self.max_seq_len = max_seq_len
-
- self.trg_word_emb = nn.Embedding(
- num_classes, d_embedding, padding_idx=padding_idx)
-
- self.position_enc = PositionalEncoding(
- d_embedding, n_position=n_position)
-
- self.layer_stack = nn.ModuleList([
- TFDecoderLayer(
- d_model, d_inner, n_head, d_k, d_v, dropout=dropout, **kwargs)
- for _ in range(n_layers)
- ])
- self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)
-
- pred_num_class = num_classes - 1 # ignore padding_idx
- self.classifier = nn.Linear(d_model, pred_num_class)
-
- self.return_confident = return_confident
- self.end_idx = end_idx
-
- @staticmethod
- def get_pad_mask(seq, pad_idx):
-
- return (seq != pad_idx).unsqueeze(-2)
-
- @staticmethod
- def get_subsequent_mask(seq):
- """For masking out the subsequent info."""
- len_s = seq.size(1)
- subsequent_mask = 1 - torch.triu(
- torch.ones((len_s, len_s), device=seq.device), diagonal=1)
- subsequent_mask = subsequent_mask.unsqueeze(0).bool()
-
- return subsequent_mask
-
- def _attention(self, trg_seq, src, src_mask=None):
- trg_embedding = self.trg_word_emb(trg_seq)
- trg_pos_encoded = self.position_enc(trg_embedding)
- trg_mask = self.get_pad_mask(
- trg_seq,
- pad_idx=self.padding_idx) & self.get_subsequent_mask(trg_seq)
- output = trg_pos_encoded
- for dec_layer in self.layer_stack:
- output = dec_layer(
- output,
- src,
- self_attn_mask=trg_mask,
- dec_enc_attn_mask=src_mask)
- output = self.layer_norm(output)
-
- return output
-
- def _get_mask(self, logit):
- N, T, _ = logit.size()
- mask = logit.new_ones((N, T))
-
- return mask
-
- def forward(self, out_enc):
- src_mask = self._get_mask(out_enc)
- N = out_enc.size(0)
- init_target_seq = torch.full((N, self.max_seq_len + 1),
- self.padding_idx,
- device=out_enc.device,
- dtype=torch.long)
- # bsz * seq_len
- init_target_seq[:, 0] = self.start_idx
-
- outputs = []
- for step in range(0, self.max_seq_len):
- decoder_output = self._attention(
- trg_seq=init_target_seq,
- src=out_enc,
- src_mask=src_mask)
- if self.return_confident:
- step_result = torch.softmax(self.classifier(decoder_output[:, step, :]), -1)
- next_step_init = step_result.argmax(-1)
- init_target_seq[:, step + 1] = next_step_init
- if next_step_init.min() >= self.end_idx:
- break
- else:
- step_result = self.classifier(decoder_output[:, step, :]).argmax(-1)
- init_target_seq[:, step + 1] = step_result
- if step_result.min() >= self.end_idx:
- break
-
- outputs.append(step_result)
-
- outputs = torch.stack(outputs, dim=1)
-
- return outputs
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/encoder.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/encoder.py
deleted file mode 100755
index 6ccb612..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/encoder.py
+++ /dev/null
@@ -1,317 +0,0 @@
-import torch
-import torch.nn as nn
-import torch.nn.functional as F
-import numpy as np
-import math
-from .conv import ConvModule
-
-
-class LocalityAwareFeedforward(nn.Module):
- """Locality-aware feedforward layer in SATRN, see `SATRN.
-
- `_
- """
-
- def __init__(self,
- d_in,
- d_hid,
- dropout=0.1):
- super().__init__()
- self.conv1 = ConvModule(
- d_in,
- d_hid,
- kernel_size=1,
- padding=0,
- bias=False,
- norm_cfg=dict(type='BN'),
- act_cfg=dict(type='ReLU'))
-
- self.depthwise_conv = ConvModule(
- d_hid,
- d_hid,
- kernel_size=3,
- padding=1,
- bias=False,
- groups=d_hid,
- norm_cfg=dict(type='BN'),
- act_cfg=dict(type='ReLU'))
-
- self.conv2 = ConvModule(
- d_hid,
- d_in,
- kernel_size=1,
- padding=0,
- bias=False,
- norm_cfg=dict(type='BN'),
- act_cfg=dict(type='ReLU'))
-
- def forward(self, x):
- x = self.conv1(x)
- x = self.depthwise_conv(x)
- x = self.conv2(x)
-
- return x
-
-
-class ScaledDotProductAttention(nn.Module):
- """Scaled Dot-Product Attention Module. This code is adopted from
- https://github.com/jadore801120/attention-is-all-you-need-pytorch.
-
- Args:
- temperature (float): The scale factor for softmax input.
- attn_dropout (float): Dropout layer on attn_output_weights.
- """
-
- def __init__(self, temperature, attn_dropout=0.1):
- super().__init__()
- self.temperature = temperature
- self.dropout = nn.Dropout(attn_dropout)
-
- def forward(self, q, k, v, mask=None):
-
- attn = torch.matmul(q / self.temperature, k.transpose(2, 3))
-
- if mask is not None:
- attn = attn.masked_fill(mask == 0, float('-inf'))
-
- attn = self.dropout(F.softmax(attn, dim=-1))
- output = torch.matmul(attn, v)
-
- return output, attn
-
-
-class MultiHeadAttention(nn.Module):
- """Multi-Head Attention module.
-
- Args:
- n_head (int): The number of heads in the
- multiheadattention models (default=8).
- d_model (int): The number of expected features
- in the decoder inputs (default=512).
- d_k (int): Total number of features in key.
- d_v (int): Total number of features in value.
- dropout (float): Dropout layer on attn_output_weights.
- qkv_bias (bool): Add bias in projection layer. Default: False.
- """
-
- def __init__(self,
- n_head=8,
- d_model=512,
- d_k=64,
- d_v=64,
- dropout=0.1,
- qkv_bias=False):
- super().__init__()
- self.n_head = n_head
- self.d_k = d_k
- self.d_v = d_v
-
- self.dim_k = n_head * d_k
- self.dim_v = n_head * d_v
-
- self.linear_q = nn.Linear(self.dim_k, self.dim_k, bias=qkv_bias)
- self.linear_k = nn.Linear(self.dim_k, self.dim_k, bias=qkv_bias)
- self.linear_v = nn.Linear(self.dim_v, self.dim_v, bias=qkv_bias)
-
- self.attention = ScaledDotProductAttention(d_k**0.5, dropout)
-
- self.fc = nn.Linear(self.dim_v, d_model, bias=qkv_bias)
- self.proj_drop = nn.Dropout(dropout)
-
- def forward(self, q, k, v, mask=None):
- batch_size, len_q, _ = q.size()
- _, len_k, _ = k.size()
-
- q = self.linear_q(q).view(batch_size, len_q, self.n_head, self.d_k)
- k = self.linear_k(k).view(batch_size, len_k, self.n_head, self.d_k)
- v = self.linear_v(v).view(batch_size, len_k, self.n_head, self.d_v)
-
- q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
-
- if mask is not None:
- if mask.dim() == 3:
- mask = mask.unsqueeze(1)
- elif mask.dim() == 2:
- mask = mask.unsqueeze(1).unsqueeze(1)
-
- attn_out, _ = self.attention(q, k, v, mask=mask)
-
- attn_out = attn_out.transpose(1, 2).contiguous().view(
- batch_size, len_q, self.dim_v)
-
- attn_out = self.fc(attn_out)
- attn_out = self.proj_drop(attn_out)
-
- return attn_out
-
-
-class SatrnEncoderLayer(nn.Module):
- """"""
-
- def __init__(self,
- d_model=512,
- d_inner=512,
- n_head=8,
- d_k=64,
- d_v=64,
- dropout=0.1,
- qkv_bias=False):
- super().__init__()
- self.norm1 = nn.LayerNorm(d_model)
- self.attn = MultiHeadAttention(
- n_head, d_model, d_k, d_v, qkv_bias=qkv_bias, dropout=dropout)
- self.norm2 = nn.LayerNorm(d_model)
- self.feed_forward = LocalityAwareFeedforward(
- d_model, d_inner, dropout=dropout)
-
- def forward(self, x, h, w, mask=None):
- n, hw, c = x.size()
- residual = x
- x = self.norm1(x)
- x = residual + self.attn(x, x, x, mask)
- residual = x
- x = self.norm2(x)
- x = x.transpose(1, 2).contiguous().view(n, c, h, w)
- x = self.feed_forward(x)
- x = x.view(n, c, hw).transpose(1, 2)
- x = residual + x
- return x
-
-
-class Adaptive2DPositionalEncoding(nn.Module):
- """Implement Adaptive 2D positional encoder for SATRN, see
- `SATRN `_
- Modified from https://github.com/Media-Smart/vedastr
- Licensed under the Apache License, Version 2.0 (the "License");
- Args:
- d_hid (int): Dimensions of hidden layer.
- n_height (int): Max height of the 2D feature output.
- n_width (int): Max width of the 2D feature output.
- dropout (int): Size of hidden layers of the model.
- """
-
- def __init__(self,
- d_hid=512,
- n_height=100,
- n_width=100,
- dropout=0.1):
- super().__init__()
-
- h_position_encoder = self._get_sinusoid_encoding_table(n_height, d_hid)
- h_position_encoder = h_position_encoder.transpose(0, 1)
- h_position_encoder = h_position_encoder.view(1, d_hid, n_height, 1)
-
- w_position_encoder = self._get_sinusoid_encoding_table(n_width, d_hid)
- w_position_encoder = w_position_encoder.transpose(0, 1)
- w_position_encoder = w_position_encoder.view(1, d_hid, 1, n_width)
-
- self.register_buffer('h_position_encoder', h_position_encoder)
- self.register_buffer('w_position_encoder', w_position_encoder)
-
- self.h_scale = self.scale_factor_generate(d_hid)
- self.w_scale = self.scale_factor_generate(d_hid)
- self.pool = nn.AdaptiveAvgPool2d(1)
- self.dropout = nn.Dropout(p=dropout)
-
- def _get_sinusoid_encoding_table(self, n_position, d_hid):
- """Sinusoid position encoding table."""
- denominator = torch.Tensor([
- 1.0 / np.power(10000, 2 * (hid_j // 2) / d_hid)
- for hid_j in range(d_hid)
- ])
- denominator = denominator.view(1, -1)
- pos_tensor = torch.arange(n_position).unsqueeze(-1).float()
- sinusoid_table = pos_tensor * denominator
- sinusoid_table[:, 0::2] = torch.sin(sinusoid_table[:, 0::2])
- sinusoid_table[:, 1::2] = torch.cos(sinusoid_table[:, 1::2])
-
- return sinusoid_table
-
- def scale_factor_generate(self, d_hid):
- scale_factor = nn.Sequential(
- nn.Conv2d(d_hid, d_hid, kernel_size=1), nn.ReLU(inplace=True),
- nn.Conv2d(d_hid, d_hid, kernel_size=1), nn.Sigmoid())
-
- return scale_factor
-
- def forward(self, x):
- b, c, h, w = x.size()
-
- avg_pool = self.pool(x)
-
- h_pos_encoding = \
- self.h_scale(avg_pool) * self.h_position_encoder[:, :, :h, :]
- w_pos_encoding = \
- self.w_scale(avg_pool) * self.w_position_encoder[:, :, :, :w]
-
- out = x + h_pos_encoding + w_pos_encoding
-
- out = self.dropout(out)
-
- return out
-
-
-class SatrnEncoder(nn.Module):
- """Implement encoder for SATRN, see `SATRN.
-
- `_.
-
- Args:
- n_layers (int): Number of attention layers.
- n_head (int): Number of parallel attention heads.
- d_k (int): Dimension of the key vector.
- d_v (int): Dimension of the value vector.
- d_model (int): Dimension :math:`D_m` of the input from previous model.
- n_position (int): Length of the positional encoding vector. Must be
- greater than ``max_seq_len``.
- d_inner (int): Hidden dimension of feedforward layers.
- dropout (float): Dropout rate.
- init_cfg (dict or list[dict], optional): Initialization configs.
- """
-
- def __init__(self,
- n_layers=12,
- n_head=8,
- d_k=64,
- d_v=64,
- d_model=512,
- n_position=100,
- d_inner=256,
- dropout=0.1,
- **kwargs):
- super().__init__()
- self.d_model = d_model
- self.position_enc = Adaptive2DPositionalEncoding(
- d_hid=d_model,
- n_height=n_position,
- n_width=n_position,
- dropout=dropout)
- self.layer_stack = nn.ModuleList([
- SatrnEncoderLayer(
- d_model, d_inner, n_head, d_k, d_v, dropout=dropout)
- for _ in range(n_layers)
- ])
- self.layer_norm = nn.LayerNorm(d_model)
-
- def forward(self, feat):
- """
- Args:
- feat (Tensor): Feature tensor of shape :math:`(N, D_m, H, W)`.
-
- Returns:
- Tensor: A tensor of shape :math:`(N, T, D_m)`.
- """
- feat = feat + self.position_enc(feat)
- n, c, h, w = feat.size()
- mask = feat.new_zeros((n, h, w))
- mask[:,:,:w] = 1
-
- mask = mask.view(n, h * w)
- feat = feat.view(n, c, h * w)
-
- output = feat.permute(0, 2, 1).contiguous()
- for enc_layer in self.layer_stack:
- output = enc_layer(output, h, w, mask)
- output = self.layer_norm(output)
-
- return output
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/factory.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/factory.py
deleted file mode 100755
index 773d5a0..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/factory.py
+++ /dev/null
@@ -1,57 +0,0 @@
-import os
-import shutil
-import colorama
-import hashlib
-
-def sha256sum(filename):
- h = hashlib.sha256()
- b = bytearray(128*1024)
- mv = memoryview(b)
- with open(filename, 'rb', buffering=0) as f:
- for n in iter(lambda : f.readinto(mv), 0):
- h.update(mv[:n])
- return h.hexdigest()
-
-
-online_model_factory = {
- 'satrn-lite-general-pretrain-20230106': {
- 'url': 'https://github.com/moewiee/satrn-model-factory/raw/main/jxqhbem4to.pth',
- 'hash': 'b0069a72bf6fc080ad5d431d5ce650c3bfbab535141adef1631fce331cb1471c'},
- 'satrn-lite-captcha-finetune-20230108': {
- 'url': 'https://github.com/moewiee/satrn-model-factory/raw/main/l27vitogmc.pth',
- 'hash': 'efcbcf2955b6b21125b073f83828d2719e908c7303b0d9901e94be5a8efba916'},
- 'satrn-lite-handwritten-finetune-20230108': {
- 'url': 'https://github.com/moewiee/satrn-model-factory/raw/main/lj9gkwelns.pth',
- 'hash': 'bccd8e985b131fcd4701114af5ceaef098f2eac50654bbb1d828e7f829e711dd'},
-}
-
-__hub_available_versions__ = online_model_factory.keys()
-
-def _get(version):
- use_online = version in __hub_available_versions__
-
- if not use_online and not os.path.exists(version):
- raise ValueError(f'Model version {version} not found online and not found local.')
-
- hub_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'hub')
- if not os.path.exists(hub_path):
- os.makedirs(hub_path)
- if use_online:
- version_url = online_model_factory[version]['url']
- file_path = os.path.join(hub_path, os.path.basename(version_url))
- else:
- file_path = os.path.join(hub_path, os.path.basename(version))
-
- if not os.path.exists(file_path):
- if use_online:
- os.system(f'wget -O {file_path} {version_url}')
- assert os.path.exists(file_path), \
- colorama.Fore.RED + 'wget failed while trying to retrieve from hub.' + colorama.Style.RESET_ALL
- downloaded_hash = sha256sum(file_path)
- if downloaded_hash != online_model_factory[version]['hash']:
- os.remove(file_path)
- raise ValueError(colorama.Fore.RED + 'sha256 hash doesnt match for version retrieved from hub.' + colorama.Style.RESET_ALL)
- else:
- shutil.copy2(version, file_path)
-
- return file_path
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/fp16_utils.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/fp16_utils.py
deleted file mode 100755
index 126ff02..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/fp16_utils.py
+++ /dev/null
@@ -1,78 +0,0 @@
-import torch
-import torch.nn as nn
-import numpy as np
-from collections import abc
-
-
-def cast_tensor_type(inputs, src_type, dst_type):
- """Recursively convert Tensor in inputs from src_type to dst_type.
-
- Args:
- inputs: Inputs that to be casted.
- src_type (torch.dtype): Source type..
- dst_type (torch.dtype): Destination type.
-
- Returns:
- The same type with inputs, but all contained Tensors have been cast.
- """
- if isinstance(inputs, nn.Module):
- return inputs
- elif isinstance(inputs, torch.Tensor):
- return inputs.to(dst_type)
- elif isinstance(inputs, str):
- return inputs
- elif isinstance(inputs, np.ndarray):
- return inputs
- elif isinstance(inputs, abc.Mapping):
- return type(inputs)({
- k: cast_tensor_type(v, src_type, dst_type)
- for k, v in inputs.items()
- })
- elif isinstance(inputs, abc.Iterable):
- return type(inputs)(
- cast_tensor_type(item, src_type, dst_type) for item in inputs)
- else:
- return inputs
-
-
-def patch_forward_method(func, src_type, dst_type, convert_output=True):
- """Patch the forward method of a module.
-
- Args:
- func (callable): The original forward method.
- src_type (torch.dtype): Type of input arguments to be converted from.
- dst_type (torch.dtype): Type of input arguments to be converted to.
- convert_output (bool): Whether to convert the output back to src_type.
-
- Returns:
- callable: The patched forward method.
- """
-
- def new_forward(*args, **kwargs):
- output = func(*cast_tensor_type(args, src_type, dst_type),
- **cast_tensor_type(kwargs, src_type, dst_type))
- if convert_output:
- output = cast_tensor_type(output, dst_type, src_type)
- return output
-
- return new_forward
-
-
-def patch_norm_fp32(module):
- """Recursively convert normalization layers from FP16 to FP32.
-
- Args:
- module (nn.Module): The modules to be converted in FP16.
-
- Returns:
- nn.Module: The converted module, the normalization layers have been
- converted to FP32.
- """
- if isinstance(module, (nn.modules.batchnorm._BatchNorm, nn.GroupNorm)):
- module.float()
- if isinstance(module, nn.GroupNorm) or torch.__version__ < '1.3':
- module.forward = patch_forward_method(module.forward, torch.half,
- torch.float)
- for child in module.children():
- patch_norm_fp32(child)
- return module
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/transform.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/transform.py
deleted file mode 100755
index e366a4c..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/transform.py
+++ /dev/null
@@ -1,33 +0,0 @@
-import torchvision.transforms.functional as TF
-import cv2
-import torch
-
-class DataPipelineSATRN:
- def __init__(self,
- resize_height,
- resize_width,
- norm_mean,
- norm_std,
- device='cpu'):
- self.resize_height = resize_height
- self.resize_width = resize_width
- self.norm_mean = norm_mean
- self.norm_std = norm_std
- self.device = device
-
- def __call__(self, imgs):
- if not isinstance(imgs, list):
- imgs = [imgs]
- datas = []
- for img in imgs:
- if isinstance(img, str):
- img = cv2.imread(img)
- data = torch.from_numpy(cv2.resize(img, (self.resize_width, self.resize_height), interpolation=cv2.INTER_LINEAR))
- datas.append(data)
-
- data = torch.stack(datas, dim=0)
- data = data.to(self.device)
- data = data.float().div_(255.).permute((0,3,1,2))
- TF.normalize(data, mean=self.norm_mean, std=self.norm_std, inplace=True)
-
- return data.half() if self.device != 'cpu' else data
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/version.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/version.py
deleted file mode 100755
index a55ccd2..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/sdsvtr/version.py
+++ /dev/null
@@ -1 +0,0 @@
-__version__ = '0.0.5'
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/setup.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/setup.py
deleted file mode 100755
index 4df1557..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/setup.py
+++ /dev/null
@@ -1,187 +0,0 @@
-import os
-import os.path as osp
-import shutil
-import sys
-import warnings
-from setuptools import find_packages, setup
-
-
-def readme():
- with open('README.md', encoding='utf-8') as f:
- content = f.read()
- return content
-
-
-version_file = 'sdsvtr/version.py'
-is_windows = sys.platform == 'win32'
-
-
-def add_mim_extention():
- """Add extra files that are required to support MIM into the package.
-
- These files will be added by creating a symlink to the originals if the
- package is installed in `editable` mode (e.g. pip install -e .), or by
- copying from the originals otherwise.
- """
-
- # parse installment mode
- if 'develop' in sys.argv:
- # installed by `pip install -e .`
- mode = 'symlink'
- elif 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
- # installed by `pip install .`
- # or create source distribution by `python setup.py sdist`
- mode = 'copy'
- else:
- return
-
- filenames = ['tools', 'configs', 'model-index.yml']
- repo_path = osp.dirname(__file__)
- mim_path = osp.join(repo_path, 'mmocr', '.mim')
- os.makedirs(mim_path, exist_ok=True)
-
- for filename in filenames:
- if osp.exists(filename):
- src_path = osp.join(repo_path, filename)
- tar_path = osp.join(mim_path, filename)
-
- if osp.isfile(tar_path) or osp.islink(tar_path):
- os.remove(tar_path)
- elif osp.isdir(tar_path):
- shutil.rmtree(tar_path)
-
- if mode == 'symlink':
- src_relpath = osp.relpath(src_path, osp.dirname(tar_path))
- try:
- os.symlink(src_relpath, tar_path)
- except OSError:
- # Creating a symbolic link on windows may raise an
- # `OSError: [WinError 1314]` due to privilege. If
- # the error happens, the src file will be copied
- mode = 'copy'
- warnings.warn(
- f'Failed to create a symbolic link for {src_relpath}, '
- f'and it will be copied to {tar_path}')
- else:
- continue
-
- if mode == 'copy':
- if osp.isfile(src_path):
- shutil.copyfile(src_path, tar_path)
- elif osp.isdir(src_path):
- shutil.copytree(src_path, tar_path)
- else:
- warnings.warn(f'Cannot copy file {src_path}.')
- else:
- raise ValueError(f'Invalid mode {mode}')
-
-
-def get_version():
- with open(version_file, 'r') as f:
- exec(compile(f.read(), version_file, 'exec'))
- import sys
-
- # return short version for sdist
- if 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
- return locals()['short_version']
- else:
- return locals()['__version__']
-
-
-def parse_requirements(fname='requirements.txt', with_version=True):
- """Parse the package dependencies listed in a requirements file but strip
- specific version information.
-
- Args:
- fname (str): Path to requirements file.
- with_version (bool, default=False): If True, include version specs.
- Returns:
- info (list[str]): List of requirements items.
- CommandLine:
- python -c "import setup; print(setup.parse_requirements())"
- """
- import re
- import sys
- from os.path import exists
- require_fpath = fname
-
- def parse_line(line):
- """Parse information from a line in a requirements text file."""
- if line.startswith('-r '):
- # Allow specifying requirements in other files
- target = line.split(' ')[1]
- for info in parse_require_file(target):
- yield info
- else:
- info = {'line': line}
- if line.startswith('-e '):
- info['package'] = line.split('#egg=')[1]
- else:
- # Remove versioning from the package
- pat = '(' + '|'.join(['>=', '==', '>']) + ')'
- parts = re.split(pat, line, maxsplit=1)
- parts = [p.strip() for p in parts]
-
- info['package'] = parts[0]
- if len(parts) > 1:
- op, rest = parts[1:]
- if ';' in rest:
- # Handle platform specific dependencies
- # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
- version, platform_deps = map(str.strip,
- rest.split(';'))
- info['platform_deps'] = platform_deps
- else:
- version = rest # NOQA
- info['version'] = (op, version)
- yield info
-
- def parse_require_file(fpath):
- with open(fpath, 'r') as f:
- for line in f.readlines():
- line = line.strip()
- if line and not line.startswith('#'):
- for info in parse_line(line):
- yield info
-
- def gen_packages_items():
- if exists(require_fpath):
- for info in parse_require_file(require_fpath):
- parts = [info['package']]
- if with_version and 'version' in info:
- parts.extend(info['version'])
- if not sys.version.startswith('3.4'):
- # apparently package_deps are broken in 3.4
- platform_deps = info.get('platform_deps')
- if platform_deps is not None:
- parts.append(';' + platform_deps)
- item = ''.join(parts)
- yield item
-
- packages = list(gen_packages_items())
- return packages
-
-
-if __name__ == '__main__':
- setup(
- name='sdsvtr',
- version=get_version(),
- description='SDSV OCR Team Text Recognizer',
- long_description=readme(),
- long_description_content_type='text/markdown',
- packages=find_packages(exclude=('configs', 'tools', 'demo')),
- include_package_data=True,
- url='https://github.com/open-mmlab/mmocr',
- classifiers=[
- 'Development Status :: 4 - Beta',
- 'License :: OSI Approved :: Apache Software License',
- 'Operating System :: OS Independent',
- 'Programming Language :: Python :: 3',
- 'Programming Language :: Python :: 3.6',
- 'Programming Language :: Python :: 3.7',
- 'Programming Language :: Python :: 3.8',
- 'Programming Language :: Python :: 3.9',
- ],
- license='Apache License 2.0',
- install_requires=parse_requirements('requirements.txt'),
- zip_safe=False)
diff --git a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/test.py b/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/test.py
deleted file mode 100755
index b929e7e..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/externals/sdsvtr/test.py
+++ /dev/null
@@ -1,12 +0,0 @@
-import numpy as np
-from sdsvtr import StandaloneSATRNRunner
-runner = StandaloneSATRNRunner(version='satrn-lite-general-pretrain-20230106', return_confident=False, device='cuda:1')
-
-dummy_list = [np.ndarray((32,128,3)) for _ in range(100)]
-bs = 32
-
-all_results = []
-while len(dummy_list) > 0:
- dummy_batch = dummy_list[:bs]
- dummy_list = dummy_list[bs:]
- all_results += runner(dummy_batch)
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/requirements.txt b/cope2n-ai-fi/modules/ocr_engine/requirements.txt
deleted file mode 100755
index 7bfd9c5..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/requirements.txt
+++ /dev/null
@@ -1,82 +0,0 @@
-addict==2.4.0
-asttokens==2.2.1
-autopep8==1.6.0
-backcall==0.2.0
-backports.functools-lru-cache==1.6.4
-brotlipy==0.7.0
-certifi==2022.12.7
-cffi==1.15.1
-charset-normalizer==2.0.4
-click==8.1.3
-colorama==0.4.6
-cryptography==39.0.1
-debugpy==1.5.1
-decorator==5.1.1
-docopt==0.6.2
-entrypoints==0.4
-executing==1.2.0
-flit_core==3.6.0
-idna==3.4
-importlib-metadata==6.0.0
-ipykernel==6.15.0
-ipython==8.11.0
-jedi==0.18.2
-jupyter-client==7.0.6
-jupyter_core==4.12.0
-Markdown==3.4.1
-markdown-it-py==2.2.0
-matplotlib-inline==0.1.6
-mdurl==0.1.2
-mkl-fft==1.3.6
-mkl-random==1.2.2
-mkl-service==2.4.0
-mmcv-full==1.7.1
-model-index==0.1.11
-nest-asyncio==1.5.6
-numpy==1.24.3
-opencv-python==4.7.0.72
-openmim==0.3.6
-ordered-set==4.1.0
-packaging==23.0
-pandas==1.5.3
-parso==0.8.3
-pexpect==4.8.0
-pickleshare==0.7.5
-Pillow==9.4.0
-pip==22.3.1
-pipdeptree==2.5.2
-prompt-toolkit==3.0.38
-psutil==5.9.0
-ptyprocess==0.7.0
-pure-eval==0.2.2
-pycodestyle==2.10.0
-pycparser==2.21
-Pygments==2.14.0
-pyOpenSSL==23.0.0
-PySocks==1.7.1
-python-dateutil==2.8.2
-pytz==2022.7.1
-PyYAML==6.0
-pyzmq==19.0.2
-requests==2.28.1
-rich==13.3.1
-sdsvtd==0.1.1
-sdsvtr==0.0.5
-setuptools==65.6.3
-Shapely==1.8.4
-six==1.16.0
-stack-data==0.6.2
-tabulate==0.9.0
-toml==0.10.2
-torch==1.13.1
-torchvision==0.14.1
-tornado==6.1
-tqdm==4.65.0
-traitlets==5.9.0
-typing_extensions==4.4.0
-urllib3==1.26.14
-wcwidth==0.2.6
-wheel==0.38.4
-yapf==0.32.0
-yarg==0.1.9
-zipp==3.15.0
diff --git a/cope2n-ai-fi/modules/ocr_engine/run.py b/cope2n-ai-fi/modules/ocr_engine/run.py
deleted file mode 100755
index 3b19879..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/run.py
+++ /dev/null
@@ -1,200 +0,0 @@
-"""
-see scripts/run_ocr.sh to run
-"""
-# from pathlib import Path # add parent path to run debugger
-# import sys
-# FILE = Path(__file__).absolute()
-# sys.path.append(FILE.parents[2].as_posix())
-
-
-from src.utils import construct_file_path, ImageReader
-from src.dto import Line
-from src.ocr import OcrEngine
-import argparse
-import tqdm
-import pandas as pd
-from pathlib import Path
-import json
-import os
-import numpy as np
-from typing import Union, Tuple, List, Optional
-from collections import defaultdict
-
-current_dir = os.getcwd()
-
-
-def get_args():
- parser = argparse.ArgumentParser()
- # parser image
- parser.add_argument(
- "--image",
- type=str,
- required=True,
- help="path to input image/directory/csv file",
- )
- parser.add_argument(
- "--save_dir", type=str, required=True, help="path to save directory"
- )
- parser.add_argument(
- "--include", type=str, nargs="+", default=[], help="files/folders to include"
- )
- parser.add_argument(
- "--exclude", type=str, nargs="+", default=[], help="files/folders to exclude"
- )
- parser.add_argument(
- "--base_dir",
- type=str,
- required=False,
- default=current_dir,
- help="used when --image and --save_dir are relative paths to a base directory, default to current directory",
- )
- parser.add_argument(
- "--export_csv",
- type=str,
- required=False,
- default="",
- help="used when --image is a directory. If set, a csv file contains image_path, ocr_path and label will be exported to save_dir.",
- )
- parser.add_argument(
- "--export_img",
- type=bool,
- required=False,
- default=False,
- help="whether to save the visualize img",
- )
- parser.add_argument("--ocr_kwargs", type=str, required=False, default="")
- opt = parser.parse_args()
- return opt
-
-
-def load_engine(opt) -> OcrEngine:
- print("[INFO] Loading engine...")
- kw = json.loads(opt.ocr_kwargs) if opt.ocr_kwargs else {}
- engine = OcrEngine(**kw)
- print("[INFO] Engine loaded")
- return engine
-
-
-def convert_relative_path_to_positive_path(tgt_dir: Path, base_dir: Path) -> Path:
- return tgt_dir if tgt_dir.is_absolute() else base_dir.joinpath(tgt_dir)
-
-
-def get_paths_from_opt(opt) -> Tuple[Path, Path]:
- # BC\ kiem\ tra\ y\ te -> BC kiem tra y te
- img_path = opt.image.replace("\\ ", " ").strip()
- save_dir = opt.save_dir.replace("\\ ", " ").strip()
- base_dir = opt.base_dir.replace("\\ ", " ").strip()
- input_image = convert_relative_path_to_positive_path(Path(img_path), Path(base_dir))
- save_dir = convert_relative_path_to_positive_path(Path(save_dir), Path(base_dir))
- if not save_dir.exists():
- save_dir.mkdir()
- print("[INFO]: Creating folder ", save_dir)
- return input_image, save_dir
-
-
-def process_img(
- img: Union[str, np.ndarray],
- save_dir_or_path: str,
- engine: OcrEngine,
- export_img: bool,
- save_path_deskew: Optional[str] = None,
-) -> None:
- save_dir_or_path = Path(save_dir_or_path)
- if isinstance(img, np.ndarray):
- if save_dir_or_path.is_dir():
- raise ValueError("numpy array input require a save path, not a save dir")
- page = engine(img)
- save_path = (
- str(save_dir_or_path.joinpath(Path(img).stem + ".txt"))
- if save_dir_or_path.is_dir()
- else str(save_dir_or_path)
- )
- page.write_to_file("word", save_path)
- if export_img:
- page.save_img(
- save_path.replace(".txt", ".jpg"),
- is_vnese=True,
- save_path_deskew=save_path_deskew,
- )
-
-
-def process_dir(
- dir_path: str,
- save_dir: str,
- engine: OcrEngine,
- export_img: bool,
- lexcludes: List[str] = [],
- lincludes: List[str] = [],
- ddata=defaultdict(list),
-) -> None:
- pdir_path = Path(dir_path)
- print(pdir_path)
- # save_dir_sub = Path(construct_file_path(save_dir, dir_path, ext=""))
- psave_dir = Path(save_dir)
- psave_dir.mkdir(exist_ok=True)
- for img_path in (pbar := tqdm.tqdm(pdir_path.iterdir())):
- pbar.set_description(f"Processing {pdir_path}")
- if (lincludes and img_path.name not in lincludes) or (
- img_path.name in lexcludes
- ):
- continue # only process desired files/foders
- if img_path.is_dir():
- psave_dir_sub = psave_dir.joinpath(img_path.stem)
- process_dir(img_path, str(psave_dir_sub), engine, ddata)
- elif img_path.suffix.lower() in ImageReader.supported_ext:
- simg_path = str(img_path)
- # try:
- img = (
- ImageReader.read(simg_path)
- if img_path.suffix != ".pdf"
- else ImageReader.read(simg_path)[0]
- )
- save_path = str(Path(psave_dir).joinpath(img_path.stem + ".txt"))
- save_path_deskew = str(
- Path(psave_dir).joinpath(img_path.stem + "_deskewed.jpg")
- )
- process_img(img, save_path, engine, export_img, save_path_deskew)
- # except Exception as e:
- # print('[ERROR]: ', e, ' at ', simg_path)
- # continue
- ddata["img_path"].append(simg_path)
- ddata["ocr_path"].append(save_path)
- if Path(save_path_deskew).exists():
- ddata["save_path_deskew"].append(save_path)
- ddata["label"].append(pdir_path.stem)
- # ddata.update({"img_path": img_path, "save_path": save_path, "label": dir_path.stem})
- return ddata
-
-
-def process_csv(csv_path: str, engine: OcrEngine) -> None:
- df = pd.read_csv(csv_path)
- if not "image_path" in df.columns or not "ocr_path" in df.columns:
- raise AssertionError("Cannot fing image_path in df headers")
- for row in df.iterrows():
- process_img(row.image_path, row.ocr_path, engine)
-
-
-if __name__ == "__main__":
- opt = get_args()
- engine = load_engine(opt)
- print("[INFO]: OCR engine settings:", engine.settings)
- img, save_dir = get_paths_from_opt(opt)
-
- lskip_dir = []
- if img.is_dir():
- ddata = process_dir(
- img, save_dir, engine, opt.export_img, opt.exclude, opt.include
- )
- if opt.export_csv:
- pd.DataFrame.from_dict(ddata).to_csv(
- Path(save_dir).joinpath(opt.export_csv)
- )
- elif img.suffix in ImageReader.supported_ext:
- process_img(str(img), save_dir, engine, opt.export_img)
- elif img.suffix == ".csv":
- print(
- "[WARNING]: Running with csv file will ignore the save_dir argument. Instead, the ocr_path in the csv would be used"
- )
- process_csv(img, engine)
- else:
- raise NotImplementedError("[ERROR]: Unsupported file {}".format(img))
diff --git a/cope2n-ai-fi/modules/ocr_engine/scripts/run_deskew.sh b/cope2n-ai-fi/modules/ocr_engine/scripts/run_deskew.sh
deleted file mode 100755
index 34ecd8c..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/scripts/run_deskew.sh
+++ /dev/null
@@ -1,9 +0,0 @@
-export CUDA_VISIBLE_DEVICES=1
-# export PATH=/usr/local/cuda-11.6/bin${PATH:+:${PATH}}
-# export LD_LIBRARY_PATH=/usr/local/cuda-11.6/lib64\ {LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}
-# export CUDA_HOME=/usr/local/cuda-11.6
-# export PATH=/usr/local/cuda-11.6/bin:$PATH
-# export CPATH=/usr/local/cuda-11.6/include:$CPATH
-# export LIBRARY_PATH=/usr/local/cuda-11.6/lib64:$LIBRARY_PATH
-# export LD_LIBRARY_PATH=/usr/local/cuda-11.6/lib64:/usr/local/cuda-11.6/extras/CUPTI/lib64:$LD_LIBRARY_PATH
-python test/test_deskew_dir.py
\ No newline at end of file
diff --git a/cope2n-ai-fi/modules/ocr_engine/scripts/run_ocr.sh b/cope2n-ai-fi/modules/ocr_engine/scripts/run_ocr.sh
deleted file mode 100755
index 8ade432..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/scripts/run_ocr.sh
+++ /dev/null
@@ -1,49 +0,0 @@
-
-
-#bash scripts/run_ocr.sh -i /mnt/hdd2T/AICR/Projects/2023/FWD/Forms/PDFs/ -o /mnt/ssd1T/hungbnt/DocumentClassification/results/ocr -e out.csv -k "{\"device\":\"cuda:1\"}" -p True -n Passport 'So\ HK'
-#bash scripts/run_ocr.sh -i '/mnt/hdd2T/AICR/Projects/2023/FWD/Forms/PDFs/So\ HK' -o /mnt/ssd1T/hungbnt/DocumentClassification/results/ocr -e out.csv -k "{\"device\":\"cuda:1\"}" -p True
-#-n and -x do not accept multiple argument currently
-
-
-# bash scripts/run_ocr.sh -i /mnt/hdd4T/OCR/hoangdc/End_to_end/ICDAR2013/data/images_receipt_5images/ -o visualize/ -e out.csv -k "{\"device\":\"cuda:1\"}" -p True
-
-export PYTHONWARNINGS="ignore"
-
-while getopts i:o:b:e:p:k:n:x: flag
-do
- case "${flag}" in
- i) img=${OPTARG};;
- o) out_dir=${OPTARG};;
- b) base_dir=${OPTARG};;
- e) export_csv=${OPTARG};;
- p) export_img=${OPTARG};;
- k) ocr_kwargs=${OPTARG};;
- n) include=("${OPTARG[@]}");;
- x) exclude=("${OPTARG[@]}");;
- esac
-done
-
-cmd="python run.py \
- --image $img \
- --save_dir $out_dir \
- --export_csv $export_csv \
- --export_img $export_img \
- --ocr_kwargs $ocr_kwargs"
-
-if [ ${#include[@]} -gt 0 ]; then
- cmd+=" --include"
- for item in "${include[@]}"; do
- cmd+=" $item"
- done
-fi
-
-if [ ${#exclude[@]} -gt 0 ]; then
- cmd+=" --exclude"
- for item in "${exclude[@]}"; do
- cmd+=" $item"
- done
-fi
-
-
-echo $cmd
-exec $cmd
diff --git a/cope2n-ai-fi/modules/ocr_engine/settings.yml b/cope2n-ai-fi/modules/ocr_engine/settings.yml
deleted file mode 100755
index 055e16f..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/settings.yml
+++ /dev/null
@@ -1,36 +0,0 @@
-device: &device cuda:0
-max_img_size: [1920,1920] #text det default size: 1280x1280 #[] = originla size, TODO: fix the deskew code to resize the image only for detecting the angle, we want to feed the original size image to the text detection pipeline so that the bounding boxes would be mapped back to the original size
-extend_bbox: [0, 0.0, 0.0, 0.0] # left, top, right, bottom
-batch_size: 1 #1 means batch_mode = False
-detector:
- # version: /mnt/hdd2T/datnt/datnt_from_ssd1T/mmdetection/wild_receipt_finetune_weights_c_lite.pth
- version: /workspace/cope2n-ai-fi/weights/models/sdsap_sbt/ocr_engine/sdsvtd/epoch_100_params.pth
- auto_rotate: True
- rotator_version: /workspace/cope2n-ai-fi/weights/models/sdsap_sbt/ocr_engine/sdsvtd/best_bbox_mAP_epoch_30_lite.pth
- device: *device
-
-recognizer:
- # version: satrn-lite-general-pretrain-20230106
- version: /workspace/cope2n-ai-fi/weights/models/sdsvtr/hub/jxqhbem4to.pth
- max_seq_len_overwrite: 24 #default = 12
- return_confident: True
- device: *device
-#extend the bbox to avoid losing accent mark in vietnames, if using ocr for only english, disable it
-
-deskew:
- enable: True
- text_detector:
- config: /workspace/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/config/det.yaml
- weight: /workspace/cope2n-ai-fi/weights/models/sdsap_sbt/ocr_engine/sdsv_dewarp/ch_PP-OCRv3_det_infer
- text_cls:
- config: /workspace/cope2n-ai-fi/modules/ocr_engine/externals/sdsv_dewarp/config/cls.yaml
- weight: /workspace/cope2n-ai-fi/weights/models/sdsap_sbt/ocr_engine/sdsv_dewarp/ch_ppocr_mobile_v2.0_cls_infer
- device: *device
-
-
-words_to_lines:
- gradient: 0.6
- max_x_dist: 20
- max_running_y_shift_degree: 10 #degrees
- y_overlap_threshold: 0.5
- word_formation_mode: line
diff --git a/cope2n-ai-fi/modules/ocr_engine/src/dto.py b/cope2n-ai-fi/modules/ocr_engine/src/dto.py
deleted file mode 100755
index 8dae901..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/src/dto.py
+++ /dev/null
@@ -1,534 +0,0 @@
-import numpy as np
-from typing import Optional, List, Union
-import cv2
-from PIL import Image
-from pathlib import Path
-from .utils import visualize_bbox_and_label
-
-
-class Box:
- def __init__(
- self, x1: int, y1: int, x2: int, y2: int, conf: float = -1.0, label: str = ""
- ):
- self._x1 = x1
- self._y1 = y1
- self._x2 = x2
- self._y2 = y2
- self._conf = conf
- self._label = label
-
- def __repr__(self) -> str:
- return str(self.bbox)
-
- def __str__(self) -> str:
- return str(self.bbox)
-
- def get(self, return_confidence=False) -> Union[list[int], list[Union[float, int]]]:
- return self.bbox if not return_confidence else self.xyxyc
-
- def __getitem__(self, key):
- return self.bbox[key]
-
- @property
- def width(self):
- return max(self._x2 - self._x1, -1)
-
- @property
- def height(self):
- return max(self._y2 - self._y1, -1)
-
- @property
- def bbox(self) -> list[int]:
- return [self._x1, self._y1, self._x2, self._y2]
-
- @bbox.setter
- def bbox(self, bbox_: list[int]):
- self._x1, self._y1, self._x2, self._y2 = bbox_
-
- @property
- def xyxyc(self) -> list[Union[float, int]]:
- return [self._x1, self._y1, self._x2, self._y2, self._conf]
-
- @staticmethod
- def normalize_bbox(bbox: list[int]) -> list[int]:
- return [int(b) for b in bbox]
-
- def to_int(self):
- self._x1, self._y1, self._x2, self._y2 = self.normalize_bbox(
- [self._x1, self._y1, self._x2, self._y2]
- )
- return self
-
- @staticmethod
- def clamp_bbox_by_img_wh(bbox: list, width: int, height: int) -> list[int]:
- x1, y1, x2, y2 = bbox
- x1 = min(max(0, x1), width)
- x2 = min(max(0, x2), width)
- y1 = min(max(0, y1), height)
- y2 = min(max(0, y2), height)
- return [x1, y1, x2, y2]
-
- def clamp_by_img_wh(self, width: int, height: int):
- self._x1, self._y1, self._x2, self._y2 = self.clamp_bbox_by_img_wh(
- [self._x1, self._y1, self._x2, self._y2], width, height
- )
- return self
-
- @staticmethod
- def extend_bbox(bbox: list, margin: list): # -> Self (python3.11)
- margin_l, margin_t, margin_r, margin_b = margin
- l, t, r, b = bbox # left, top, right, bottom
- t = t - (b - t) * margin_t
- b = b + (b - t) * margin_b
- l = l - (r - l) * margin_l
- r = r + (r - l) * margin_r
- return [l, t, r, b]
-
- def get_extend_bbox(self, margin: list):
- extended_bbox = self.extend_bbox(self.bbox, margin)
- return Box(*extended_bbox, label=self._label)
-
- @staticmethod
- def bbox_is_valid(bbox: list[int]) -> bool:
- if bbox == [-1, -1, -1, -1]:
- raise ValueError("Empty bounding box found")
- l, t, r, b = bbox # left, top, right, bottom
- return True if (b - t) * (r - l) > 0 else False
-
- def is_valid(self) -> bool:
- return self.bbox_is_valid(self.bbox)
-
- @staticmethod
- def crop_img_by_bbox(img: np.ndarray, bbox: list) -> np.ndarray:
- l, t, r, b = bbox
- return img[t:b, l:r]
-
- def crop_img(self, img: np.ndarray) -> np.ndarray:
- return self.crop_img_by_bbox(img, self.bbox)
-
-
-class Word:
- def __init__(
- self,
- image=None,
- text="",
- conf_cls=-1.0,
- bbox_obj: Box = Box(-1, -1, -1, -1),
- conf_detect=-1.0,
- kie_label="",
- ):
- # self.type = "word"
- self._text = text
- self._image = image
- self._conf_det = conf_detect
- self._conf_cls = conf_cls
- # [left, top,right,bot] coordinate of top-left and bottom-right point
- self._bbox_obj = bbox_obj
- # self.word_id = 0 # id of word
- # self.word_group_id = 0 # id of word_group which instance belongs to
- # self.line_id = 0 # id of line which instance belongs to
- # self.paragraph_id = 0 # id of line which instance belongs to
- self._kie_label = kie_label
-
- @property
- def bbox(self) -> list[int]:
- return self._bbox_obj.bbox
-
- @property
- def text(self) -> str:
- return self._text
-
- @property
- def height(self):
- return self._bbox_obj.height
-
- @property
- def width(self):
- return self._bbox_obj.width
-
- def __repr__(self) -> str:
- return self._text
-
- def __str__(self) -> str:
- return self._text
-
- def is_valid(self) -> bool:
- return self._bbox_obj.is_valid()
-
- # def is_special_word(self):
- # if not self._text:
- # raise ValueError("Cannot validatie size of empty bounding box")
-
- # # if len(text) > 7:
- # # return True
- # if len(self._text) >= 7:
- # no_digits = sum(c.isdigit() for c in text)
- # return no_digits / len(text) >= 0.3
-
- # return False
-
-
-class WordGroup:
- def __init__(
- self,
- list_words: List[Word] = list(),
- text: str = "",
- boundingbox: Box = Box(-1, -1, -1, -1),
- conf_cls: float = -1,
- conf_det: float = -1,
- ):
- # self.type = "word_group"
- self._list_words = list_words # dict of word instances
- # self.word_group_id = 0 # word group id
- # self.line_id = 0 # id of line which instance belongs to
- # self.paragraph_id = 0 # id of paragraph which instance belongs to
- self._text = text
- self._bbox_obj = boundingbox
- self._kie_label = ""
- self._conf_cls = conf_cls
- self._conf_det = conf_det
-
- @property
- def bbox(self) -> list[int]:
- return self._bbox_obj.bbox
-
- @property
- def text(self) -> str:
- return self._text
-
- @property
- def list_words(self) -> list[Word]:
- return self._list_words
-
- def __repr__(self) -> str:
- return self._text
-
- def __str__(self) -> str:
- return self._text
-
- # def add_word(self, word: Word): # add a word instance to the word_group
- # if word._text != "✪":
- # for w in self._list_words:
- # if word.word_id == w.word_id:
- # print("Word id collision")
- # return False
- # word.word_group_id = self.word_group_id #
- # word.line_id = self.line_id
- # word.paragraph_id = self.paragraph_id
- # self._list_words.append(word)
- # self._text += " " + word._text
- # if self.bbox_obj == [-1, -1, -1, -1]:
- # self.bbox_obj = word._bbox_obj
- # else:
- # self.bbox_obj = [
- # min(self.bbox_obj[0], word._bbox_obj[0]),
- # min(self.bbox_obj[1], word._bbox_obj[1]),
- # max(self.bbox_obj[2], word._bbox_obj[2]),
- # max(self.bbox_obj[3], word._bbox_obj[3]),
- # ]
- # return True
- # else:
- # return False
-
- # def update_word_group_id(self, new_word_group_id):
- # self.word_group_id = new_word_group_id
- # for i in range(len(self._list_words)):
- # self._list_words[i].word_group_id = new_word_group_id
-
- # def update_kie_label(self):
- # list_kie_label = [word._kie_label for word in self._list_words]
- # dict_kie = dict()
- # for label in list_kie_label:
- # if label not in dict_kie:
- # dict_kie[label] = 1
- # else:
- # dict_kie[label] += 1
- # total = len(list(dict_kie.values()))
- # max_value = max(list(dict_kie.values()))
- # list_keys = list(dict_kie.keys())
- # list_values = list(dict_kie.values())
- # self.kie_label = list_keys[list_values.index(max_value)]
-
- # def update_text(self): # update text after changing positions of words in list word
- # text = ""
- # for word in self._list_words:
- # text += " " + word._text
- # self._text = text
-
-
-class Line:
- def __init__(
- self,
- list_word_groups: List[WordGroup] = [],
- text: str = "",
- boundingbox: Box = Box(-1, -1, -1, -1),
- conf_cls: float = -1,
- conf_det: float = -1,
- ):
- # self.type = "line"
- self._list_word_groups = (
- list_word_groups # list of Word_group instances in the line
- )
- # self.line_id = 0 # id of line in the paragraph
- # self.paragraph_id = 0 # id of paragraph which instance belongs to
- self._text = text
- self._bbox_obj = boundingbox
- self._conf_cls = conf_cls
- self._conf_det = conf_det
-
- @property
- def bbox(self) -> list[int]:
- return self._bbox_obj.bbox
-
- @property
- def text(self) -> str:
- return self._text
-
- @property
- def list_word_groups(self) -> List[WordGroup]:
- return self._list_word_groups
-
- @property
- def list_words(self) -> list[Word]:
- return [
- word
- for word_group in self._list_word_groups
- for word in word_group.list_words
- ]
-
- def __repr__(self) -> str:
- return self._text
-
- def __str__(self) -> str:
- return self._text
-
- # def add_group(self, word_group: WordGroup): # add a word_group instance
- # if word_group._list_words is not None:
- # for wg in self.list_word_groups:
- # if word_group.word_group_id == wg.word_group_id:
- # print("Word_group id collision")
- # return False
-
- # self.list_word_groups.append(word_group)
- # self.text += word_group._text
- # word_group.paragraph_id = self.paragraph_id
- # word_group.line_id = self.line_id
-
- # for i in range(len(word_group._list_words)):
- # word_group._list_words[
- # i
- # ].paragraph_id = self.paragraph_id # set paragraph_id for word
- # word_group._list_words[i].line_id = self.line_id # set line_id for word
- # return True
- # return False
-
- # def update_line_id(self, new_line_id):
- # self.line_id = new_line_id
- # for i in range(len(self.list_word_groups)):
- # self.list_word_groups[i].line_id = new_line_id
- # for j in range(len(self.list_word_groups[i]._list_words)):
- # self.list_word_groups[i]._list_words[j].line_id = new_line_id
-
- # def merge_word(self, word): # word can be a Word instance or a Word_group instance
- # if word.text != "✪":
- # if self.boundingbox == [-1, -1, -1, -1]:
- # self.boundingbox = word.boundingbox
- # else:
- # self.boundingbox = [
- # min(self.boundingbox[0], word.boundingbox[0]),
- # min(self.boundingbox[1], word.boundingbox[1]),
- # max(self.boundingbox[2], word.boundingbox[2]),
- # max(self.boundingbox[3], word.boundingbox[3]),
- # ]
- # self.list_word_groups.append(word)
- # self.text += " " + word.text
- # return True
- # return False
-
- # def __cal_ratio(self, top1, bottom1, top2, bottom2):
- # sorted_vals = sorted([top1, bottom1, top2, bottom2])
- # intersection = sorted_vals[2] - sorted_vals[1]
- # min_height = min(bottom1 - top1, bottom2 - top2)
- # if min_height == 0:
- # return -1
- # ratio = intersection / min_height
- # return ratio
-
- # def __cal_ratio_height(self, top1, bottom1, top2, bottom2):
-
- # height1, height2 = top1 - bottom1, top2 - bottom2
- # ratio_height = float(max(height1, height2)) / float(min(height1, height2))
- # return ratio_height
-
- # def in_same_line(self, input_line, thresh=0.7):
- # # calculate iou in vertical direction
- # _, top1, _, bottom1 = self.boundingbox
- # _, top2, _, bottom2 = input_line.boundingbox
-
- # ratio = self.__cal_ratio(top1, bottom1, top2, bottom2)
- # ratio_height = self.__cal_ratio_height(top1, bottom1, top2, bottom2)
-
- # if (
- # (top2 <= top1 <= bottom2) or (top1 <= top2 <= bottom1)
- # and ratio >= thresh
- # and (ratio_height < 2)
- # ):
- # return True
- # return False
-
-
-# class Paragraph:
-# def __init__(self, id=0, lines=None):
-# self.list_lines = lines if lines is not None else [] # list of all lines in the paragraph
-# self.paragraph_id = id # index of paragraph in the ist of paragraph
-# self.text = ""
-# self.boundingbox = [-1, -1, -1, -1]
-
-# @property
-# def bbox(self):
-# return self.boundingbox
-
-# def __repr__(self) -> str:
-# return self.text
-
-# def __str__(self) -> str:
-# return self.text
-
-# def add_line(self, line: Line): # add a line instance
-# if line.list_word_groups is not None:
-# for l in self.list_lines:
-# if line.line_id == l.line_id:
-# print("Line id collision")
-# return False
-# for i in range(len(line.list_word_groups)):
-# line.list_word_groups[
-# i
-# ].paragraph_id = (
-# self.paragraph_id
-# ) # set paragraph id for every word group in line
-# for j in range(len(line.list_word_groups[i]._list_words)):
-# line.list_word_groups[i]._list_words[
-# j
-# ].paragraph_id = (
-# self.paragraph_id
-# ) # set paragraph id for every word in word groups
-# line.paragraph_id = self.paragraph_id # set paragraph id for line
-# self.list_lines.append(line) # add line to paragraph
-# self.text += " " + line.text
-# return True
-# else:
-# return False
-
-# def update_paragraph_id(
-# self, new_paragraph_id
-# ): # update new paragraph_id for all lines, word_groups, words inside paragraph
-# self.paragraph_id = new_paragraph_id
-# for i in range(len(self.list_lines)):
-# self.list_lines[
-# i
-# ].paragraph_id = new_paragraph_id # set new paragraph_id for line
-# for j in range(len(self.list_lines[i].list_word_groups)):
-# self.list_lines[i].list_word_groups[
-# j
-# ].paragraph_id = new_paragraph_id # set new paragraph_id for word_group
-# for k in range(len(self.list_lines[i].list_word_groups[j].list_words)):
-# self.list_lines[i].list_word_groups[j].list_words[
-# k
-# ].paragraph_id = new_paragraph_id # set new paragraph id for word
-# return True
-
-
-class Page:
- def __init__(
- self,
- word_segments: Union[List[WordGroup], List[Line]],
- image: np.ndarray,
- deskewed_image: Optional[np.ndarray] = None,
- ) -> None:
- self._word_segments = word_segments
- self._image = image
- self._deskewed_image = deskewed_image
- self._drawed_image: Optional[np.ndarray] = None
-
- @property
- def word_segments(self):
- return self._word_segments
-
- @property
- def list_words(self) -> list[Word]:
- return [
- word
- for word_segment in self._word_segments
- for word in word_segment.list_words
- ]
-
- @property
- def image(self):
- return self._image
-
- @property
- def PIL_image(self):
- return Image.fromarray(self._image)
-
- @property
- def drawed_image(self):
- return self._drawed_image
-
- @property
- def deskewed_image(self):
- return self._deskewed_image
-
- def visualize_bbox_and_label(self, **kwargs: dict):
- if self._drawed_image is not None:
- return self._drawed_image
- bboxes = list()
- texts = list()
- for word in self.list_words:
- bboxes.append([int(float(b)) for b in word.bbox])
- texts.append(word._text)
- img = visualize_bbox_and_label(
- self._deskewed_image if self._deskewed_image is not None else self._image,
- bboxes,
- texts,
- **kwargs
- )
- self._drawed_image = img
- return self._drawed_image
-
- def save_img(self, save_path: str, **kwargs: dict) -> None:
- save_path_deskew = kwargs.pop("save_path_deskew", Path(save_path).with_stem(Path(save_path).stem + "_deskewed").as_posix())
- if self._deskewed_image is not None:
- # save_path_deskew: str = kwargs.pop("save_path_deskew", Path(save_path).with_stem(Path(save_path).stem + "_deskewed").as_posix()) # type: ignore
- cv2.imwrite(save_path_deskew, self._deskewed_image)
-
- img = self.visualize_bbox_and_label(**kwargs)
- cv2.imwrite(save_path, img)
-
-
- def write_to_file(self, mode: str, save_path: str) -> None:
- f = open(save_path, "w+", encoding="utf-8")
- for word_segment in self._word_segments:
- if mode == "segment":
- xmin, ymin, xmax, ymax = word_segment.bbox
- f.write(
- "{}\t{}\t{}\t{}\t{}\n".format(
- xmin, ymin, xmax, ymax, word_segment._text
- )
- )
- elif mode == "word":
- for word in word_segment.list_words:
- # xmin, ymin, xmax, ymax = word.bbox
- xmin, ymin, xmax, ymax = [int(float(b)) for b in word.bbox]
- f.write(
- "{}\t{}\t{}\t{}\t{}\n".format(
- xmin, ymin, xmax, ymax, word._text
- )
- )
- else:
- raise NotImplementedError("Unknown mode: {}".format(mode))
- f.close()
-
-
-class Document:
- def __init__(self, lpages: List[Page]) -> None:
- self.lpages = lpages
diff --git a/cope2n-ai-fi/modules/ocr_engine/src/ocr.py b/cope2n-ai-fi/modules/ocr_engine/src/ocr.py
deleted file mode 100755
index 280d0b2..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/src/ocr.py
+++ /dev/null
@@ -1,258 +0,0 @@
-from typing import Union, overload, List, Optional, Tuple
-from PIL import Image
-import torch
-import numpy as np
-import yaml
-from pathlib import Path
-import mmcv
-from sdsvtd import StandaloneYOLOXRunner
-from sdsvtr import StandaloneSATRNRunner
-from sdsv_dewarp.api import AlignImage
-
-from .utils import ImageReader, chunks, Timer, post_process_recog # rotate_bbox
-
-# from .utils import jdeskew as deskew
-# from externals.deskew.sdsv_dewarp import pdeskew as deskew
-# from .utils import deskew
-from .dto import Word, Line, Page, Document, Box, WordGroup
-
-# from .word_formation import words_to_lines as words_to_lines
-# from .word_formation import wo rds_to_lines_mmocr as words_to_lines
-from .word_formation import words_formation_mmocr_tesseract as word_formation
-
-DEFAULT_SETTING_PATH = str(Path(__file__).parents[1]) + "/settings.yml"
-
-
-class OcrEngine:
- def __init__(self, settings_file: str = DEFAULT_SETTING_PATH, **kwargs):
- """Warper of text detection and text recognition
- :param settings_file: path to default setting file
- :param kwargs: keyword arguments to overwrite the default settings file
- """
- with open(settings_file) as f:
- # use safe_load instead load
- self._settings = yaml.safe_load(f)
- self._update_configs(kwargs)
-
- self._ensure_device()
- self._detector = StandaloneYOLOXRunner(**self._settings["detector"])
- self._recognizer = StandaloneSATRNRunner(**self._settings["recognizer"])
- self._deskewer = self._load_deskewer()
-
- def _update_configs(self, params):
- for key, para in params.items(): # overwrite default settings by keyword arguments
- if key not in self._settings:
- raise ValueError("Invalid setting found in OcrEngine: ", k)
- if key == "device":
- self._settings[key] = para
- self._settings["detector"][key] = para
- self._settings["recognizer"][key] = para
- self._settings["deskew"][key] = para
- else:
- for k, v in para.items():
- if isinstance(v, dict):
- for sub_key, sub_value in v.items():
- self._settings[key][k][sub_key] = sub_value
- else:
- self._settings[key][k] = v
-
- def _load_deskewer(self) -> Optional[AlignImage]:
- if self._settings["deskew"]["enable"]:
- deskewer = AlignImage(
- **{k: v for k, v in self._settings["deskew"].items() if k != "enable"}
- )
- print(
- "[WARNING]: Deskew is enabled. The bounding boxes prediction may not be aligned with the original image. In case of using these predictions for pseudo-label, turn on save_deskewed option and use the saved deskewed images instead for further proceed."
- )
- return deskewer
- return None
-
- def _ensure_device(self):
- if "cuda" in self._settings["device"]:
- if not torch.cuda.is_available():
- print("[WARNING]: CUDA is not available, running with cpu instead")
- self._settings["device"] = "cpu"
-
- @property
- def version(self):
- return {
- "detector": self._settings["detector"],
- "recognizer": self._settings["recognizer"],
- }
-
- @property
- def settings(self):
- return self._settings
-
- # @staticmethod
- # def xyxyc_to_xyxy_c(xyxyc: np.ndarray) -> Tuple[List[list], list]:
- # '''
- # convert sdsvtd yoloX detection output to list of bboxes and list of confidences
- # @param xyxyc: array of shape (n, 5)
- # '''
- # xyxy = xyxyc[:, :4].tolist()
- # confs = xyxyc[:, 4].tolist()
- # return xyxy, confs
- # -> Tuple[np.ndarray, List[Box]]:
-
- def preprocess(self, img: np.ndarray) -> tuple[np.ndarray, bool, float]:
- img_ = img.copy()
- if self._settings["max_img_size"]:
- img_ = mmcv.imrescale(
- img,
- tuple(self._settings["max_img_size"]),
- return_scale=False,
- interpolation="bilinear",
- backend="cv2",
- )
- is_blank = False
- if self._deskewer:
- with Timer("deskew"):
- img_, is_blank, angle = self._deskewer(img_)
- return img, is_blank, angle # replace img_ to img
- # for i, bbox in enumerate(bboxes):
- # rotated_bbox = rotate_bbox(bbox, angle, img.shape[:2])
- # bboxes[i].bbox = rotated_bbox
- return img, is_blank, 0
-
- def run_detect(
- self, img: np.ndarray, return_raw: bool = False
- ) -> Tuple[np.ndarray, Union[List[Box], List[list]]]:
- """
- run text detection and return list of xyxyc if return_confidence is True, otherwise return a list of xyxy
- """
- pred_det = self._detector(img)
- if self._settings["detector"]["auto_rotate"]:
- img, pred_det = pred_det
- pred_det = pred_det[0] # only image at a time
- return (
- (img, pred_det.tolist())
- if return_raw
- else (img, [Box(*xyxyc) for xyxyc in pred_det.tolist()])
- )
-
- def run_recog(
- self, imgs: List[np.ndarray]
- ) -> Union[List[str], List[Tuple[str, float]]]:
- if len(imgs) == 0:
- return list()
- pred_rec = self._recognizer(imgs)
- return [
- (post_process_recog(word), conf)
- for word, conf in zip(pred_rec[0], pred_rec[1])
- ]
-
- def read_img(self, img: str) -> np.ndarray:
- return ImageReader.read(img)
-
- def get_cropped_imgs(
- self, img: np.ndarray, bboxes: Union[List[Box], List[list]]
- ) -> Tuple[List[np.ndarray], List[bool]]:
- """
- img: np image
- bboxes: list of xyxy
- """
- lcropped_imgs = list()
- mask = list()
- for bbox in bboxes:
- bbox = Box(*bbox) if isinstance(bbox, list) else bbox
- bbox = bbox.get_extend_bbox(self._settings["extend_bbox"])
-
- bbox.clamp_by_img_wh(img.shape[1], img.shape[0])
- bbox.to_int()
- if not bbox.is_valid():
- mask.append(False)
- continue
- cropped_img = bbox.crop_img(img)
- lcropped_imgs.append(cropped_img)
- mask.append(True)
- return lcropped_imgs, mask
-
- def read_page(
- self, img: np.ndarray, bboxes: Union[List[Box], List[list]]
- ) -> Union[List[WordGroup], List[Line]]:
- if len(bboxes) == 0: # no bbox found
- return list()
- with Timer("cropped imgs"):
- lcropped_imgs, mask = self.get_cropped_imgs(img, bboxes)
- with Timer("recog"):
- # batch_mode for efficiency
- pred_recs = self.run_recog(lcropped_imgs)
- with Timer("construct words"):
- lwords = list()
- for i in range(len(pred_recs)):
- if not mask[i]:
- continue
- text, conf_rec = pred_recs[i][0], pred_recs[i][1]
- bbox = Box(*bboxes[i]) if isinstance(bboxes[i], list) else bboxes[i]
- lwords.append(
- Word(
- image=img,
- text=text,
- conf_cls=conf_rec,
- bbox_obj=bbox,
- conf_detect=bbox._conf,
- )
- )
- with Timer("word formation"):
- return word_formation(
- lwords, img.shape[1], **self._settings["words_to_lines"]
- )[0]
-
- # https://stackoverflow.com/questions/48127642/incompatible-types-in-assignment-on-union
-
- @overload
- def __call__(self, img: Union[str, np.ndarray, Image.Image]) -> Page:
- ...
-
- @overload
- def __call__(self, img: List[Union[str, np.ndarray, Image.Image]]) -> Document:
- ...
-
- def __call__(self, img): # type: ignore #ignoring type before implementing batch_mode
- """
- Accept an image or list of them, return ocr result as a page or document
- """
- with Timer("read image"):
- img = ImageReader.read(img)
- if self._settings["batch_size"] == 1:
- if isinstance(img, list):
- if len(img) == 1:
- img = img[0] # in case input type is a 1 page pdf
- else:
- raise AssertionError(
- "list input can only be used with batch_mode enabled"
- )
- img_deskewed, is_blank, angle = self.preprocess(img)
-
- if is_blank:
- print(
- "[WARNING]: Blank image detected"
- ) # TODO: should we stop the execution here?
- with Timer("detect"):
- img_deskewed, bboxes = self.run_detect(img_deskewed)
- with Timer("read_page"):
- lsegments = self.read_page(img_deskewed, bboxes)
- return Page(lsegments, img, img_deskewed if angle != 0 else None)
- else:
- # lpages = []
- # # chunks to reduce memory footprint
- # for imgs in chunks(img, self._batch_size):
- # # pred_dets = self._detector(imgs)
- # # TEMP: use list comprehension because sdsvtd do not support batch mode of text detection
- # img = self.preprocess(img)
- # img, bboxes = self.run_detect(img)
- # for img_, bboxes_ in zip(imgs, bboxes):
- # llines = self.read_page(img, bboxes_)
- # page = Page(llines, img)
- # lpages.append(page)
- # return Document(lpages)
- raise NotImplementedError("Batch mode is currently not supported")
-
-
-if __name__ == "__main__":
- img_path = "/mnt/ssd1T/hungbnt/Cello/data/PH/Sea7/Sea_7_1.jpg"
- engine = OcrEngine(device="cuda:0")
- # https://stackoverflow.com/questions/66435480/overload-following-optional-argument
- page = engine(img_path) # type: ignore
- print(page._word_segments)
diff --git a/cope2n-ai-fi/modules/ocr_engine/src/utils.py b/cope2n-ai-fi/modules/ocr_engine/src/utils.py
deleted file mode 100755
index 3c4332e..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/src/utils.py
+++ /dev/null
@@ -1,369 +0,0 @@
-from PIL import ImageFont, ImageDraw, Image, ImageOps
-# import matplotlib.pyplot as plt
-import numpy as np
-import cv2
-import os
-import time
-from typing import Generator, Union, List, overload, Tuple, Callable
-import glob
-import math
-from pathlib import Path
-from pdf2image import convert_from_path
-# from deskew import determine_skew
-# from jdeskew.estimator import get_angle
-# from jdeskew.utility import rotate as jrotate
-
-
-def post_process_recog(text: str) -> str:
- text = text.replace("✪", " ")
- return text
-
-
-def find_maximum_without_outliers(lst: list[int], threshold: float = 1.):
- '''
- To find the maximum number in a list while excluding its outlier values, you can follow these steps:
- Determine the range within which you consider values as outliers. This can be based on a specific threshold or a statistical measure such as the interquartile range (IQR).
- Iterate through the list and filter out the outlier values based on the defined range. Keep track of the non-outlier values.
- Find the maximum value among the non-outlier values.
- '''
- # Calculate the lower and upper boundaries for outliers
- q1 = np.percentile(lst, 25)
- q3 = np.percentile(lst, 75)
- iqr = q3 - q1
- lower_bound = q1 - threshold * iqr
- upper_bound = q3 + threshold * iqr
-
- # Filter out outlier values
- non_outliers = [x for x in lst if lower_bound <= x <= upper_bound]
-
- # Find the maximum value among non-outliers
- max_value = max(non_outliers)
-
- return max_value
-
-
-class Timer:
- def __init__(self, name: str) -> None:
- self.name = name
-
- def __enter__(self):
- self.start_time = time.perf_counter()
- return self
-
- def __exit__(self, func: Callable, *args):
- self.end_time = time.perf_counter()
- self.elapsed_time = self.end_time - self.start_time
- print(f"[INFO]: {self.name} took : {self.elapsed_time:.6f} seconds")
-
-
-# def rotate(
-# image: np.ndarray, angle: float, background: Union[int, Tuple[int, int, int]]
-# ) -> np.ndarray:
-# old_width, old_height = image.shape[:2]
-# angle_radian = math.radians(angle)
-# width = abs(np.sin(angle_radian) * old_height) + abs(np.cos(angle_radian) * old_width)
-# height = abs(np.sin(angle_radian) * old_width) + abs(np.cos(angle_radian) * old_height)
-# image_center = tuple(np.array(image.shape[1::-1]) / 2)
-# rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
-# rot_mat[1, 2] += (width - old_width) / 2
-# rot_mat[0, 2] += (height - old_height) / 2
-# return cv2.warpAffine(image, rot_mat, (int(round(height)), int(round(width))), borderValue=background)
-
-
-# def rotate_bbox(bbox: list, angle: float) -> list:
-# # Compute the center point of the bounding box
-# cx = bbox[0] + bbox[2] / 2
-# cy = bbox[1] + bbox[3] / 2
-
-# # Define the scale factor for the rotated bounding box
-# scale = 1.0 # following the deskew and jdeskew function
-# angle_radian = math.radians(angle)
-
-# # Obtain the rotation matrix using cv2.getRotationMatrix2D()
-# M = cv2.getRotationMatrix2D((cx, cy), angle_radian, scale)
-
-# # Apply the rotation matrix to the four corners of the bounding box
-# corners = np.array([[bbox[0], bbox[1]],
-# [bbox[0] + bbox[2], bbox[1]],
-# [bbox[0] + bbox[2], bbox[1] + bbox[3]],
-# [bbox[0], bbox[1] + bbox[3]]], dtype=np.float32)
-# rotated_corners = cv2.transform(np.array([corners]), M)[0]
-
-# # Compute the bounding box of the rotated corners
-# x = int(np.min(rotated_corners[:, 0]))
-# y = int(np.min(rotated_corners[:, 1]))
-# w = int(np.max(rotated_corners[:, 0]) - np.min(rotated_corners[:, 0]))
-# h = int(np.max(rotated_corners[:, 1]) - np.min(rotated_corners[:, 1]))
-# rotated_bbox = [x, y, w, h]
-
-# return rotated_bbox
-
-# def rotate_bbox(bbox: List[int], angle: float, old_shape: Tuple[int, int]) -> List[int]:
-# # https://medium.com/@pokomaru/image-and-bounding-box-rotation-using-opencv-python-2def6c39453
-# bbox_ = [bbox[0], bbox[1], bbox[2], bbox[1], bbox[2], bbox[3], bbox[0], bbox[3]]
-# h, w = old_shape
-# cx, cy = (int(w / 2), int(h / 2))
-
-# bbox_tuple = [
-# (bbox_[0], bbox_[1]),
-# (bbox_[2], bbox_[3]),
-# (bbox_[4], bbox_[5]),
-# (bbox_[6], bbox_[7]),
-# ] # put x and y coordinates in tuples, we will iterate through the tuples and perform rotation
-
-# rotated_bbox = []
-
-# for i, coord in enumerate(bbox_tuple):
-# M = cv2.getRotationMatrix2D((cx, cy), angle, 1.0)
-# cos, sin = abs(M[0, 0]), abs(M[0, 1])
-# newW = int((h * sin) + (w * cos))
-# newH = int((h * cos) + (w * sin))
-# M[0, 2] += (newW / 2) - cx
-# M[1, 2] += (newH / 2) - cy
-# v = [coord[0], coord[1], 1]
-# adjusted_coord = np.dot(M, v)
-# rotated_bbox.insert(i, (adjusted_coord[0], adjusted_coord[1]))
-# result = [int(x) for t in rotated_bbox for x in t]
-# return [result[i] for i in [0, 1, 2, -1]] # reformat to xyxy
-
-
-# def deskew(image: np.ndarray) -> Tuple[np.ndarray, float]:
-# grayscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
-# angle = 0.
-# try:
-# angle = determine_skew(grayscale)
-# except Exception:
-# pass
-# rotated = rotate(image, angle, (0, 0, 0)) if angle else image
-# return rotated, angle
-
-
-# def jdeskew(image: np.ndarray) -> Tuple[np.ndarray, float]:
-# angle = 0.
-# try:
-# angle = get_angle(image)
-# except Exception:
-# pass
-# # TODO: change resize = True and scale the bounding box
-# rotated = jrotate(image, angle, resize=False) if angle else image
-# return rotated, angle
-# def deskew()
-
-class ImageReader:
- """
- accept anything, return numpy array image
- """
- supported_ext = [".png", ".jpg", ".jpeg", ".pdf", ".gif"]
-
- @staticmethod
- def validate_img_path(img_path: str) -> None:
- if not os.path.exists(img_path):
- raise FileNotFoundError(img_path)
- if os.path.isdir(img_path):
- raise IsADirectoryError(img_path)
- if not Path(img_path).suffix.lower() in ImageReader.supported_ext:
- raise NotImplementedError("Not supported extension at {}".format(img_path))
-
- @overload
- @staticmethod
- def read(img: Union[str, np.ndarray, Image.Image]) -> np.ndarray: ...
-
- @overload
- @staticmethod
- def read(img: List[Union[str, np.ndarray, Image.Image]]) -> List[np.ndarray]: ...
-
- @overload
- @staticmethod
- def read(img: str) -> List[np.ndarray]: ... # for pdf or directory
-
- @staticmethod
- def read(img):
- if isinstance(img, list):
- return ImageReader.from_list(img)
- elif isinstance(img, str) and os.path.isdir(img):
- return ImageReader.from_dir(img)
- elif isinstance(img, str) and img.endswith(".pdf"):
- return ImageReader.from_pdf(img)
- else:
- return ImageReader._read(img)
-
- @staticmethod
- def from_dir(dir_path: str) -> List[np.ndarray]:
- if os.path.isdir(dir_path):
- image_files = glob.glob(os.path.join(dir_path, "*"))
- return ImageReader.from_list(image_files)
- else:
- raise NotADirectoryError(dir_path)
-
- @staticmethod
- def from_str(img_path: str) -> np.ndarray:
- ImageReader.validate_img_path(img_path)
- return ImageReader.from_PIL(Image.open(img_path))
-
- @staticmethod
- def from_np(img_array: np.ndarray) -> np.ndarray:
- return img_array
-
- @staticmethod
- def from_PIL(img_pil: Image.Image, transpose=True) -> np.ndarray:
- # if img_pil.is_animated:
- # raise NotImplementedError("Only static images are supported, animated image found")
- if transpose:
- img_pil = ImageOps.exif_transpose(img_pil)
- if img_pil.mode != "RGB":
- img_pil = img_pil.convert("RGB")
-
- return np.array(img_pil)
-
- @staticmethod
- def from_list(img_list: List[Union[str, np.ndarray, Image.Image]]) -> List[np.ndarray]:
- limgs = list()
- for img_path in img_list:
- try:
- if isinstance(img_path, str):
- ImageReader.validate_img_path(img_path)
- limgs.append(ImageReader._read(img_path))
- except (FileNotFoundError, NotImplementedError, IsADirectoryError) as e:
- print("[ERROR]: ", e)
- print("[INFO]: Skipping image {}".format(img_path))
- return limgs
-
- @staticmethod
- def from_pdf(pdf_path: str, start_page: int = 0, end_page: int = 0) -> List[np.ndarray]:
- pdf_file = convert_from_path(pdf_path)
- if end_page is not None:
- end_page = min(len(pdf_file), end_page + 1)
- limgs = [np.array(pdf_page) for pdf_page in pdf_file[start_page:end_page]]
- return limgs
-
- @staticmethod
- def _read(img: Union[str, np.ndarray, Image.Image]) -> np.ndarray:
- if isinstance(img, str):
- return ImageReader.from_str(img)
- elif isinstance(img, Image.Image):
- return ImageReader.from_PIL(img)
- elif isinstance(img, np.ndarray):
- return ImageReader.from_np(img)
- else:
- raise ValueError("Invalid img argument type: ", type(img))
-
-
-def get_name(file_path, ext: bool = True):
- file_path_ = os.path.basename(file_path)
- return file_path_ if ext else os.path.splitext(file_path_)[0]
-
-
-def construct_file_path(dir, file_path, ext=''):
- '''
- args:
- dir: /path/to/dir
- file_path /example_path/to/file.txt
- ext = '.json'
- return
- /path/to/dir/file.json
- '''
- return os.path.join(
- dir, get_name(file_path,
- True)) if ext == '' else os.path.join(
- dir, get_name(file_path,
- False)) + ext
-
-
-def chunks(lst: list, n: int) -> Generator:
- """
- Yield successive n-sized chunks from lst.
- https://stackoverflow.com/questions/312443/how-do-i-split-a-list-into-equally-sized-chunks
- """
- for i in range(0, len(lst), n):
- yield lst[i:i + n]
-
-
-def read_ocr_result_from_txt(file_path: str) -> Tuple[list, list]:
- '''
- return list of bounding boxes, list of words
- '''
- with open(file_path, 'r') as f:
- lines = f.read().splitlines()
- boxes, words = [], []
- for line in lines:
- if line == "":
- continue
- x1, y1, x2, y2, text = line.split("\t")
- x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
- if text and text != " ":
- words.append(text)
- boxes.append((x1, y1, x2, y2))
- return boxes, words
-
-
-def get_xyxywh_base_on_format(bbox, format):
- if format == "xywh":
- x1, y1, w, h = bbox[0], bbox[1], bbox[2], bbox[3]
- x2, y2 = x1 + w, y1 + h
- elif format == "xyxy":
- x1, y1, x2, y2 = bbox
- w, h = x2 - x1, y2 - y1
- else:
- raise NotImplementedError("Invalid format {}".format(format))
- return (x1, y1, x2, y2, w, h)
-
-
-def get_dynamic_params_for_bbox_of_label(text, x1, y1, w, h, img_h, img_w, font, font_scale_offset=1):
- font_scale_factor = img_h / (img_w + img_h) * font_scale_offset
- font_scale = w / (w + h) * font_scale_factor # adjust font scale by width height
- thickness = int(font_scale_factor) + 1
- (text_width, text_height) = cv2.getTextSize(text, font, fontScale=font_scale, thickness=thickness)[0]
- text_offset_x = x1
- text_offset_y = y1 - thickness
- box_coords = ((text_offset_x, text_offset_y + 1), (text_offset_x + text_width - 2, text_offset_y - text_height - 2))
- return (font_scale, thickness, text_height, box_coords)
-
-
-def visualize_bbox_and_label(
- img, bboxes, texts, bbox_color=(200, 180, 60),
- text_color=(0, 0, 0),
- format="xyxy", is_vnese=False, draw_text=True):
- ori_img_type = type(img)
- if is_vnese:
- img = Image.fromarray(img) if ori_img_type is np.ndarray else img
- draw = ImageDraw.Draw(img)
- img_w, img_h = img.size
- font_pil_str = "fonts/arial.ttf"
- font_cv2 = cv2.FONT_HERSHEY_SIMPLEX
- else:
- img_h, img_w = img.shape[0], img.shape[1]
- font_cv2 = cv2.FONT_HERSHEY_SIMPLEX
- for i in range(len(bboxes)):
- text = texts[i] # text = "{}: {:.0f}%".format(LABELS[classIDs[i]], confidences[i]*100)
- x1, y1, x2, y2, w, h = get_xyxywh_base_on_format(bboxes[i], format)
- font_scale, thickness, text_height, box_coords = get_dynamic_params_for_bbox_of_label(
- text, x1, y1, w, h, img_h, img_w, font=font_cv2)
- if is_vnese:
- font_pil = ImageFont.truetype(font_pil_str, size=text_height) # type: ignore
- fdraw_text = draw.text # type: ignore
- fdraw_bbox = draw.rectangle # type: ignore
- # Pil use different coordinate => y = y+thickness = y-thickness + 2*thickness
- arg_text = ((box_coords[0][0], box_coords[1][1]), text)
- kwarg_text = {"font": font_pil, "fill": text_color, "width": thickness}
- arg_rec = ((x1, y1, x2, y2),)
- kwarg_rec = {"outline": bbox_color, "width": thickness}
- arg_rec_text = ((box_coords[0], box_coords[1]),)
- kwarg_rec_text = {"fill": bbox_color, "width": thickness}
- else:
- # cv2.rectangle(img, box_coords[0], box_coords[1], color, cv2.FILLED)
- # cv2.putText(img, text, (text_offset_x, text_offset_y), font, fontScale=font_scale, color=(50, 0,0), thickness=thickness)
- # cv2.rectangle(img, (x1, y1), (x2, y2), color, thickness)
- fdraw_text = cv2.putText
- fdraw_bbox = cv2.rectangle
- arg_text = (img, text, box_coords[0])
- kwarg_text = {"fontFace": font_cv2, "fontScale": font_scale, "color": text_color, "thickness": thickness}
- arg_rec = (img, (x1, y1), (x2, y2))
- kwarg_rec = {"color": bbox_color, "thickness": thickness}
- arg_rec_text = (img, box_coords[0], box_coords[1])
- kwarg_rec_text = {"color": bbox_color, "thickness": cv2.FILLED}
- # draw a bounding box rectangle and label on the img
- fdraw_bbox(*arg_rec, **kwarg_rec) # type: ignore
- if draw_text:
- fdraw_bbox(*arg_rec_text, **kwarg_rec_text) # type: ignore
- fdraw_text(*arg_text, **kwarg_text) # type: ignore # text have to put in front of rec_text
- return np.array(img) if ori_img_type is np.ndarray and is_vnese else img
diff --git a/cope2n-ai-fi/modules/ocr_engine/src/word_formation.py b/cope2n-ai-fi/modules/ocr_engine/src/word_formation.py
deleted file mode 100755
index 3e64b97..0000000
--- a/cope2n-ai-fi/modules/ocr_engine/src/word_formation.py
+++ /dev/null
@@ -1,903 +0,0 @@
-from builtins import dict
-from .dto import Word, Line, WordGroup, Box
-from .utils import find_maximum_without_outliers
-import numpy as np
-from typing import Optional, List, Tuple, Union
-
-############################################################################################################################################################################################################################
-############################################################################################################################################################################################################################
-### WORDS TO LINES ALGORITHMS FROM MMOCR AND TESSERACT ###############################################################################################################################################################################
-############################################################################################################################################################################################################################
-############################################################################################################################################################################################################################
-
-DEGREE_TO_RADIAN_COEF = np.pi / 180
-MAX_INT = int(2e10 + 9)
-MIN_INT = -MAX_INT
-
-
-def is_on_same_line(box_a, box_b, min_y_overlap_ratio=0.8):
- """Check if two boxes are on the same line by their y-axis coordinates.
-
- Two boxes are on the same line if they overlap vertically, and the length
- of the overlapping line segment is greater than min_y_overlap_ratio * the
- height of either of the boxes.
-
- Args:
- box_a (list), box_b (list): Two bounding boxes to be checked
- min_y_overlap_ratio (float): The minimum vertical overlapping ratio
- allowed for boxes in the same line
-
- Returns:
- The bool flag indicating if they are on the same line
- """
- a_y_min = np.min(box_a[1::2])
- b_y_min = np.min(box_b[1::2])
- a_y_max = np.max(box_a[1::2])
- b_y_max = np.max(box_b[1::2])
-
- # Make sure that box a is always the box above another
- if a_y_min > b_y_min:
- a_y_min, b_y_min = b_y_min, a_y_min
- a_y_max, b_y_max = b_y_max, a_y_max
-
- if b_y_min <= a_y_max:
- if min_y_overlap_ratio is not None:
- sorted_y = sorted([b_y_min, b_y_max, a_y_max])
- overlap = sorted_y[1] - sorted_y[0]
- min_a_overlap = (a_y_max - a_y_min) * min_y_overlap_ratio
- min_b_overlap = (b_y_max - b_y_min) * min_y_overlap_ratio
- return overlap >= min_a_overlap or \
- overlap >= min_b_overlap
- else:
- return True
- return False
-
-
-def merge_bboxes_to_group(bboxes_group, x_sorted_boxes):
- merged_bboxes = []
- for box_group in bboxes_group:
- merged_box = {}
- merged_box['text'] = ' '.join(
- [x_sorted_boxes[idx]['text'] for idx in box_group])
- x_min, y_min = float('inf'), float('inf')
- x_max, y_max = float('-inf'), float('-inf')
- for idx in box_group:
- x_max = max(np.max(x_sorted_boxes[idx]['box'][::2]), x_max)
- x_min = min(np.min(x_sorted_boxes[idx]['box'][::2]), x_min)
- y_max = max(np.max(x_sorted_boxes[idx]['box'][1::2]), y_max)
- y_min = min(np.min(x_sorted_boxes[idx]['box'][1::2]), y_min)
- merged_box['box'] = [
- x_min, y_min, x_max, y_min, x_max, y_max, x_min, y_max
- ]
- merged_box['list_words'] = [x_sorted_boxes[idx]['word']
- for idx in box_group]
- merged_bboxes.append(merged_box)
- return merged_bboxes
-
-
-def stitch_boxes_into_lines(boxes, max_x_dist=10, min_y_overlap_ratio=0.3):
- """Stitch fragmented boxes of words into lines.
-
- Note: part of its logic is inspired by @Johndirr
- (https://github.com/faustomorales/keras-ocr/issues/22)
-
- Args:
- boxes (list): List of ocr results to be stitched
- max_x_dist (int): The maximum horizontal distance between the closest
- edges of neighboring boxes in the same line
- min_y_overlap_ratio (float): The minimum vertical overlapping ratio
- allowed for any pairs of neighboring boxes in the same line
-
- Returns:
- merged_boxes(List[dict]): List of merged boxes and texts
- """
-
- if len(boxes) <= 1:
- if len(boxes) == 1:
- boxes[0]["list_words"] = [boxes[0]["word"]]
- return boxes
-
- # merged_groups = []
- merged_lines = []
-
- # sort groups based on the x_min coordinate of boxes
- x_sorted_boxes = sorted(boxes, key=lambda x: np.min(x['box'][::2]))
- # store indexes of boxes which are already parts of other lines
- skip_idxs = set()
-
- i = 0
- # locate lines of boxes starting from the leftmost one
- for i in range(len(x_sorted_boxes)):
- if i in skip_idxs:
- continue
- # the rightmost box in the current line
- rightmost_box_idx = i
- line = [rightmost_box_idx]
- for j in range(i + 1, len(x_sorted_boxes)):
- if j in skip_idxs:
- continue
- if is_on_same_line(x_sorted_boxes[rightmost_box_idx]['box'],
- x_sorted_boxes[j]['box'], min_y_overlap_ratio):
- line.append(j)
- skip_idxs.add(j)
- rightmost_box_idx = j
-
- # split line into lines if the distance between two neighboring
- # sub-lines' is greater than max_x_dist
- # groups = []
- # line_idx = 0
- # groups.append([line[0]])
- # for k in range(1, len(line)):
- # curr_box = x_sorted_boxes[line[k]]
- # prev_box = x_sorted_boxes[line[k - 1]]
- # dist = np.min(curr_box['box'][::2]) - np.max(prev_box['box'][::2])
- # if dist > max_x_dist:
- # line_idx += 1
- # groups.append([])
- # groups[line_idx].append(line[k])
-
- # # Get merged boxes
- merged_line = merge_bboxes_to_group([line], x_sorted_boxes)
- merged_lines.extend(merged_line)
- # merged_group = merge_bboxes_to_group(groups,x_sorted_boxes)
- # merged_groups.extend(merged_group)
-
- merged_lines = sorted(merged_lines, key=lambda x: np.min(x['box'][1::2]))
- # merged_groups = sorted(merged_groups, key=lambda x: np.min(x['box'][1::2]))
- return merged_lines # , merged_groups
-
-# REFERENCE
-# https://vigneshgig.medium.com/bounding-box-sorting-algorithm-for-text-detection-and-object-detection-from-left-to-right-and-top-cf2c523c8a85
-# https://huggingface.co/spaces/tomofi/MMOCR/blame/main/mmocr/utils/box_util.py
-
-
-def words_to_lines_mmocr(words: List[Word], *args) -> Tuple[List[Line], Optional[int]]:
- bboxes = [{"box": [w.bbox[0], w.bbox[1], w.bbox[2], w.bbox[1], w.bbox[2], w.bbox[3], w.bbox[0], w.bbox[3]],
- "text":w._text, "word":w} for w in words]
- merged_lines = stitch_boxes_into_lines(bboxes)
- merged_groups = merged_lines # TODO: fix code to return both word group and line
- lwords_groups = [WordGroup(list_words=merged_box["list_words"],
- text=merged_box["text"],
- boundingbox=[merged_box["box"][i] for i in [0, 1, 2, -1]])
- for merged_box in merged_groups]
-
- llines = [Line(text=word_group._text, list_word_groups=[word_group], boundingbox=word_group._bbox_obj)
- for word_group in lwords_groups]
-
- return llines, None # same format with the origin words_to_lines
- # lines = [Line() for merged]
-
-
-# def most_overlapping_row(rows, top, bottom, y_shift):
-# max_overlap = -1
-# max_overlap_idx = -1
-# for i, row in enumerate(rows):
-# row_top, row_bottom = row
-# overlap = min(top + y_shift, row_top) - max(bottom + y_shift, row_bottom)
-# if overlap > max_overlap:
-# max_overlap = overlap
-# max_overlap_idx = i
-# return max_overlap_idx
-def most_overlapping_row(rows, row_words, bottom, top, y_shift, max_row_size, y_overlap_threshold=0.5):
- max_overlap = -1
- max_overlap_idx = -1
- overlapping_rows = []
-
- for i, row in enumerate(rows):
- row_bottom, row_top = row
- overlap = min(bottom - y_shift[i], row_bottom) - \
- max(top - y_shift[i], row_top)
-
- if overlap > max_overlap:
- max_overlap = overlap
- max_overlap_idx = i
-
- # if at least overlap 1 pixel and not (overlap too much and overlap too little)
- if (row_top <= bottom and row_bottom >= top) and not (bottom - top - max_overlap > max_row_size * y_overlap_threshold) and not (max_overlap < max_row_size * y_overlap_threshold):
- overlapping_rows.append(i)
-
- # Merge overlapping rows if necessary
- if len(overlapping_rows) > 1:
- merge_bottom = max(rows[i][0] for i in overlapping_rows)
- merge_top = min(rows[i][1] for i in overlapping_rows)
-
- if merge_bottom - merge_top <= max_row_size:
- # Merge rows
- merged_row = (merge_bottom, merge_top)
- merged_words = []
- # Remove other overlapping rows
-
- for row_idx in overlapping_rows[:0:-1]: # [1,2,3] -> 3,2
- merged_words.extend(row_words[row_idx])
- del rows[row_idx]
- del row_words[row_idx]
-
- rows[overlapping_rows[0]] = merged_row
- row_words[overlapping_rows[0]].extend(merged_words[::-1])
- max_overlap_idx = overlapping_rows[0]
-
- if bottom - top - max_overlap > max_row_size * y_overlap_threshold and max_overlap < max_row_size * y_overlap_threshold:
- max_overlap_idx = -1
- return max_overlap_idx
-
-
-def stitch_boxes_into_lines_tesseract(words: list[Word], max_running_y_shift: int,
- gradient: float, y_overlap_threshold: float) -> Tuple[list[list[Word]], float]:
- sorted_words = sorted(words, key=lambda x: x.bbox[0])
- rows = []
- row_words = []
- max_row_size = find_maximum_without_outliers([word.height for word in sorted_words])
- running_y_shift = []
- for _i, word in enumerate(sorted_words):
- bbox, _text = word.bbox, word._text
- _x1, y1, _x2, y2 = bbox
- bottom, top = y2, y1
- max_row_size = max(max_row_size, bottom - top)
- overlap_row_idx = most_overlapping_row(
- rows, row_words, bottom, top, running_y_shift, max_row_size, y_overlap_threshold)
-
- if overlap_row_idx == -1: # No overlapping row found
- new_row = (bottom, top)
- rows.append(new_row)
- row_words.append([word])
- running_y_shift.append(0)
- else: # Overlapping row found
- row_bottom, row_top = rows[overlap_row_idx]
- new_bottom = max(row_bottom, bottom)
- new_top = min(row_top, top)
- rows[overlap_row_idx] = (new_bottom, new_top)
- row_words[overlap_row_idx].append(word)
- new_shift = (top + bottom) / 2 - (row_top + row_bottom) / 2
- running_y_shift[overlap_row_idx] = min(
- gradient * running_y_shift[overlap_row_idx] + (1 - gradient) * new_shift, max_running_y_shift) # update and clamp
-
- # Sort rows and row_texts based on the top y-coordinate
- sorted_rows_data = sorted(zip(rows, row_words), key=lambda x: x[0][1])
- _sorted_rows_idx, sorted_row_words = zip(*sorted_rows_data)
- # /_|<- the perpendicular line of the horizontal line and the skew line of the page
- page_skew_dist = sum(running_y_shift) / len(running_y_shift)
- return sorted_row_words, page_skew_dist
-
-
-def construct_word_groups_tesseract(sorted_row_words: list[list[Word]],
- max_x_dist: int, page_skew_dist: float) -> list[list[list[Word]]]:
- # approximate page_skew_angle by page_skew_dist
- corrected_max_x_dist = max_x_dist * abs(np.cos(page_skew_dist * DEGREE_TO_RADIAN_COEF))
- constructed_row_word_groups = []
- for row_words in sorted_row_words:
- lword_groups = []
- line_idx = 0
- lword_groups.append([row_words[0]])
- for k in range(1, len(row_words)):
- curr_box = row_words[k].bbox
- prev_box = row_words[k - 1].bbox
- dist = curr_box[0] - prev_box[2]
- if dist > corrected_max_x_dist:
- line_idx += 1
- lword_groups.append([])
- lword_groups[line_idx].append(row_words[k])
- constructed_row_word_groups.append(lword_groups)
- return constructed_row_word_groups
-
-
-def group_bbox_and_text(lwords: Union[list[Word], list[WordGroup]]) -> tuple[Box, tuple[str, float]]:
- text = ' '.join([word._text for word in lwords])
- x_min, y_min = MAX_INT, MAX_INT
- x_max, y_max = MIN_INT, MIN_INT
- conf_det = 0
- conf_cls = 0
- for word in lwords:
- x_max = int(max(np.max(word.bbox[::2]), x_max))
- x_min = int(min(np.min(word.bbox[::2]), x_min))
- y_max = int(max(np.max(word.bbox[1::2]), y_max))
- y_min = int(min(np.min(word.bbox[1::2]), y_min))
- conf_det += word._conf_det
- conf_cls += word._conf_cls
- bbox = Box(x_min, y_min, x_max, y_max, conf=conf_det / len(lwords))
- return bbox, (text, conf_cls / len(lwords))
-
-
-def words_to_lines_tesseract(words: List[Word],
- page_width: int, max_running_y_shift_degree: int, gradient: float, max_x_dist: int,
- y_overlap_threshold: float) -> Tuple[List[Line],
- Optional[float]]:
- max_running_y_shift = page_width * np.tan(max_running_y_shift_degree * DEGREE_TO_RADIAN_COEF)
- sorted_row_words, page_skew_dist = stitch_boxes_into_lines_tesseract(
- words, max_running_y_shift, gradient, y_overlap_threshold)
- constructed_row_word_groups = construct_word_groups_tesseract(
- sorted_row_words, max_x_dist, page_skew_dist)
- llines = []
- for row in constructed_row_word_groups:
- lwords_row = []
- lword_groups = []
- for word_group in row:
- bbox_word_group, text_word_group = group_bbox_and_text(word_group)
- lwords_row.extend(word_group)
- lword_groups.append(
- WordGroup(
- list_words=word_group, text=text_word_group[0],
- conf_cls=text_word_group[1],
- boundingbox=bbox_word_group))
- bbox_line, text_line = group_bbox_and_text(lwords_row)
- llines.append(
- Line(
- list_word_groups=lword_groups, text=text_line[0],
- boundingbox=bbox_line, conf_cls=text_line[1]))
- return llines, page_skew_dist
-
-
-
-
-### WORDS TO WORDGROUPS #########################################################################################################################################################################################################################
-
-
-def merge_overlapping_word_groups(
- rows: list[list[int]],
- row_words: list[list[Word]],
- overlapping_rows: list[int],
- max_row_size: int) -> bool:
- # Merge found overlapping rows if necessary
- merge_top = max(rows[i][1] for i in overlapping_rows)
- merge_bottom = min(rows[i][3] for i in overlapping_rows)
- merge_left = min(rows[i][0] for i in overlapping_rows)
- merge_right = max(rows[i][2] for i in overlapping_rows)
-
- if merge_top - merge_bottom <= max_row_size:
- # Merge rows
- merged_row = [merge_left, merge_top, merge_right, merge_bottom]
- merged_words = []
- # Remove other overlapping rows
-
- for row_idx in overlapping_rows[:0:-1]: # [1,2,3] -> 3,2
- merged_words.extend(row_words[row_idx])
- del rows[row_idx]
- del row_words[row_idx]
-
- rows[overlapping_rows[0]] = merged_row
- row_words[overlapping_rows[0]].extend(merged_words[::-1])
- return True
- return False
-
-
-def most_overlapping_word_groups(
- rows, row_words, curr_word_bbox, y_shift, max_row_size, y_overlap_threshold, max_x_dist):
- max_overlap = -1
- max_overlap_idx = -1
- overlapping_rows = []
- left, top, right, bottom = curr_word_bbox
- for i, row in enumerate(rows):
- row_left, row_top, row_right, row_bottom = row
- top_shift = top - y_shift[i]
- bottom_shift = bottom - y_shift[i]
-
- # find the most overlapping row
- overlap = min(bottom_shift, row_bottom) - max(top_shift, row_top)
- if overlap > max_overlap and min(right - row_left, left - row_right) < max_x_dist:
- max_overlap = overlap
- max_overlap_idx = i
-
- # exclusive process to handle cases where there are multiple satisfying overlapping rows. For example some rows are not initially overlapping but as the appended words constantly get skewer, there is a change that the end of 1 row would reạch the beginning other row
- # if (row_top <= bottom and row_bottom >= top) and not (bottom - top - max_overlap > max_row_size * y_overlap_threshold) and not (max_overlap < max_row_size * y_overlap_threshold):
- if (row_top <= bottom_shift and row_bottom >= top_shift) \
- and min(right - row_left, left - row_right) < max_x_dist \
- and not (bottom - top - overlap > max_row_size * y_overlap_threshold) \
- and not (overlap < max_row_size * y_overlap_threshold):
- # explain:
- # (row_top <= bottom_shift and row_bottom >= top_shift) -> overlap at least 1 pixel
- # not (bottom - top - overlap > max_row_size * y_overlap_threshold) -> curr_word is not too big too overlap (to exclude figures containing words)
- # not (overlap < max_row_size * y_overlap_threshold) -> overlap too little should not be merged
- # min(right - row_left, row_right - left) < max_x_dist -> either the curr_word is close enough to left or right of the curr_row
- overlapping_rows.append(i)
-
- if len(overlapping_rows) > 1 and merge_overlapping_word_groups(rows, row_words, overlapping_rows, max_row_size):
- max_overlap_idx = overlapping_rows[0]
- if bottom - top - max_overlap > max_row_size * y_overlap_threshold and max_overlap < max_row_size * y_overlap_threshold:
- max_overlap_idx = -1
- return max_overlap_idx
-
-
-def update_overlapping_word_group_bbox(rows: list[list[int]], overlap_row_idx: int, curr_word_bbox: list[int]) -> None:
- left, top, right, bottom = curr_word_bbox
- row_left, row_top, row_right, row_bottom = rows[overlap_row_idx]
- new_bottom = max(row_bottom, bottom)
- new_top = min(row_top, top)
- new_left = min(row_left, left)
- new_right = max(row_right, right)
- rows[overlap_row_idx] = [new_left, new_top, new_right, new_bottom]
-
-
-def update_word_group_running_y_shift(
- running_y_shift: list[float],
- overlap_row_idx: int, curr_row_bbox: list[int],
- curr_word_bbox: list[int],
- gradient: float, max_running_y_shift: float) -> None:
- _, top, _, bottom = curr_word_bbox
- _, row_top, _, row_bottom = curr_row_bbox
- new_shift = (top + bottom) / 2 - (row_top + row_bottom) / 2
- running_y_shift[overlap_row_idx] = min(
- gradient * running_y_shift[overlap_row_idx] + (1 - gradient) * new_shift, max_running_y_shift) # update and clamp
-
-
-def stitch_boxes_into_word_groups_tesseract(words: list[Word],
- max_running_y_shift: int, gradient: float, y_overlap_threshold: float,
- max_x_dist: int) -> Tuple[list[WordGroup], float]:
- sorted_words = sorted(words, key=lambda x: x.bbox[0])
- rows = []
- row_words = []
- max_row_size = sorted_words[0].height
- running_y_shift = []
- for word in sorted_words:
- bbox: list[int] = word.bbox
- max_row_size = max(max_row_size, bbox[3] - bbox[1])
- if bbox[-1] < 200 and word.text == "Nguyễn":
- print("DEBUGING")
- overlap_row_idx = most_overlapping_word_groups(
- rows, row_words, bbox, running_y_shift, max_row_size, y_overlap_threshold, max_x_dist)
- if overlap_row_idx == -1: # No overlapping row found
- rows.append(bbox) # new row
- row_words.append([word]) # new row_word
- running_y_shift.append(0)
- else: # Overlapping row found
- # row_bottom, row_top = rows[overlap_row_idx]
- update_overlapping_word_group_bbox(rows, overlap_row_idx, bbox)
- row_words[overlap_row_idx].append(word) # update row_words
- update_word_group_running_y_shift(
- running_y_shift, overlap_row_idx, rows[overlap_row_idx],
- bbox, gradient, max_running_y_shift)
-
- # Sort rows and row_texts based on the top y-coordinate
- sorted_rows_data = sorted(zip(rows, row_words), key=lambda x: x[0][1])
- _sorted_rows_idx, sorted_row_words = zip(*sorted_rows_data)
- lword_groups = []
- for word_group in sorted_row_words:
- bbox_word_group, text_word_group = group_bbox_and_text(word_group)
- lword_groups.append(
- WordGroup(
- list_words=word_group, text=text_word_group[0],
- conf_cls=text_word_group[1],
- boundingbox=bbox_word_group))
- # /_|<- the perpendicular line of the horizontal line and the skew line of the page
- page_skew_dist = sum(running_y_shift) / len(running_y_shift)
-
- return lword_groups, page_skew_dist
-
-
-def is_on_same_line_mmocr_tesseract(box_a: list[int], box_b: list[int], min_y_overlap_ratio: float) -> bool:
- a_y_min = box_a[1]
- b_y_min = box_b[1]
- a_y_max = box_a[3]
- b_y_max = box_b[3]
-
- # Make sure that box a is always the box above another
- if a_y_min > b_y_min:
- a_y_min, b_y_min = b_y_min, a_y_min
- a_y_max, b_y_max = b_y_max, a_y_max
-
- if b_y_min <= a_y_max:
- if min_y_overlap_ratio is not None:
- sorted_y = sorted([b_y_min, b_y_max, a_y_max])
- overlap = sorted_y[1] - sorted_y[0]
- min_a_overlap = (a_y_max - a_y_min) * min_y_overlap_ratio
- min_b_overlap = (b_y_max - b_y_min) * min_y_overlap_ratio
- return overlap >= min_a_overlap or \
- overlap >= min_b_overlap
- else:
- return True
- return False
-
-
-def stitch_word_groups_into_lines_mmocr_tesseract(
- lword_groups: list[WordGroup],
- min_y_overlap_ratio: float) -> list[Line]:
- merged_lines = []
-
- # sort groups based on the x_min coordinate of boxes
- # store indexes of boxes which are already parts of other lines
- sorted_word_groups = sorted(lword_groups, key=lambda x: x.bbox[0])
- skip_idxs = set()
-
- i = 0
- # locate lines of boxes starting from the leftmost one
- for i in range(len(sorted_word_groups)):
- if i in skip_idxs:
- continue
- # the rightmost box in the current line
- rightmost_box_idx = i
- line = [rightmost_box_idx]
- for j in range(i + 1, len(sorted_word_groups)):
- if j in skip_idxs:
- continue
- if is_on_same_line_mmocr_tesseract(sorted_word_groups[rightmost_box_idx].bbox,
- sorted_word_groups[j].bbox, min_y_overlap_ratio):
- line.append(j)
- skip_idxs.add(j)
- rightmost_box_idx = j
-
- lword_groups_in_line = [sorted_word_groups[k] for k in line]
- bbox_line, text_line = group_bbox_and_text(lword_groups_in_line)
- merged_lines.append(
- Line(
- list_word_groups=lword_groups_in_line, text=text_line[0],
- conf_cls=text_line[1],
- boundingbox=bbox_line))
- merged_lines = sorted(merged_lines, key=lambda x: x.bbox[1])
- return merged_lines
-
-
-def words_formation_mmocr_tesseract(words: List[Word], page_width: int, word_formation_mode: str, max_running_y_shift_degree: int, gradient: float,
- max_x_dist: int, y_overlap_threshold: float) -> Tuple[Union[List[WordGroup], list[Line]],
- Optional[float]]:
- if len(words) == 0:
- return [], 0
- max_running_y_shift = page_width * np.tan(max_running_y_shift_degree * DEGREE_TO_RADIAN_COEF)
- lword_groups, page_skew_dist = stitch_boxes_into_word_groups_tesseract(
- words, max_running_y_shift, gradient, y_overlap_threshold, max_x_dist)
- if word_formation_mode == "word_group":
- return lword_groups, page_skew_dist
- elif word_formation_mode == "line":
- llines = stitch_word_groups_into_lines_mmocr_tesseract(lword_groups, y_overlap_threshold)
- return llines, page_skew_dist
- else:
- raise NotImplementedError("Word formation mode not supported: {}".format(word_formation_mode))
-
-############################################################################################################################################################################################################################
-############################################################################################################################################################################################################################
-### END WORDS TO LINES ALGORITHMS FROM MMOCR AND TESSERACT ###############################################################################################################################################################################
-############################################################################################################################################################################################################################
-############################################################################################################################################################################################################################
-
-# MIN_IOU_HEIGHT = 0.7
-# MIN_WIDTH_LINE_RATIO = 0.05
-
-
-# def resize_to_original(
-# boundingbox, scale
-# ): # resize coordinates to match size of original image
-# left, top, right, bottom = boundingbox
-# left *= scale[1]
-# right *= scale[1]
-# top *= scale[0]
-# bottom *= scale[0]
-# return [left, top, right, bottom]
-
-
-# def check_iomin(word: Word, word_group: Word_group):
-# min_height = min(
-# word.boundingbox[3] - word.boundingbox[1],
-# word_group.boundingbox[3] - word_group.boundingbox[1],
-# )
-# intersect = min(word.boundingbox[3], word_group.boundingbox[3]) - max(
-# word.boundingbox[1], word_group.boundingbox[1]
-# )
-# if intersect / min_height > 0.7:
-# return True
-# return False
-
-
-# def prepare_line(words):
-# lines = []
-# visited = [False] * len(words)
-# for id_word, word in enumerate(words):
-# if word.invalid_size() == 0:
-# continue
-# new_line = True
-# for i in range(len(lines)):
-# if (
-# lines[i].in_same_line(word) and not visited[id_word]
-# ): # check if word is in the same line with lines[i]
-# lines[i].merge_word(word)
-# new_line = False
-# visited[id_word] = True
-
-# if new_line == True:
-# new_line = Line()
-# new_line.merge_word(word)
-# lines.append(new_line)
-
-# # print(len(lines))
-# # sort line from top to bottom according top coordinate
-# lines.sort(key=lambda x: x.boundingbox[1])
-# return lines
-
-
-# def __create_word_group(word, word_group_id):
-# new_word_group_ = Word_group()
-# new_word_group_.list_words = list()
-# new_word_group_.word_group_id = word_group_id
-# new_word_group_.add_word(word)
-
-# return new_word_group_
-
-
-# def __sort_line(line):
-# line.list_word_groups.sort(
-# key=lambda x: x.boundingbox[0]
-# ) # sort word in lines from left to right
-
-# return line
-
-
-# def __merge_text_for_line(line):
-# line.text = ""
-# for word in line.list_word_groups:
-# line.text += " " + word.text
-
-# return line
-
-
-# def __update_list_word_groups(line, word_group_id, word_id, line_width):
-
-# old_list_word_group = line.list_word_groups
-# list_word_groups = []
-
-# inital_word_group = __create_word_group(
-# old_list_word_group[0], word_group_id)
-# old_list_word_group[0].word_id = word_id
-# list_word_groups.append(inital_word_group)
-# word_group_id += 1
-# word_id += 1
-
-# for word in old_list_word_group[1:]:
-# check_word_group = True
-# word.word_id = word_id
-# word_id += 1
-
-# if (
-# (not list_word_groups[-1].text.endswith(":"))
-# and (
-# (word.boundingbox[0] - list_word_groups[-1].boundingbox[2])
-# / line_width
-# < MIN_WIDTH_LINE_RATIO
-# )
-# and check_iomin(word, list_word_groups[-1])
-# ):
-# list_word_groups[-1].add_word(word)
-# check_word_group = False
-
-# if check_word_group:
-# new_word_group = __create_word_group(word, word_group_id)
-# list_word_groups.append(new_word_group)
-# word_group_id += 1
-# line.list_word_groups = list_word_groups
-# return line, word_group_id, word_id
-
-
-# def construct_word_groups_in_each_line(lines):
-# line_id = 0
-# word_group_id = 0
-# word_id = 0
-# for i in range(len(lines)):
-# if len(lines[i].list_word_groups) == 0:
-# continue
-
-# # left, top ,right, bottom
-# line_width = lines[i].boundingbox[2] - \
-# lines[i].boundingbox[0] # right - left
-# line_width = 1 # TODO: to remove
-# lines[i] = __sort_line(lines[i])
-
-# # update text for lines after sorting
-# lines[i] = __merge_text_for_line(lines[i])
-
-# lines[i], word_group_id, word_id = __update_list_word_groups(
-# lines[i],
-# word_group_id,
-# word_id,
-# line_width)
-# lines[i].update_line_id(line_id)
-# line_id += 1
-# return lines
-
-
-# def words_to_lines(words, check_special_lines=True): # words is list of Word instance
-# # sort word by top
-# words.sort(key=lambda x: (x.boundingbox[1], x.boundingbox[0]))
-# # words.sort(key=lambda x: (sum(x.bbox)))
-# number_of_word = len(words)
-# # print(number_of_word)
-# # sort list words to list lines, which have not contained word_group yet
-# lines = prepare_line(words)
-
-# # construct word_groups in each line
-# lines = construct_word_groups_in_each_line(lines)
-# return lines, number_of_word
-
-
-# def near(word_group1: Word_group, word_group2: Word_group):
-# min_height = min(
-# word_group1.boundingbox[3] - word_group1.boundingbox[1],
-# word_group2.boundingbox[3] - word_group2.boundingbox[1],
-# )
-# overlap = min(word_group1.boundingbox[3], word_group2.boundingbox[3]) - max(
-# word_group1.boundingbox[1], word_group2.boundingbox[1]
-# )
-
-# if overlap > 0:
-# return True
-# if abs(overlap / min_height) < 1.5:
-# print("near enough", abs(overlap / min_height), overlap, min_height)
-# return True
-# return False
-
-
-# def calculate_iou_and_near(wg1: Word_group, wg2: Word_group):
-# min_height = min(
-# wg1.boundingbox[3] -
-# wg1.boundingbox[1], wg2.boundingbox[3] - wg2.boundingbox[1]
-# )
-# overlap = min(wg1.boundingbox[3], wg2.boundingbox[3]) - max(
-# wg1.boundingbox[1], wg2.boundingbox[1]
-# )
-# iou = overlap / min_height
-# distance = min(
-# abs(wg1.boundingbox[0] - wg2.boundingbox[2]),
-# abs(wg1.boundingbox[2] - wg2.boundingbox[0]),
-# )
-# if iou > 0.7 and distance < 0.5 * (wg1.boundingboxp[2] - wg1.boundingbox[0]):
-# return True
-# return False
-
-
-# def construct_word_groups_to_kie_label(list_word_groups: list):
-# kie_dict = dict()
-# for wg in list_word_groups:
-# if wg.kie_label == "other":
-# continue
-# if wg.kie_label not in kie_dict:
-# kie_dict[wg.kie_label] = [wg]
-# else:
-# kie_dict[wg.kie_label].append(wg)
-
-# new_dict = dict()
-# for key, value in kie_dict.items():
-# if len(value) == 1:
-# new_dict[key] = value
-# continue
-
-# value.sort(key=lambda x: x.boundingbox[1])
-# new_dict[key] = value
-# return new_dict
-
-
-# def invoice_construct_word_groups_to_kie_label(list_word_groups: list):
-# kie_dict = dict()
-
-# for wg in list_word_groups:
-# if wg.kie_label == "other":
-# continue
-# if wg.kie_label not in kie_dict:
-# kie_dict[wg.kie_label] = [wg]
-# else:
-# kie_dict[wg.kie_label].append(wg)
-
-# return kie_dict
-
-
-# def postprocess_total_value(kie_dict):
-# if "total_in_words_value" not in kie_dict:
-# return kie_dict
-
-# for k, value in kie_dict.items():
-# if k == "total_in_words_value":
-# continue
-# l = []
-# for v in value:
-# if v.boundingbox[3] <= kie_dict["total_in_words_value"][0].boundingbox[3]:
-# l.append(v)
-
-# if len(l) != 0:
-# kie_dict[k] = l
-
-# return kie_dict
-
-
-# def postprocess_tax_code_value(kie_dict):
-# if "buyer_tax_code_value" in kie_dict or "seller_tax_code_value" not in kie_dict:
-# return kie_dict
-
-# kie_dict["buyer_tax_code_value"] = []
-# for v in kie_dict["seller_tax_code_value"]:
-# if "buyer_name_key" in kie_dict and (
-# v.boundingbox[3] > kie_dict["buyer_name_key"][0].boundingbox[3]
-# or near(v, kie_dict["buyer_name_key"][0])
-# ):
-# kie_dict["buyer_tax_code_value"].append(v)
-# continue
-
-# if "buyer_name_value" in kie_dict and (
-# v.boundingbox[3] > kie_dict["buyer_name_value"][0].boundingbox[3]
-# or near(v, kie_dict["buyer_name_value"][0])
-# ):
-# kie_dict["buyer_tax_code_value"].append(v)
-# continue
-
-# if "buyer_address_value" in kie_dict and near(
-# kie_dict["buyer_address_value"][0], v
-# ):
-# kie_dict["buyer_tax_code_value"].append(v)
-# return kie_dict
-
-
-# def postprocess_tax_code_key(kie_dict):
-# if "buyer_tax_code_key" in kie_dict or "seller_tax_code_key" not in kie_dict:
-# return kie_dict
-# kie_dict["buyer_tax_code_key"] = []
-# for v in kie_dict["seller_tax_code_key"]:
-# if "buyer_name_key" in kie_dict and (
-# v.boundingbox[3] > kie_dict["buyer_name_key"][0].boundingbox[3]
-# or near(v, kie_dict["buyer_name_key"][0])
-# ):
-# kie_dict["buyer_tax_code_key"].append(v)
-# continue
-
-# if "buyer_name_value" in kie_dict and (
-# v.boundingbox[3] > kie_dict["buyer_name_value"][0].boundingbox[3]
-# or near(v, kie_dict["buyer_name_value"][0])
-# ):
-# kie_dict["buyer_tax_code_key"].append(v)
-# continue
-
-# if "buyer_address_value" in kie_dict and near(
-# kie_dict["buyer_address_value"][0], v
-# ):
-# kie_dict["buyer_tax_code_key"].append(v)
-
-# return kie_dict
-
-
-# def invoice_postprocess(kie_dict: dict):
-# # all keys or values which are below total_in_words_value will be thrown away
-# kie_dict = postprocess_total_value(kie_dict)
-# kie_dict = postprocess_tax_code_value(kie_dict)
-# kie_dict = postprocess_tax_code_key(kie_dict)
-# return kie_dict
-
-
-# def throw_overlapping_words(list_words):
-# new_list = [list_words[0]]
-# for word in list_words:
-# overlap = False
-# area = (word.boundingbox[2] - word.boundingbox[0]) * (
-# word.boundingbox[3] - word.boundingbox[1]
-# )
-# for word2 in new_list:
-# area2 = (word2.boundingbox[2] - word2.boundingbox[0]) * (
-# word2.boundingbox[3] - word2.boundingbox[1]
-# )
-# xmin_intersect = max(word.boundingbox[0], word2.boundingbox[0])
-# xmax_intersect = min(word.boundingbox[2], word2.boundingbox[2])
-# ymin_intersect = max(word.boundingbox[1], word2.boundingbox[1])
-# ymax_intersect = min(word.boundingbox[3], word2.boundingbox[3])
-# if xmax_intersect < xmin_intersect or ymax_intersect < ymin_intersect:
-# continue
-
-# area_intersect = (xmax_intersect - xmin_intersect) * (
-# ymax_intersect - ymin_intersect
-# )
-# if area_intersect / area > 0.7 or area_intersect / area2 > 0.7:
-# overlap = True
-# if overlap == False:
-# new_list.append(word)
-# return new_list
-
-
-# def check_iou(box1: Word, box2: Box, threshold=0.9):
-# area1 = (box1.boundingbox[2] - box1.boundingbox[0]) * (
-# box1.boundingbox[3] - box1.boundingbox[1]
-# )
-# area2 = (box2.xmax - box2.xmin) * (box2.ymax - box2.ymin)
-# xmin_intersect = max(box1.boundingbox[0], box2.xmin)
-# ymin_intersect = max(box1.boundingbox[1], box2.ymin)
-# xmax_intersect = min(box1.boundingbox[2], box2.xmax)
-# ymax_intersect = min(box1.boundingbox[3], box2.ymax)
-# if xmax_intersect < xmin_intersect or ymax_intersect < ymin_intersect:
-# area_intersect = 0
-# else:
-# area_intersect = (xmax_intersect - xmin_intersect) * (
-# ymax_intersect - ymin_intersect
-# )
-# union = area1 + area2 - area_intersect
-# iou = area_intersect / union
-# if iou > threshold:
-# return True
-# return False
diff --git a/docker-compose-dev.yml b/docker-compose-dev.yml
index 5638fee..5244ab2 100755
--- a/docker-compose-dev.yml
+++ b/docker-compose-dev.yml
@@ -18,10 +18,11 @@ services:
privileged: true
image: sidp/cope2n-ai-fi-sbt
environment:
+ - PYTHONPATH=${PYTHONPATH}:/workspace/cope2n-ai-fi # For import module
- CELERY_BROKER=amqp://${RABBITMQ_DEFAULT_USER}:${RABBITMQ_DEFAULT_PASS}@rabbitmq-sbt:5672
- CUDA_VISIBLE_DEVICES=0
- # volumes:
- # - ./cope2n-ai-fi:/workspace/cope2n-ai-fi # for dev container only
+ volumes:
+ - ./cope2n-ai-fi:/workspace/cope2n-ai-fi # for dev container only
working_dir: /workspace/cope2n-ai-fi
# deploy:
# resources:
@@ -74,7 +75,7 @@ services:
networks:
- ctel-sbt
volumes:
- - ${HOST_MEDIA_FOLDER}:${MEDIA_ROOT}
+ # - ${HOST_MEDIA_FOLDER}:${MEDIA_ROOT}
- BE_static:/app/static
- ./cope2n-api:/app
working_dir: /app
@@ -164,7 +165,7 @@ services:
rabbitmq-sbt:
condition: service_started
volumes:
- - ${HOST_MEDIA_FOLDER}:${MEDIA_ROOT}
+ # - ${HOST_MEDIA_FOLDER}:${MEDIA_ROOT}
- ./cope2n-api:/app
working_dir: /app