Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
refactor(ocr): remove unused code and simplify model architecture
myhlolib3d6785db491
diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorch_paddle.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorch_paddle.pyindex 77c396ac..25d4cd1d 100644--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorch_paddle.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorch_paddle.py@@ -6,10 +6,9 @@ import numpy as npfrom loguru import loggerfrom magic_pdf.libs.config_reader import get_device-from magic_pdf.model.sub_modules.ocr.paddleocr2pytorch.ocr_utils import check_img, preprocess_image, sorted_boxes, \- merge_det_boxes, update_det_boxes, get_rotate_crop_image-from magic_pdf.model.sub_modules.ocr.paddleocr2pytorch.tools.infer.predict_system import TextSystem-import tools.infer.pytorchocr_utility as utility+from .ocr_utils import check_img, preprocess_image, sorted_boxes, merge_det_boxes, update_det_boxes, get_rotate_crop_image+from .tools.infer.predict_system import TextSystem+from .tools.infer import pytorchocr_utility as utilityimport argparse@@ -20,14 +19,9 @@ class PytorchPaddleOCR(TextSystem):self.lang = kwargs.get('lang', 'ch')- # kwargs['cls_model_path'] = "/Users/myhloli/Downloads/ch_ptocr_mobile_v2.0_cls_infer.pth"-if self.lang == 'ch':kwargs['det_model_path'] = "/Users/myhloli/Downloads/ch_ptocr_v4_det_infer.pth"kwargs['rec_model_path'] = "/Users/myhloli/Downloads/ch_ptocr_v4_rec_infer.pth"- kwargs['det_yaml_path'] = "/Users/myhloli/Downloads/PaddleOCR2Pytorch-main/configs/det/ch_PP-OCRv4/ch_PP-OCRv4_det_student.yml"- kwargs['rec_yaml_path'] = "/Users/myhloli/Downloads/PaddleOCR2Pytorch-main/configs/rec/PP-OCRv4/ch_PP-OCRv4_rec.yml"- kwargs['rec_image_shape'] = '3,48,320'kwargs['device'] = get_device()diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/base_ocr_v20.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/base_ocr_v20.pyindex 3c7eb1aa..01779274 100755--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/base_ocr_v20.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/base_ocr_v20.py@@ -1,11 +1,6 @@-import os, sys-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))-from collections import OrderedDict-import numpy as np-import cv2+import osimport torch--from pytorchocr.modeling.architectures.base_model import BaseModel+from .modeling.architectures.base_model import BaseModelclass BaseOCRV20:def __init__(self, config, **kwargs):@@ -17,45 +12,6 @@ class BaseOCRV20:def build_net(self, **kwargs):self.net = BaseModel(self.config, **kwargs)-- def load_paddle_weights(self, weights_path):- raise NotImplementedError('implemented in converter.')- print('paddle weights loading...')- import paddle.fluid as fluid- with fluid.dygraph.guard():- para_state_dict, opti_state_dict = fluid.load_dygraph(weights_path)-- for k,v in self.net.state_dict().items():- name = k-- if name.endswith('num_batches_tracked'):- continue-- if name.endswith('running_mean'):- ppname = name.replace('running_mean', '_mean')- elif name.endswith('running_var'):- ppname = name.replace('running_var', '_variance')- elif name.endswith('bias') or name.endswith('weight'):- ppname = name- elif 'lstm' in name:- ppname = name-- else:- print('Redundance:')- print(name)- raise ValueError- try:- if ppname.endswith('fc.weight'):- self.net.state_dict()[k].copy_(torch.Tensor(para_state_dict[ppname].T))- else:- self.net.state_dict()[k].copy_(torch.Tensor(para_state_dict[ppname]))- except Exception as e:- print('pytorch: {}, {}'.format(k, v.size()))- print('paddle: {}, {}'.format(ppname, para_state_dict[ppname].shape))- raise e-- print('model is loaded: {}'.format(weights_path))-def read_pytorch_weights(self, weights_path):if not os.path.exists(weights_path):raise FileNotFoundError('{} is not existed.'.format(weights_path))@@ -74,38 +30,9 @@ class BaseOCRV20:print('weights is loaded.')def load_pytorch_weights(self, weights_path):- self.net.load_state_dict(torch.load(weights_path))+ self.net.load_state_dict(torch.load(weights_path, weights_only=True))print('model is loaded: {}'.format(weights_path))-- def save_pytorch_weights(self, weights_path):- try:- torch.save(self.net.state_dict(), weights_path, _use_new_zipfile_serialization=False)- except:- torch.save(self.net.state_dict(), weights_path) # _use_new_zipfile_serialization=False for torch>=1.6.0- print('model is saved: {}'.format(weights_path))--- def print_pytorch_state_dict(self):- print('pytorch:')- for k,v in self.net.state_dict().items():- print('{}----{}'.format(k,type(v)))-- def read_paddle_weights(self, weights_path):- import paddle.fluid as fluid- with fluid.dygraph.guard():- para_state_dict, opti_state_dict = fluid.load_dygraph(weights_path)- return para_state_dict, opti_state_dict-- def print_paddle_state_dict(self, weights_path):- import paddle.fluid as fluid- with fluid.dygraph.guard():- para_state_dict, opti_state_dict = fluid.load_dygraph(weights_path)- print('paddle"')- for k,v in para_state_dict.items():- print('{}----{}'.format(k,type(v)))--def inference(self, inputs):with torch.no_grad():infer = self.net(inputs)diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/data/__init__.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/data/__init__.pyindex 4bc5c347..6cfaf436 100755--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/data/__init__.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/data/__init__.py@@ -18,7 +18,6 @@ import copy# from paddle.io import Dataset, DataLoader, BatchSampler, DistributedBatchSampler# import paddle.distributed as dist-from pytorchocr.data.imaug import transform, create_operators-# from pytorchocr.data.simple_dataset import SimpleDataSet-# from pytorchocr.data.lmdb_dataset import LMDBDateSet+from .imaug import transform, create_operators+diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/data/imaug/__init__.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/data/imaug/__init__.pyindex dce5011e..13abd674 100755--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/data/imaug/__init__.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/data/imaug/__init__.py@@ -15,7 +15,7 @@ from .operators import *# from .east_process import *# from .sast_process import *-from .gen_table_mask import *+# from .gen_table_mask import *def transform(data, ops=None):""" transform """diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/data/imaug/gen_table_mask.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/data/imaug/gen_table_mask.pydeleted file mode 100755index 2b14e7a9..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/data/imaug/gen_table_mask.py+++ /dev/null@@ -1,245 +0,0 @@-"""-# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.-"""--from __future__ import absolute_import-from __future__ import division-from __future__ import print_function-from __future__ import unicode_literals--import sys-import six-import cv2-import numpy as np---class GenTableMask(object):- """ gen table mask """-- def __init__(self, shrink_h_max, shrink_w_max, mask_type=0, **kwargs):- self.shrink_h_max = 5- self.shrink_w_max = 5- self.mask_type = mask_type-- def projection(self, erosion, h, w, spilt_threshold=0):- # 水平投影- projection_map = np.ones_like(erosion)- project_val_array = [0 for _ in range(0, h)]-- for j in range(0, h):- for i in range(0, w):- if erosion[j, i] == 255:- project_val_array[j] += 1- # 根据数组,获取切割点- start_idx = 0 # 记录进入字符区的索引- end_idx = 0 # 记录进入空白区域的索引- in_text = False # 是否遍历到了字符区内- box_list = []- for i in range(len(project_val_array)):- if in_text == False and project_val_array[i] > spilt_threshold: # 进入字符区了- in_text = True- start_idx = i- elif project_val_array[i] <= spilt_threshold and in_text == True: # 进入空白区了- end_idx = i- in_text = False- if end_idx - start_idx <= 2:- continue- box_list.append((start_idx, end_idx + 1))-- if in_text:- box_list.append((start_idx, h - 1))- # 绘制投影直方图- for j in range(0, h):- for i in range(0, project_val_array[j]):- projection_map[j, i] = 0- return box_list, projection_map-- def projection_cx(self, box_img):- box_gray_img = cv2.cvtColor(box_img, cv2.COLOR_BGR2GRAY)- h, w = box_gray_img.shape- # 灰度图片进行二值化处理- ret, thresh1 = cv2.threshold(box_gray_img, 200, 255, cv2.THRESH_BINARY_INV)- # 纵向腐蚀- if h < w:- kernel = np.ones((2, 1), np.uint8)- erode = cv2.erode(thresh1, kernel, iterations=1)- else:- erode = thresh1- # 水平膨胀- kernel = np.ones((1, 5), np.uint8)- erosion = cv2.dilate(erode, kernel, iterations=1)- # 水平投影- projection_map = np.ones_like(erosion)- project_val_array = [0 for _ in range(0, h)]-- for j in range(0, h):- for i in range(0, w):- if erosion[j, i] == 255:- project_val_array[j] += 1- # 根据数组,获取切割点- start_idx = 0 # 记录进入字符区的索引- end_idx = 0 # 记录进入空白区域的索引- in_text = False # 是否遍历到了字符区内- box_list = []- spilt_threshold = 0- for i in range(len(project_val_array)):- if in_text == False and project_val_array[i] > spilt_threshold: # 进入字符区了- in_text = True- start_idx = i- elif project_val_array[i] <= spilt_threshold and in_text == True: # 进入空白区了- end_idx = i- in_text = False- if end_idx - start_idx <= 2:- continue- box_list.append((start_idx, end_idx + 1))-- if in_text:- box_list.append((start_idx, h - 1))- # 绘制投影直方图- for j in range(0, h):- for i in range(0, project_val_array[j]):- projection_map[j, i] = 0- split_bbox_list = []- if len(box_list) > 1:- for i, (h_start, h_end) in enumerate(box_list):- if i == 0:- h_start = 0- if i == len(box_list):- h_end = h- word_img = erosion[h_start:h_end + 1, :]- word_h, word_w = word_img.shape- w_split_list, w_projection_map = self.projection(word_img.T, word_w, word_h)- w_start, w_end = w_split_list[0][0], w_split_list[-1][1]- if h_start > 0:- h_start -= 1- h_end += 1- word_img = box_img[h_start:h_end + 1:, w_start:w_end + 1, :]- split_bbox_list.append([w_start, h_start, w_end, h_end])- else:- split_bbox_list.append([0, 0, w, h])- return split_bbox_list-- def shrink_bbox(self, bbox):- left, top, right, bottom = bbox- sh_h = min(max(int((bottom - top) * 0.1), 1), self.shrink_h_max)- sh_w = min(max(int((right - left) * 0.1), 1), self.shrink_w_max)- left_new = left + sh_w- right_new = right - sh_w- top_new = top + sh_h- bottom_new = bottom - sh_h- if left_new >= right_new:- left_new = left- right_new = right- if top_new >= bottom_new:- top_new = top- bottom_new = bottom- return [left_new, top_new, right_new, bottom_new]-- def __call__(self, data):- img = data['image']- cells = data['cells']- height, width = img.shape[0:2]- if self.mask_type == 1:- mask_img = np.zeros((height, width), dtype=np.float32)- else:- mask_img = np.zeros((height, width, 3), dtype=np.float32)- cell_num = len(cells)- for cno in range(cell_num):- if "bbox" in cells[cno]:- bbox = cells[cno]['bbox']- left, top, right, bottom = bbox- box_img = img[top:bottom, left:right, :].copy()- split_bbox_list = self.projection_cx(box_img)- for sno in range(len(split_bbox_list)):- split_bbox_list[sno][0] += left- split_bbox_list[sno][1] += top- split_bbox_list[sno][2] += left- split_bbox_list[sno][3] += top-- for sno in range(len(split_bbox_list)):- left, top, right, bottom = split_bbox_list[sno]- left, top, right, bottom = self.shrink_bbox([left, top, right, bottom])- if self.mask_type == 1:- mask_img[top:bottom, left:right] = 1.0- data['mask_img'] = mask_img- else:- mask_img[top:bottom, left:right, :] = (255, 255, 255)- data['image'] = mask_img- return data---class ResizeTableImage(object):- def __init__(self, max_len, **kwargs):- super(ResizeTableImage, self).__init__()- self.max_len = max_len-- def get_img_bbox(self, cells):- bbox_list = []- if len(cells) == 0:- return bbox_list- cell_num = len(cells)- for cno in range(cell_num):- if "bbox" in cells[cno]:- bbox = cells[cno]['bbox']- bbox_list.append(bbox)- return bbox_list-- def resize_img_table(self, img, bbox_list, max_len):- height, width = img.shape[0:2]- ratio = max_len / (max(height, width) * 1.0)- resize_h = int(height * ratio)- resize_w = int(width * ratio)- img_new = cv2.resize(img, (resize_w, resize_h))- bbox_list_new = []- for bno in range(len(bbox_list)):- left, top, right, bottom = bbox_list[bno].copy()- left = int(left * ratio)- top = int(top * ratio)- right = int(right * ratio)- bottom = int(bottom * ratio)- bbox_list_new.append([left, top, right, bottom])- return img_new, bbox_list_new-- def __call__(self, data):- img = data['image']- if 'cells' not in data:- cells = []- else:- cells = data['cells']- bbox_list = self.get_img_bbox(cells)- img_new, bbox_list_new = self.resize_img_table(img, bbox_list, self.max_len)- data['image'] = img_new- cell_num = len(cells)- bno = 0- for cno in range(cell_num):- if "bbox" in data['cells'][cno]:- data['cells'][cno]['bbox'] = bbox_list_new[bno]- bno += 1- data['max_len'] = self.max_len- return data---class PaddingTableImage(object):- def __init__(self, **kwargs):- super(PaddingTableImage, self).__init__()-- def __call__(self, data):- img = data['image']- max_len = data['max_len']- padding_img = np.zeros((max_len, max_len, 3), dtype=np.float32)- height, width = img.shape[0:2]- padding_img[0:height, 0:width, :] = img.copy()- data['image'] = padding_img- return data\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/__init__.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/__init__.pyold mode 100755new mode 100644diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/arch_config.yaml b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/arch_config.yamlnew file mode 100644index 00000000..bdb423ae--- /dev/null+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/arch_config.yaml@@ -0,0 +1,366 @@+ch_ptocr_mobile_v2.0_cls_infer:+ model_type: cls+ algorithm: CLS+ Transform:+ Backbone:+ name: MobileNetV3+ scale: 0.35+ model_name: small+ Neck:+ Head:+ name: ClsHead+ class_dim: 2++Multilingual_PP-OCRv3_det_infer:+ model_type: det+ algorithm: DB+ Transform:+ Backbone:+ name: MobileNetV3+ scale: 0.5+ model_name: large+ disable_se: True+ Neck:+ name: RSEFPN+ out_channels: 96+ shortcut: True+ Head:+ name: DBHead+ k: 50++en_PP-OCRv3_det_infer:+ model_type: det+ algorithm: DB+ Transform:+ Backbone:+ name: MobileNetV3+ scale: 0.5+ model_name: large+ disable_se: True+ Neck:+ name: RSEFPN+ out_channels: 96+ shortcut: True+ Head:+ name: DBHead+ k: 50++en_PP-OCRv4_rec_infer:+ model_type: rec+ algorithm: SVTR_LCNet+ Transform:+ Backbone:+ name: PPLCNetV3+ scale: 0.95+ Head:+ name: MultiHead+ out_channels_list:+ CTCLabelDecode: 97 #'blank' + ...(62) + ' '+ head_list:+ - CTCHead:+ Neck:+ name: svtr+ dims: 120+ depth: 2+ hidden_dims: 120+ kernel_size: [ 1, 3 ]+ use_guide: True+ Head:+ fc_decay: 0.00001+ - NRTRHead:+ nrtr_dim: 384+ max_text_length: 25++ch_PP-OCRv4_det_infer:+ model_type: det+ algorithm: DB+ Transform: null+ Backbone:+ name: PPLCNetV3+ scale: 0.75+ det: True+ Neck:+ name: RSEFPN+ out_channels: 96+ shortcut: True+ Head:+ name: DBHead+ k: 50++ch_PP-OCRv4_det_server_infer:+ model_type: det+ algorithm: DB+ Transform: null+ Backbone:+ name: PPHGNet_small+ det: True+ Neck:+ name: LKPAN+ out_channels: 256+ intracl: true+ Head:+ name: PFHeadLocal+ k: 50+ mode: "large"++ch_PP-OCRv4_rec_infer:+ model_type: rec+ algorithm: SVTR_LCNet+ Transform:+ Backbone:+ name: PPLCNetV3+ scale: 0.95+ Head:+ name: MultiHead+ out_channels_list:+ CTCLabelDecode: 6625 #'blank' + ...(6623) + ' '+ head_list:+ - CTCHead:+ Neck:+ name: svtr+ dims: 120+ depth: 2+ hidden_dims: 120+ kernel_size: [ 1, 3 ]+ use_guide: True+ Head:+ fc_decay: 0.00001+ - NRTRHead:+ nrtr_dim: 384+ max_text_length: 25++ch_PP-OCRv4_rec_server_infer:+ model_type: rec+ algorithm: SVTR_HGNet+ Transform:+ Backbone:+ name: PPHGNet_small+ Head:+ name: MultiHead+ out_channels_list:+ CTCLabelDecode: 6625 #'blank' + ...(6623) + ' '+ head_list:+ - CTCHead:+ Neck:+ name: svtr+ dims: 120+ depth: 2+ hidden_dims: 120+ kernel_size: [ 1, 3 ]+ use_guide: True+ Head:+ fc_decay: 0.00001+ - NRTRHead:+ nrtr_dim: 384+ max_text_length: 25++chinese_cht_PP-OCRv3_rec_infer:+ model_type: rec+ algorithm: SVTR+ Transform:+ Backbone:+ name: MobileNetV1Enhance+ scale: 0.5+ last_conv_stride: [1, 2]+ last_pool_type: avg+ Neck:+ name: SequenceEncoder+ encoder_type: svtr+ dims: 64+ depth: 2+ hidden_dims: 120+ use_guide: True+ Head:+ name: CTCHead+ out_channels: 8423+ fc_decay: 0.00001++latin_PP-OCRv3_rec_infer:+ model_type: rec+ algorithm: SVTR+ Transform:+ Backbone:+ name: MobileNetV1Enhance+ scale: 0.5+ last_conv_stride: [ 1, 2 ]+ last_pool_type: avg+ Neck:+ name: SequenceEncoder+ encoder_type: svtr+ dims: 64+ depth: 2+ hidden_dims: 120+ use_guide: True+ Head:+ name: CTCHead+ out_channels: 187+ fc_decay: 0.00001++cyrillic_PP-OCRv3_rec_infer:+ model_type: rec+ algorithm: SVTR+ Transform:+ Backbone:+ name: MobileNetV1Enhance+ scale: 0.5+ last_conv_stride: [ 1, 2 ]+ last_pool_type: avg+ Neck:+ name: SequenceEncoder+ encoder_type: svtr+ dims: 64+ depth: 2+ hidden_dims: 120+ use_guide: True+ Head:+ name: CTCHead+ out_channels: 165+ fc_decay: 0.00001++arabic_PP-OCRv4_rec_infer:+ model_type: rec+ algorithm: SVTR+ Transform:+ Backbone:+ name: MobileNetV1Enhance+ scale: 0.5+ last_conv_stride: [ 1, 2 ]+ last_pool_type: avg+ Neck:+ name: SequenceEncoder+ encoder_type: svtr+ dims: 64+ depth: 2+ hidden_dims: 120+ use_guide: True+ Head:+ name: CTCHead+ out_channels: 164+ fc_decay: 0.00001++korean_PP-OCRv4_rec_infer:+ model_type: rec+ algorithm: SVTR+ Transform:+ Backbone:+ name: MobileNetV1Enhance+ scale: 0.5+ last_conv_stride: [ 1, 2 ]+ last_pool_type: avg+ Neck:+ name: SequenceEncoder+ encoder_type: svtr+ dims: 64+ depth: 2+ hidden_dims: 120+ use_guide: True+ Head:+ name: CTCHead+ out_channels: 3690+ fc_decay: 0.00001++japan_PP-OCRv4_rec_infer:+ model_type: rec+ algorithm: SVTR+ Transform:+ Backbone:+ name: MobileNetV1Enhance+ scale: 0.5+ last_conv_stride: [ 1, 2 ]+ last_pool_type: avg+ Neck:+ name: SequenceEncoder+ encoder_type: svtr+ dims: 64+ depth: 2+ hidden_dims: 120+ use_guide: True+ Head:+ name: CTCHead+ out_channels: 4401+ fc_decay: 0.00001++ta_PP-OCRv4_rec_infer:+ model_type: rec+ algorithm: SVTR+ Transform:+ Backbone:+ name: MobileNetV1Enhance+ scale: 0.5+ last_conv_stride: [ 1, 2 ]+ last_pool_type: avg+ Neck:+ name: SequenceEncoder+ encoder_type: svtr+ dims: 64+ depth: 2+ hidden_dims: 120+ use_guide: True+ Head:+ name: CTCHead+ out_channels: 130+ fc_decay: 0.00001++te_PP-OCRv4_rec_infer:+ model_type: rec+ algorithm: SVTR+ Transform:+ Backbone:+ name: MobileNetV1Enhance+ scale: 0.5+ last_conv_stride: [ 1, 2 ]+ last_pool_type: avg+ Neck:+ name: SequenceEncoder+ encoder_type: svtr+ dims: 64+ depth: 2+ hidden_dims: 120+ use_guide: True+ Head:+ name: CTCHead+ out_channels: 153+ fc_decay: 0.00001++ka_PP-OCRv4_rec_infer:+ model_type: rec+ algorithm: SVTR+ Transform:+ Backbone:+ name: MobileNetV1Enhance+ scale: 0.5+ last_conv_stride: [ 1, 2 ]+ last_pool_type: avg+ Neck:+ name: SequenceEncoder+ encoder_type: svtr+ dims: 64+ depth: 2+ hidden_dims: 120+ use_guide: True+ Head:+ name: CTCHead+ out_channels: 155+ fc_decay: 0.00001++devanagari_PP-OCRv4_rec_infer:+ model_type: rec+ algorithm: SVTR+ Transform:+ Backbone:+ name: MobileNetV1Enhance+ scale: 0.5+ last_conv_stride: [ 1, 2 ]+ last_pool_type: avg+ Neck:+ name: SequenceEncoder+ encoder_type: svtr+ dims: 64+ depth: 2+ hidden_dims: 120+ use_guide: True+ Head:+ name: CTCHead+ out_channels: 169+ fc_decay: 0.00001+diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/architectures/__init__.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/architectures/__init__.pyold mode 100755new mode 100644index a93052f4..7ad5eb47--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/architectures/__init__.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/architectures/__init__.py@@ -14,7 +14,7 @@import copy-__all__ = ['build_model']+__all__ = ["build_model"]def build_model(config, **kwargs):@@ -22,4 +22,4 @@ def build_model(config, **kwargs):config = copy.deepcopy(config)module_class = BaseModel(config, **kwargs)- return module_class\ No newline at end of file+ return module_classdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/architectures/base_model.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/architectures/base_model.pyold mode 100755new mode 100644index b0ba725f..e7f7ce49--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/architectures/base_model.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/architectures/base_model.py@@ -1,13 +1,9 @@-import os, sys-# import torch-import torch.nn as nn-# import torch.nn.functional as F-# from pytorchocr.modeling.common import Activation+from torch import nn++from ..backbones import build_backbone+from ..heads import build_head+from ..necks import build_neck-from pytorchocr.modeling.transforms import build_transform-from pytorchocr.modeling.backbones import build_backbone-from pytorchocr.modeling.necks import build_neck-from pytorchocr.modeling.heads import build_headclass BaseModel(nn.Module):def __init__(self, config, **kwargs):@@ -18,27 +14,14 @@ class BaseModel(nn.Module):"""super(BaseModel, self).__init__()- in_channels = config.get('in_channels', 3)- model_type = config['model_type']- # build transfrom,- # for rec, transfrom can be TPS,None- # for det and cls, transfrom shoule to be None,- # if you make model differently, you can use transfrom in det and cls- if 'Transform' not in config or config['Transform'] is None:- self.use_transform = False- else:- self.use_transform = True- config['Transform']['in_channels'] = in_channels- self.transform = build_transform(config['Transform'])- in_channels = self.transform.out_channels- # raise NotImplementedError-+ in_channels = config.get("in_channels", 3)+ model_type = config["model_type"]# build backbone, backbone is need for del, rec and cls- if 'Backbone' not in config or config['Backbone'] is None:+ if "Backbone" not in config or config["Backbone"] is None:self.use_backbone = Falseelse:self.use_backbone = True- config["Backbone"]['in_channels'] = in_channels+ config["Backbone"]["in_channels"] = in_channelsself.backbone = build_backbone(config["Backbone"], model_type)in_channels = self.backbone.out_channels@@ -46,20 +29,20 @@ class BaseModel(nn.Module):# for rec, neck can be cnn,rnn or reshape(None)# for det, neck can be FPN, BIFPN and so on.# for cls, neck should be none- if 'Neck' not in config or config['Neck'] is None:+ if "Neck" not in config or config["Neck"] is None:self.use_neck = Falseelse:self.use_neck = True- config['Neck']['in_channels'] = in_channels- self.neck = build_neck(config['Neck'])+ config["Neck"]["in_channels"] = in_channels+ self.neck = build_neck(config["Neck"])in_channels = self.neck.out_channels# # build head, head is need for det, rec and cls- if 'Head' not in config or config['Head'] is None:+ if "Head" not in config or config["Head"] is None:self.use_head = Falseelse:self.use_head = True- config["Head"]['in_channels'] = in_channels+ config["Head"]["in_channels"] = in_channelsself.head = build_head(config["Head"], **kwargs)self.return_all_feats = config.get("return_all_feats", False)@@ -70,7 +53,7 @@ class BaseModel(nn.Module):# weight initializationfor m in self.modules():if isinstance(m, nn.Conv2d):- nn.init.kaiming_normal_(m.weight, mode='fan_out')+ nn.init.kaiming_normal_(m.weight, mode="fan_out")if m.bias is not None:nn.init.zeros_(m.bias)elif isinstance(m, nn.BatchNorm2d):@@ -81,15 +64,12 @@ class BaseModel(nn.Module):if m.bias is not None:nn.init.zeros_(m.bias)elif isinstance(m, nn.ConvTranspose2d):- nn.init.kaiming_normal_(m.weight, mode='fan_out')+ nn.init.kaiming_normal_(m.weight, mode="fan_out")if m.bias is not None:nn.init.zeros_(m.bias)-def forward(self, x):y = dict()- if self.use_transform:- x = self.transform(x)if self.use_backbone:x = self.backbone(x)if isinstance(x, dict):@@ -107,9 +87,9 @@ class BaseModel(nn.Module):if self.use_head:x = self.head(x)# for multi head, save ctc neck out for udml- if isinstance(x, dict) and 'ctc_nect' in x.keys():- y['neck_out'] = x['ctc_neck']- y['head_out'] = x+ if isinstance(x, dict) and "ctc_nect" in x.keys():+ y["neck_out"] = x["ctc_neck"]+ y["head_out"] = xelif isinstance(x, dict):y.update(x)else:@@ -122,4 +102,4 @@ class BaseModel(nn.Module):else:return {final_name: x}else:- return x\ No newline at end of file+ return xdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/__init__.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/__init__.pyold mode 100755new mode 100644index 7abdb0e3..79f2e51d--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/__init__.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/__init__.py@@ -12,45 +12,51 @@# See the License for the specific language governing permissions and# limitations under the License.-__all__ = ['build_backbone']+__all__ = ["build_backbone"]def build_backbone(config, model_type):- if model_type == 'det':+ if model_type == "det":from .det_mobilenet_v3 import MobileNetV3- from .det_resnet import ResNet- from .det_resnet_vd import ResNet_vd- from .det_resnet_vd_sast import ResNet_SAST+ from .rec_hgnet import PPHGNet_smallfrom .rec_lcnetv3 import PPLCNetV3++ support_dict = [+ "MobileNetV3",+ "ResNet",+ "ResNet_vd",+ "ResNet_SAST",+ "PPLCNetV3",+ "PPHGNet_small",+ ]+ elif model_type == "rec" or model_type == "cls":from .rec_hgnet import PPHGNet_small- support_dict = ['MobileNetV3', 'ResNet', 'ResNet_vd', 'ResNet_SAST', 'PPLCNetV3', 'PPHGNet_small']- elif model_type == 'rec' or model_type == 'cls':+ from .rec_lcnetv3 import PPLCNetV3from .rec_mobilenet_v3 import MobileNetV3- from .rec_resnet_vd import ResNet- from .rec_resnet_fpn import ResNetFPN- from .rec_mv1_enhance import MobileNetV1Enhance- from .rec_nrtr_mtb import MTB- from .rec_resnet_31 import ResNet31from .rec_svtrnet import SVTRNet- from .rec_vitstr import ViTSTR- from .rec_densenet import DenseNet- from .rec_lcnetv3 import PPLCNetV3- from .rec_hgnet import PPHGNet_small- support_dict = ['MobileNetV1Enhance', 'MobileNetV3', 'ResNet', 'ResNetFPN', 'MTB',- 'ResNet31', 'SVTRNet', 'ViTSTR', 'DenseNet', 'PPLCNetV3', 'PPHGNet_small']- elif model_type == 'e2e':- from .e2e_resnet_vd_pg import ResNet- support_dict = ['ResNet']- elif model_type == "table":- from .table_resnet_vd import ResNet- from .table_mobilenet_v3 import MobileNetV3- support_dict = ["ResNet", "MobileNetV3"]+ from .rec_mv1_enhance import MobileNetV1Enhance++ support_dict = [+ "MobileNetV1Enhance",+ "MobileNetV3",+ "ResNet",+ "ResNetFPN",+ "MTB",+ "ResNet31",+ "SVTRNet",+ "ViTSTR",+ "DenseNet",+ "PPLCNetV3",+ "PPHGNet_small",+ ]else:raise NotImplementedError- module_name = config.pop('name')+ module_name = config.pop("name")assert module_name in support_dict, Exception(- 'when model typs is {}, backbone only support {}'.format(model_type,- support_dict))+ "when model typs is {}, backbone only support {}".format(+ model_type, support_dict+ )+ )module_class = eval(module_name)(**config)- return module_class\ No newline at end of file+ return module_classdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/det_mobilenet_v3.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/det_mobilenet_v3.pyold mode 100755new mode 100644index 795f5d11..03511599--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/det_mobilenet_v3.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/det_mobilenet_v3.py@@ -1,8 +1,7 @@-import os, sys-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation+from torch import nn++from ..common import Activation+def make_divisible(v, divisor=8, min_value=None):if min_value is None:@@ -14,16 +13,18 @@ def make_divisible(v, divisor=8, min_value=None):class ConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride,- padding,- groups=1,- if_act=True,- act=None,- name=None):+ def __init__(+ self,+ in_channels,+ out_channels,+ kernel_size,+ stride,+ padding,+ groups=1,+ if_act=True,+ act=None,+ name=None,+ ):super(ConvBNLayer, self).__init__()self.if_act = if_actself.conv = nn.Conv2d(@@ -33,11 +34,12 @@ class ConvBNLayer(nn.Module):stride=stride,padding=padding,groups=groups,- bias=False)+ bias=False,+ )self.bn = nn.BatchNorm2d(out_channels,- )+ )if self.if_act:self.act = Activation(act_type=act, inplace=True)@@ -59,16 +61,18 @@ class SEModule(nn.Module):kernel_size=1,stride=1,padding=0,- bias=True)- self.relu1 = Activation(act_type='relu', inplace=True)+ bias=True,+ )+ self.relu1 = Activation(act_type="relu", inplace=True)self.conv2 = nn.Conv2d(in_channels=in_channels // reduction,out_channels=in_channels,kernel_size=1,stride=1,padding=0,- bias=True)- self.hard_sigmoid = Activation(act_type='hard_sigmoid', inplace=True)+ bias=True,+ )+ self.hard_sigmoid = Activation(act_type="hard_sigmoid", inplace=True)def forward(self, inputs):outputs = self.avg_pool(inputs)@@ -81,15 +85,17 @@ class SEModule(nn.Module):class ResidualUnit(nn.Module):- def __init__(self,- in_channels,- mid_channels,- out_channels,- kernel_size,- stride,- use_se,- act=None,- name=''):+ def __init__(+ self,+ in_channels,+ mid_channels,+ out_channels,+ kernel_size,+ stride,+ use_se,+ act=None,+ name="",+ ):super(ResidualUnit, self).__init__()self.if_shortcut = stride == 1 and in_channels == out_channelsself.if_se = use_se@@ -102,7 +108,8 @@ class ResidualUnit(nn.Module):padding=0,if_act=True,act=act,- name=name + "_expand")+ name=name + "_expand",+ )self.bottleneck_conv = ConvBNLayer(in_channels=mid_channels,out_channels=mid_channels,@@ -112,7 +119,8 @@ class ResidualUnit(nn.Module):groups=mid_channels,if_act=True,act=act,- name=name + "_depthwise")+ name=name + "_depthwise",+ )if self.if_se:self.mid_se = SEModule(mid_channels, name=name + "_se")self.linear_conv = ConvBNLayer(@@ -123,7 +131,8 @@ class ResidualUnit(nn.Module):padding=0,if_act=False,act=None,- name=name + "_linear")+ name=name + "_linear",+ )def forward(self, inputs):x = self.expand_conv(inputs)@@ -137,12 +146,9 @@ class ResidualUnit(nn.Module):class MobileNetV3(nn.Module):- def __init__(self,- in_channels=3,- model_name='large',- scale=0.5,- disable_se=False,- **kwargs):+ def __init__(+ self, in_channels=3, model_name="large", scale=0.5, disable_se=False, **kwargs+ ):"""the MobilenetV3 backbone network for detection module.Args:@@ -155,46 +161,48 @@ class MobileNetV3(nn.Module):if model_name == "large":cfg = [# k, exp, c, se, nl, s,- [3, 16, 16, False, 'relu', 1],- [3, 64, 24, False, 'relu', 2],- [3, 72, 24, False, 'relu', 1],- [5, 72, 40, True, 'relu', 2],- [5, 120, 40, True, 'relu', 1],- [5, 120, 40, True, 'relu', 1],- [3, 240, 80, False, 'hard_swish', 2],- [3, 200, 80, False, 'hard_swish', 1],- [3, 184, 80, False, 'hard_swish', 1],- [3, 184, 80, False, 'hard_swish', 1],- [3, 480, 112, True, 'hard_swish', 1],- [3, 672, 112, True, 'hard_swish', 1],- [5, 672, 160, True, 'hard_swish', 2],- [5, 960, 160, True, 'hard_swish', 1],- [5, 960, 160, True, 'hard_swish', 1],+ [3, 16, 16, False, "relu", 1],+ [3, 64, 24, False, "relu", 2],+ [3, 72, 24, False, "relu", 1],+ [5, 72, 40, True, "relu", 2],+ [5, 120, 40, True, "relu", 1],+ [5, 120, 40, True, "relu", 1],+ [3, 240, 80, False, "hard_swish", 2],+ [3, 200, 80, False, "hard_swish", 1],+ [3, 184, 80, False, "hard_swish", 1],+ [3, 184, 80, False, "hard_swish", 1],+ [3, 480, 112, True, "hard_swish", 1],+ [3, 672, 112, True, "hard_swish", 1],+ [5, 672, 160, True, "hard_swish", 2],+ [5, 960, 160, True, "hard_swish", 1],+ [5, 960, 160, True, "hard_swish", 1],]cls_ch_squeeze = 960elif model_name == "small":cfg = [# k, exp, c, se, nl, s,- [3, 16, 16, True, 'relu', 2],- [3, 72, 24, False, 'relu', 2],- [3, 88, 24, False, 'relu', 1],- [5, 96, 40, True, 'hard_swish', 2],- [5, 240, 40, True, 'hard_swish', 1],- [5, 240, 40, True, 'hard_swish', 1],- [5, 120, 48, True, 'hard_swish', 1],- [5, 144, 48, True, 'hard_swish', 1],- [5, 288, 96, True, 'hard_swish', 2],- [5, 576, 96, True, 'hard_swish', 1],- [5, 576, 96, True, 'hard_swish', 1],+ [3, 16, 16, True, "relu", 2],+ [3, 72, 24, False, "relu", 2],+ [3, 88, 24, False, "relu", 1],+ [5, 96, 40, True, "hard_swish", 2],+ [5, 240, 40, True, "hard_swish", 1],+ [5, 240, 40, True, "hard_swish", 1],+ [5, 120, 48, True, "hard_swish", 1],+ [5, 144, 48, True, "hard_swish", 1],+ [5, 288, 96, True, "hard_swish", 2],+ [5, 576, 96, True, "hard_swish", 1],+ [5, 576, 96, True, "hard_swish", 1],]cls_ch_squeeze = 576else:- raise NotImplementedError("mode[" + model_name +- "_model] is not implemented!")+ raise NotImplementedError(+ "mode[" + model_name + "_model] is not implemented!"+ )supported_scale = [0.35, 0.5, 0.75, 1.0, 1.25]- assert scale in supported_scale, \- "supported scale are {} but input scale is {}".format(supported_scale, scale)+ assert (+ scale in supported_scale+ ), "supported scale are {} but input scale is {}".format(supported_scale, scale)inplanes = 16# conv1self.conv = ConvBNLayer(@@ -205,15 +213,16 @@ class MobileNetV3(nn.Module):padding=1,groups=1,if_act=True,- act='hard_swish',- name='conv1')+ act="hard_swish",+ name="conv1",+ )self.stages = nn.ModuleList()self.out_channels = []block_list = []i = 0inplanes = make_divisible(inplanes * scale)- for (k, exp, c, se, nl, s) in cfg:+ for k, exp, c, se, nl, s in cfg:se = se and not self.disable_seif s == 2 and i > 2:self.out_channels.append(inplanes)@@ -228,7 +237,9 @@ class MobileNetV3(nn.Module):stride=s,use_se=se,act=nl,- name="conv" + str(i + 2)))+ name="conv" + str(i + 2),+ )+ )inplanes = make_divisible(scale * c)i += 1block_list.append(@@ -240,8 +251,10 @@ class MobileNetV3(nn.Module):padding=0,groups=1,if_act=True,- act='hard_swish',- name='conv_last'))+ act="hard_swish",+ name="conv_last",+ )+ )self.stages.append(nn.Sequential(*block_list))self.out_channels.append(make_divisible(scale * cls_ch_squeeze))# for i, stage in enumerate(self.stages):diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/det_resnet.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/det_resnet.pydeleted file mode 100755index f925d74f..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/det_resnet.py+++ /dev/null@@ -1,210 +0,0 @@--from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import numpy as np-import torch-import torch.nn as nn-import torch.nn.functional as F-from .det_resnet_vd import DeformableConvV2, ConvBNLayer---class BottleneckBlock(nn.Module):- def __init__(self,- num_channels,- num_filters,- stride,- shortcut=True,- is_dcn=False):- super(BottleneckBlock, self).__init__()-- self.conv0 = ConvBNLayer(- in_channels=num_channels,- out_channels=num_filters,- kernel_size=1,- act="relu", )- self.conv1 = ConvBNLayer(- in_channels=num_filters,- out_channels=num_filters,- kernel_size=3,- stride=stride,- act="relu",- is_dcn=is_dcn,- # dcn_groups=1,- )- self.conv2 = ConvBNLayer(- in_channels=num_filters,- out_channels=num_filters * 4,- kernel_size=1,- act=None, )-- if not shortcut:- self.short = ConvBNLayer(- in_channels=num_channels,- out_channels=num_filters * 4,- kernel_size=1,- stride=stride, )-- self.shortcut = shortcut-- self._num_channels_out = num_filters * 4-- def forward(self, inputs):- y = self.conv0(inputs)- conv1 = self.conv1(y)- conv2 = self.conv2(conv1)-- if self.shortcut:- short = inputs- else:- short = self.short(inputs)-- y = torch.add(short, conv2)- y = F.relu(y)- return y---class BasicBlock(nn.Module):- def __init__(self,- num_channels,- num_filters,- stride,- shortcut=True,- name=None):- super(BasicBlock, self).__init__()- self.stride = stride- self.conv0 = ConvBNLayer(- in_channels=num_channels,- out_channels=num_filters,- kernel_size=3,- stride=stride,- act="relu")- self.conv1 = ConvBNLayer(- in_channels=num_filters,- out_channels=num_filters,- kernel_size=3,- act=None)-- if not shortcut:- self.short = ConvBNLayer(- in_channels=num_channels,- out_channels=num_filters,- kernel_size=1,- stride=stride)-- self.shortcut = shortcut-- def forward(self, inputs):- y = self.conv0(inputs)- conv1 = self.conv1(y)-- if self.shortcut:- short = inputs- else:- short = self.short(inputs)- y = torch.add(short, conv1)- y = F.relu(y)- return y---class ResNet(nn.Module):- def __init__(self,- in_channels=3,- layers=50,- out_indices=None,- dcn_stage=None):- super(ResNet, self).__init__()-- self.layers = layers- self.input_image_channel = in_channels-- supported_layers = [18, 34, 50, 101, 152]- assert layers in supported_layers, \- "supported layers are {} but input layer is {}".format(- supported_layers, layers)-- if layers == 18:- depth = [2, 2, 2, 2]- elif layers == 34 or layers == 50:- depth = [3, 4, 6, 3]- elif layers == 101:- depth = [3, 4, 23, 3]- elif layers == 152:- depth = [3, 8, 36, 3]- num_channels = [64, 256, 512,- 1024] if layers >= 50 else [64, 64, 128, 256]- num_filters = [64, 128, 256, 512]-- self.dcn_stage = dcn_stage if dcn_stage is not None else [- False, False, False, False- ]- self.out_indices = out_indices if out_indices is not None else [- 0, 1, 2, 3- ]-- self.conv = ConvBNLayer(- in_channels=self.input_image_channel,- out_channels=64,- kernel_size=7,- stride=2,- act="relu", )- self.pool2d_max = nn.MaxPool2d(- kernel_size=3,- stride=2,- padding=1, )-- self.stages = nn.ModuleList()- self.out_channels = []- if layers >= 50:- for block in range(len(depth)):- shortcut = False- block_list = nn.Sequential()- is_dcn = self.dcn_stage[block]- for i in range(depth[block]):- if layers in [101, 152] and block == 2:- if i == 0:- conv_name = "res" + str(block + 2) + "a"- else:- conv_name = "res" + str(block + 2) + "b" + str(i)- else:- conv_name = "res" + str(block + 2) + chr(97 + i)- bottleneck_block = BottleneckBlock(- num_channels=num_channels[block]- if i == 0 else num_filters[block] * 4,- num_filters=num_filters[block],- stride=2 if i == 0 and block != 0 else 1,- shortcut=shortcut,- is_dcn=is_dcn)- block_list.add_module(conv_name, bottleneck_block)- shortcut = True- if block in self.out_indices:- self.out_channels.append(num_filters[block] * 4)- self.stages.append(block_list)- else:- for block in range(len(depth)):- shortcut = False- block_list = nn.Sequential()- for i in range(depth[block]):- conv_name = "res" + str(block + 2) + chr(97 + i)- basic_block = BasicBlock(- num_channels=num_channels[block]- if i == 0 else num_filters[block],- num_filters=num_filters[block],- stride=2 if i == 0 and block != 0 else 1,- shortcut=shortcut)- block_list.add_module(conv_name, basic_block)- shortcut = True- if block in self.out_indices:- self.out_channels.append(num_filters[block])- self.stages.append(block_list)-- def forward(self, inputs):- y = self.conv(inputs)- y = self.pool2d_max(y)- out = []- for i, block in enumerate(self.stages):- y = block(y)- if i in self.out_indices:- out.append(y)- return outdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/det_resnet_vd.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/det_resnet_vd.pydeleted file mode 100755index 2330bc79..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/det_resnet_vd.py+++ /dev/null@@ -1,360 +0,0 @@---import os, sys-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation-import torchvision--class DeformableConvV2(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride=1,- padding=0,- dilation=1,- groups=1,- weight_attr=None,- bias_attr=None,- lr_scale=1,- regularizer=None,- skip_quant=False,- dcn_bias_regularizer=None,- dcn_bias_lr_scale=2.):- super(DeformableConvV2, self).__init__()- self.offset_channel = 2 * kernel_size**2 * groups- self.mask_channel = kernel_size**2 * groups-- if bias_attr:- # in FCOS-DCN head, specifically need learning_rate and regularizer- dcn_bias_attr = True- else:- # in ResNet backbone, do not need bias- dcn_bias_attr = False- self.conv_dcn = torchvision.ops.DeformConv2d(- in_channels,- out_channels,- kernel_size,- stride=stride,- padding=(kernel_size - 1) // 2 * dilation,- dilation=dilation,- groups=groups//2 if groups > 1 else 1,- bias=dcn_bias_attr)-- self.conv_offset = nn.Conv2d(- in_channels,- groups * 3 * kernel_size**2,- kernel_size,- stride=stride,- padding=(kernel_size - 1) // 2,- bias=True)- if skip_quant:- self.conv_offset.skip_quant = True-- def forward(self, x):- offset_mask = self.conv_offset(x)- offset, mask = torch.split(- offset_mask,- split_size_or_sections=[self.offset_channel, self.mask_channel],- dim=1)- mask = torch.sigmoid(mask)- y = self.conv_dcn(x, offset, mask=mask)- return y--class ConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride=1,- groups=1,- dcn_groups=1,- is_vd_mode=False,- act=None,- name=None,- is_dcn=False,- ):- super(ConvBNLayer, self).__init__()-- self.is_vd_mode = is_vd_mode- self.act = act- self._pool2d_avg = nn.AvgPool2d(- kernel_size=2, stride=2, padding=0, ceil_mode=True)- if not is_dcn:- self._conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=(kernel_size - 1) // 2,- groups=groups,- bias=False)- else:- self._conv = DeformableConvV2(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=(kernel_size - 1) // 2,- groups=dcn_groups,- bias_attr=False)-- self._batch_norm = nn.BatchNorm2d(- out_channels,- track_running_stats=True,- )-- if act is not None:- self._act = Activation(act_type=act, inplace=True)--- def forward(self, inputs):- if self.is_vd_mode:- inputs = self._pool2d_avg(inputs)- y = self._conv(inputs)- y = self._batch_norm(y)- if self.act is not None:- y = self._act(y)- return y---class BottleneckBlock(nn.Module):- def __init__(self,- in_channels,- out_channels,- stride,- shortcut=True,- if_first=False,- name=None,- is_dcn=False,- ):- super(BottleneckBlock, self).__init__()-- self.conv0 = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=1,- act='relu',- name=name + "_branch2a")- self.conv1 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels,- kernel_size=3,- stride=stride,- act='relu',- name=name + "_branch2b",- is_dcn=is_dcn,- dcn_groups=2,- )- self.conv2 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels * 4,- kernel_size=1,- act=None,- name=name + "_branch2c")-- if not shortcut:- self.short = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels * 4,- kernel_size=1,- stride=1,- is_vd_mode=False if if_first else True,- name=name + "_branch1")-- self.shortcut = shortcut-- def forward(self, inputs):- y = self.conv0(inputs)- conv1 = self.conv1(y)- conv2 = self.conv2(conv1)-- if self.shortcut:- short = inputs- else:- short = self.short(inputs)- y = torch.add(short, conv2)- y = F.relu(y)- return y---class BasicBlock(nn.Module):- def __init__(self,- in_channels,- out_channels,- stride,- shortcut=True,- if_first=False,- name=None):- super(BasicBlock, self).__init__()- self.stride = stride- self.conv0 = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=3,- stride=stride,- act='relu',- name=name + "_branch2a")- self.conv1 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels,- kernel_size=3,- act=None,- name=name + "_branch2b")-- if not shortcut:- self.short = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=1,- stride=1,- is_vd_mode=False if if_first else True,- name=name + "_branch1")-- self.shortcut = shortcut-- def forward(self, inputs):- y = self.conv0(inputs)- conv1 = self.conv1(y)-- if self.shortcut:- short = inputs- else:- short = self.short(inputs)- y = short + conv1- y = F.relu(y)- return y---class ResNet_vd(nn.Module):- def __init__(self,- in_channels=3,- layers=50,- dcn_stage=None,- out_indices=None,- **kwargs):- super(ResNet_vd, self).__init__()-- self.layers = layers- supported_layers = [18, 34, 50, 101, 152, 200]- assert layers in supported_layers, \- "supported layers are {} but input layer is {}".format(- supported_layers, layers)-- if layers == 18:- depth = [2, 2, 2, 2]- elif layers == 34 or layers == 50:- depth = [3, 4, 6, 3]- elif layers == 101:- depth = [3, 4, 23, 3]- elif layers == 152:- depth = [3, 8, 36, 3]- elif layers == 200:- depth = [3, 12, 48, 3]- num_channels = [64, 256, 512,- 1024] if layers >= 50 else [64, 64, 128, 256]- num_filters = [64, 128, 256, 512]-- self.dcn_stage = dcn_stage if dcn_stage is not None else [- False, False, False, False- ]- self.out_indices = out_indices if out_indices is not None else [- 0, 1, 2, 3- ]-- self.conv1_1 = ConvBNLayer(- in_channels=in_channels,- out_channels=32,- kernel_size=3,- stride=2,- act='relu',- name="conv1_1")- self.conv1_2 = ConvBNLayer(- in_channels=32,- out_channels=32,- kernel_size=3,- stride=1,- act='relu',- name="conv1_2")- self.conv1_3 = ConvBNLayer(- in_channels=32,- out_channels=64,- kernel_size=3,- stride=1,- act='relu',- name="conv1_3")- self.pool2d_max = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)-- self.stages = nn.ModuleList()- self.out_channels = []- if layers >= 50:- for block in range(len(depth)):- # block_list = []- block_list = nn.Sequential()- shortcut = False- is_dcn = self.dcn_stage[block]- for i in range(depth[block]):- if layers in [101, 152] and block == 2:- if i == 0:- conv_name = "res" + str(block + 2) + "a"- else:- conv_name = "res" + str(block + 2) + "b" + str(i)- else:- conv_name = "res" + str(block + 2) + chr(97 + i)- bottleneck_block = BottleneckBlock(- in_channels=num_channels[block]- if i == 0 else num_filters[block] * 4,- out_channels=num_filters[block],- stride=2 if i == 0 and block != 0 else 1,- shortcut=shortcut,- if_first=block == i == 0,- name=conv_name,- is_dcn=is_dcn,- )-- shortcut = True- block_list.add_module('bb_%d_%d' % (block, i), bottleneck_block)- if block in self.out_indices:- self.out_channels.append(num_filters[block] * 4)- # self.stages.append(nn.Sequential(*block_list))- self.stages.append(block_list)- else:- for block in range(len(depth)):- # block_list = []- block_list = nn.Sequential()- shortcut = False- # is_dcn = self.dcn_stage[block]- for i in range(depth[block]):- conv_name = "res" + str(block + 2) + chr(97 + i)- basic_block = BasicBlock(- in_channels=num_channels[block]- if i == 0 else num_filters[block],- out_channels=num_filters[block],- stride=2 if i == 0 and block != 0 else 1,- shortcut=shortcut,- if_first=block == i == 0,- name=conv_name)-- shortcut = True- block_list.add_module('bb_%d_%d' % (block, i), basic_block)- # block_list.append(basic_block)- if block in self.out_indices:- self.out_channels.append(num_filters[block])- self.stages.append(block_list)-- # self.stages.append(nn.Sequential(*block_list))--- def forward(self, inputs):- y = self.conv1_1(inputs)- y = self.conv1_2(y)- y = self.conv1_3(y)- y = self.pool2d_max(y)- out = []- for i, block in enumerate(self.stages):- y = block(y)- if i in self.out_indices:- out.append(y)- return out\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/det_resnet_vd_sast.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/det_resnet_vd_sast.pydeleted file mode 100755index 0f496439..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/det_resnet_vd_sast.py+++ /dev/null@@ -1,279 +0,0 @@-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import os, sys-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation-# import paddle-# from paddle import ParamAttr-# import paddle.nn as nn-# import paddle.nn.functional as F--__all__ = ["ResNet_SAST"]---class ConvBNLayer(nn.Module):- def __init__(- self,- in_channels,- out_channels,- kernel_size,- stride=1,- groups=1,- is_vd_mode=False,- act=None,- name=None, ):- super(ConvBNLayer, self).__init__()-- self.is_vd_mode = is_vd_mode- self._pool2d_avg = nn.AvgPool2d(- kernel_size=2, stride=2, padding=0, ceil_mode=True)- self._conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=(kernel_size - 1) // 2,- groups=groups,- bias=False)- if name == "conv1":- bn_name = "bn_" + name- else:- bn_name = "bn" + name[3:]- self._batch_norm = nn.BatchNorm2d(- out_channels,)- self.act = act- if act is not None:- self._act = Activation(act_type=act)--- def forward(self, inputs):- if self.is_vd_mode:- inputs = self._pool2d_avg(inputs)- y = self._conv(inputs)- y = self._batch_norm(y)- if self.act:- y = self._act(y)- return y---class BottleneckBlock(nn.Module):- def __init__(self,- in_channels,- out_channels,- stride,- shortcut=True,- if_first=False,- name=None):- super(BottleneckBlock, self).__init__()-- self.conv0 = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=1,- act='relu',- name=name + "_branch2a")- self.conv1 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels,- kernel_size=3,- stride=stride,- act='relu',- name=name + "_branch2b")- self.conv2 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels * 4,- kernel_size=1,- act=None,- name=name + "_branch2c")-- if not shortcut:- self.short = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels * 4,- kernel_size=1,- stride=1,- is_vd_mode=False if if_first else True,- name=name + "_branch1")-- self.shortcut = shortcut-- def forward(self, inputs):- y = self.conv0(inputs)- conv1 = self.conv1(y)- conv2 = self.conv2(conv1)-- if self.shortcut:- short = inputs- else:- short = self.short(inputs)- y = torch.add(short, conv2)- y = F.relu(y)- return y---class BasicBlock(nn.Module):- def __init__(self,- in_channels,- out_channels,- stride,- shortcut=True,- if_first=False,- name=None):- super(BasicBlock, self).__init__()- self.stride = stride- self.conv0 = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=3,- stride=stride,- act='relu',- name=name + "_branch2a")- self.conv1 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels,- kernel_size=3,- act=None,- name=name + "_branch2b")-- if not shortcut:- self.short = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=1,- stride=1,- is_vd_mode=False if if_first else True,- name=name + "_branch1")-- self.shortcut = shortcut-- def forward(self, inputs):- y = self.conv0(inputs)- conv1 = self.conv1(y)-- if self.shortcut:- short = inputs- else:- short = self.short(inputs)- y = torch.add(short, conv1)- y = F.relu(y)- return y---class ResNet_SAST(nn.Module):- def __init__(self, in_channels=3, layers=50, **kwargs):- super(ResNet_SAST, self).__init__()-- self.layers = layers- supported_layers = [18, 34, 50, 101, 152, 200]- assert layers in supported_layers, \- "supported layers are {} but input layer is {}".format(- supported_layers, layers)-- if layers == 18:- depth = [2, 2, 2, 2]- elif layers == 34 or layers == 50:- # depth = [3, 4, 6, 3]- depth = [3, 4, 6, 3, 3]- elif layers == 101:- depth = [3, 4, 23, 3]- elif layers == 152:- depth = [3, 8, 36, 3]- elif layers == 200:- depth = [3, 12, 48, 3]- # num_channels = [64, 256, 512,- # 1024] if layers >= 50 else [64, 64, 128, 256]- # num_filters = [64, 128, 256, 512]- num_channels = [64, 256, 512,- 1024, 2048] if layers >= 50 else [64, 64, 128, 256]- num_filters = [64, 128, 256, 512, 512]-- self.conv1_1 = ConvBNLayer(- in_channels=in_channels,- out_channels=32,- kernel_size=3,- stride=2,- act='relu',- name="conv1_1")- self.conv1_2 = ConvBNLayer(- in_channels=32,- out_channels=32,- kernel_size=3,- stride=1,- act='relu',- name="conv1_2")- self.conv1_3 = ConvBNLayer(- in_channels=32,- out_channels=64,- kernel_size=3,- stride=1,- act='relu',- name="conv1_3")- # self.pool2d_max = nn.MaxPool2D(kernel_size=3, stride=2, padding=1)- self.pool2d_max = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)-- self.stages = nn.ModuleList()- self.out_channels = [3, 64]- if layers >= 50:- for block in range(len(depth)):- # block_list = []- block_list = nn.Sequential()- shortcut = False- for i in range(depth[block]):- if layers in [101, 152] and block == 2:- if i == 0:- conv_name = "res" + str(block + 2) + "a"- else:- conv_name = "res" + str(block + 2) + "b" + str(i)- else:- conv_name = "res" + str(block + 2) + chr(97 + i)- bottleneck_block = BottleneckBlock(- in_channels=num_channels[block] if i == 0 else num_filters[block] * 4,- out_channels=num_filters[block],- stride=2 if i == 0 and block != 0 else 1,- shortcut=shortcut,- if_first=block == i == 0,- name=conv_name- )- shortcut = True- # block_list.append(bottleneck_block)- block_list.add_module('bb_%d_%d' % (block, i), bottleneck_block)- self.out_channels.append(num_filters[block] * 4)- # self.stages.append(nn.Sequential(*block_list))- self.stages.append(block_list)- else:- for block in range(len(depth)):- # block_list = []- block_list = nn.Sequential()- shortcut = False- for i in range(depth[block]):- conv_name = "res" + str(block + 2) + chr(97 + i)- basic_block = BasicBlock(- in_channels=num_channels[block]- if i == 0 else num_filters[block],- out_channels=num_filters[block],- stride=2 if i == 0 and block != 0 else 1,- shortcut=shortcut,- if_first=block == i == 0,- name=conv_name)- shortcut = True- # block_list.append(basic_block)- block_list.add_module('bb_%d_%d' % (block, i), basic_block)- self.out_channels.append(num_filters[block])- # self.stages.append(nn.Sequential(*block_list))- self.stages.append(block_list)-- def forward(self, inputs):- out = [inputs]- y = self.conv1_1(inputs)- y = self.conv1_2(y)- y = self.conv1_3(y)- out.append(y)- y = self.pool2d_max(y)- for block in self.stages:- y = block(y)- out.append(y)- return out\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/e2e_resnet_vd_pg.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/e2e_resnet_vd_pg.pydeleted file mode 100755index d6ff30f4..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/e2e_resnet_vd_pg.py+++ /dev/null@@ -1,247 +0,0 @@--from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation--__all__ = ["ResNet"]---class ConvBNLayer(nn.Module):- def __init__(- self,- in_channels,- out_channels,- kernel_size,- stride=1,- groups=1,- is_vd_mode=False,- act=None,- name=None, ):- super(ConvBNLayer, self).__init__()-- self.is_vd_mode = is_vd_mode- self._pool2d_avg = nn.AvgPool2d(- kernel_size=2, stride=2, padding=0, ceil_mode=True)- self._conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=(kernel_size - 1) // 2,- groups=groups,- bias=False)- if name == "conv1":- bn_name = "bn_" + name- else:- bn_name = "bn" + name[3:]- self._batch_norm = nn.BatchNorm2d(out_channels)- self.act = act- if self.act is not None:- self._act = Activation(act_type=self.act, inplace=True)-- def forward(self, inputs):- y = self._conv(inputs)- y = self._batch_norm(y)- if self.act is not None:- y = self._act(y)- return y---class BottleneckBlock(nn.Module):- def __init__(self,- in_channels,- out_channels,- stride,- shortcut=True,- if_first=False,- name=None):- super(BottleneckBlock, self).__init__()-- self.conv0 = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=1,- act='relu',- name=name + "_branch2a")- self.conv1 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels,- kernel_size=3,- stride=stride,- act='relu',- name=name + "_branch2b")- self.conv2 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels * 4,- kernel_size=1,- act=None,- name=name + "_branch2c")-- if not shortcut:- self.short = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels * 4,- kernel_size=1,- stride=stride,- is_vd_mode=False if if_first else True,- name=name + "_branch1")-- self.shortcut = shortcut-- def forward(self, inputs):- y = self.conv0(inputs)- conv1 = self.conv1(y)- conv2 = self.conv2(conv1)-- if self.shortcut:- short = inputs- else:- short = self.short(inputs)- y = torch.add(short, conv2)- y = F.relu(y)- return y---class BasicBlock(nn.Module):- def __init__(self,- in_channels,- out_channels,- stride,- shortcut=True,- if_first=False,- name=None):- super(BasicBlock, self).__init__()- self.stride = stride- self.conv0 = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=3,- stride=stride,- act='relu',- name=name + "_branch2a")- self.conv1 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels,- kernel_size=3,- act=None,- name=name + "_branch2b")-- if not shortcut:- self.short = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=1,- stride=1,- is_vd_mode=False if if_first else True,- name=name + "_branch1")-- self.shortcut = shortcut-- def forward(self, inputs):- y = self.conv0(inputs)- conv1 = self.conv1(y)-- if self.shortcut:- short = inputs- else:- short = self.short(inputs)- y = torch.add(short, conv1)- y = F.relu(y)- return y---class ResNet(nn.Module):- def __init__(self, in_channels=3, layers=50, **kwargs):- super(ResNet, self).__init__()-- self.layers = layers- supported_layers = [18, 34, 50, 101, 152, 200]- assert layers in supported_layers, \- "supported layers are {} but input layer is {}".format(- supported_layers, layers)-- if layers == 18:- depth = [2, 2, 2, 2]- elif layers == 34 or layers == 50:- # depth = [3, 4, 6, 3]- depth = [3, 4, 6, 3, 3]- elif layers == 101:- depth = [3, 4, 23, 3]- elif layers == 152:- depth = [3, 8, 36, 3]- elif layers == 200:- depth = [3, 12, 48, 3]- num_channels = [64, 256, 512, 1024,- 2048] if layers >= 50 else [64, 64, 128, 256]- num_filters = [64, 128, 256, 512, 512]-- self.conv1_1 = ConvBNLayer(- in_channels=in_channels,- out_channels=64,- kernel_size=7,- stride=2,- act='relu',- name="conv1_1")- self.pool2d_max = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)-- self.stages = nn.ModuleList()- self.out_channels = [3, 64]- # num_filters = [64, 128, 256, 512, 512]- if layers >= 50:- for block in range(len(depth)):- block_list = nn.Sequential()- shortcut = False- for i in range(depth[block]):- if layers in [101, 152] and block == 2:- if i == 0:- conv_name = "res" + str(block + 2) + "a"- else:- conv_name = "res" + str(block + 2) + "b" + str(i)- else:- conv_name = "res" + str(block + 2) + chr(97 + i)- bottleneckBlock = BottleneckBlock(- in_channels=num_channels[block]- if i == 0 else num_filters[block] * 4,- out_channels=num_filters[block],- stride=2 if i == 0 and block != 0 else 1,- shortcut=shortcut,- if_first=block == i == 0,- name=conv_name)- shortcut = True- block_list.add_module('bb_%d_%d' % (block, i), bottleneckBlock)- self.out_channels.append(num_filters[block] * 4)- self.stages.append(block_list)- else:- for block in range(len(depth)):- block_list = nn.Sequential()- shortcut = False- for i in range(depth[block]):- conv_name = "res" + str(block + 2) + chr(97 + i)- basicBlock = BasicBlock(- in_channels=num_channels[block]- if i == 0 else num_filters[block],- out_channels=num_filters[block],- stride=2 if i == 0 and block != 0 else 1,- shortcut=shortcut,- if_first=block == i == 0,- name=conv_name)- shortcut = True- block_list.add_module('bb_%d_%d' % (block, i), basicBlock)- self.out_channels.append(num_filters[block])- self.stages.append(block_list)--- def forward(self, inputs):- out = [inputs]- y = self.conv1_1(inputs)- out.append(y)- y = self.pool2d_max(y)- for block in self.stages:- y = block(y)- out.append(y)- return outdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_densenet.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_densenet.pydeleted file mode 100755index 8c1989f3..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_densenet.py+++ /dev/null@@ -1,133 +0,0 @@-"""-This code is refer from:-https://github.com/LBH1024/CAN/models/densenet.py--"""--from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import math-import torch-import torch.nn as nn-import torch.nn.functional as F---class Bottleneck(nn.Module):- def __init__(self, nChannels, growthRate, use_dropout):- super(Bottleneck, self).__init__()- interChannels = 4 * growthRate- self.bn1 = nn.BatchNorm2d(interChannels)- self.conv1 = nn.Conv2d(- nChannels, interChannels, kernel_size=1,- bias=True) # Xavier initialization- self.bn2 = nn.BatchNorm2d(growthRate)- self.conv2 = nn.Conv2d(- interChannels, growthRate, kernel_size=3, padding=1,- bias=True) # Xavier initialization- self.use_dropout = use_dropout- self.dropout = nn.Dropout(p=0.2)-- def forward(self, x):- out = F.relu(self.bn1(self.conv1(x)))- if self.use_dropout:- out = self.dropout(out)- out = F.relu(self.bn2(self.conv2(out)))- if self.use_dropout:- out = self.dropout(out)- out = torch.cat([x, out], 1)- return out---class SingleLayer(nn.Module):- def __init__(self, nChannels, growthRate, use_dropout):- super(SingleLayer, self).__init__()- self.bn1 = nn.BatchNorm2d(nChannels)- self.conv1 = nn.Conv2d(- nChannels, growthRate, kernel_size=3, padding=1, bias=False)-- self.use_dropout = use_dropout- self.dropout = nn.Dropout(p=0.2)-- def forward(self, x):- out = self.conv1(F.relu(x))- if self.use_dropout:- out = self.dropout(out)-- out = torch.cat([x, out], 1)- return out---class Transition(nn.Module):- def __init__(self, nChannels, out_channels, use_dropout):- super(Transition, self).__init__()- self.bn1 = nn.BatchNorm2d(out_channels)- self.conv1 = nn.Conv2d(- nChannels, out_channels, kernel_size=1, bias=False)- self.use_dropout = use_dropout- self.dropout = nn.Dropout(p=0.2)-- def forward(self, x):- out = F.relu(self.bn1(self.conv1(x)))- if self.use_dropout:- out = self.dropout(out)- out = F.avg_pool2d(out, 2, ceil_mode=True, count_include_pad=False)- return out---class DenseNet(nn.Module):- def __init__(self, growthRate, reduction, bottleneck, use_dropout,- input_channel, **kwargs):- super(DenseNet, self).__init__()-- nDenseBlocks = 16- nChannels = 2 * growthRate-- self.conv1 = nn.Conv2d(- input_channel,- nChannels,- kernel_size=7,- padding=3,- stride=2,- bias=False)- self.dense1 = self._make_dense(nChannels, growthRate, nDenseBlocks,- bottleneck, use_dropout)- nChannels += nDenseBlocks * growthRate- out_channels = int(math.floor(nChannels * reduction))- self.trans1 = Transition(nChannels, out_channels, use_dropout)-- nChannels = out_channels- self.dense2 = self._make_dense(nChannels, growthRate, nDenseBlocks,- bottleneck, use_dropout)- nChannels += nDenseBlocks * growthRate- out_channels = int(math.floor(nChannels * reduction))- self.trans2 = Transition(nChannels, out_channels, use_dropout)-- nChannels = out_channels- self.dense3 = self._make_dense(nChannels, growthRate, nDenseBlocks,- bottleneck, use_dropout)- self.out_channels = out_channels-- def _make_dense(self, nChannels, growthRate, nDenseBlocks, bottleneck,- use_dropout):- layers = []- for i in range(int(nDenseBlocks)):- if bottleneck:- layers.append(Bottleneck(nChannels, growthRate, use_dropout))- else:- layers.append(SingleLayer(nChannels, growthRate, use_dropout))- nChannels += growthRate- return nn.Sequential(*layers)-- def forward(self, inputs):- x, x_m, y = inputs- out = self.conv1(x)- out = F.relu(out, inplace=True)- out = F.max_pool2d(out, 2, ceil_mode=True)- out = self.dense1(out)- out = self.trans1(out)- out = self.dense2(out)- out = self.trans2(out)- out = self.dense3(out)- return out, x_m, ydiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_hgnet.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_hgnet.pyold mode 100755new mode 100644index fecb1bcc..c1515a71--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_hgnet.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_hgnet.py@@ -1,16 +1,12 @@import torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nnclass ConvBNAct(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride,- groups=1,- use_act=True):+ def __init__(+ self, in_channels, out_channels, kernel_size, stride, groups=1, use_act=True+ ):super().__init__()self.use_act = use_actself.conv = nn.Conv2d(@@ -20,7 +16,8 @@ class ConvBNAct(nn.Module):stride,padding=(kernel_size - 1) // 2,groups=groups,- bias=False)+ bias=False,+ )self.bn = nn.BatchNorm2d(out_channels)if self.use_act:self.act = nn.ReLU()@@ -42,7 +39,8 @@ class ESEModule(nn.Module):out_channels=channels,kernel_size=1,stride=1,- padding=0)+ padding=0,+ )self.sigmoid = nn.Sigmoid()def forward(self, x):@@ -55,12 +53,13 @@ class ESEModule(nn.Module):class HG_Block(nn.Module):def __init__(- self,- in_channels,- mid_channels,- out_channels,- layer_num,- identity=False, ):+ self,+ in_channels,+ mid_channels,+ out_channels,+ layer_num,+ identity=False,+ ):super().__init__()self.identity = identity@@ -70,14 +69,18 @@ class HG_Block(nn.Module):in_channels=in_channels,out_channels=mid_channels,kernel_size=3,- stride=1))+ stride=1,+ )+ )for _ in range(layer_num - 1):self.layers.append(ConvBNAct(in_channels=mid_channels,out_channels=mid_channels,kernel_size=3,- stride=1))+ stride=1,+ )+ )# feature aggregationtotal_channels = in_channels + layer_num * mid_channels@@ -85,7 +88,8 @@ class HG_Block(nn.Module):in_channels=total_channels,out_channels=out_channels,kernel_size=1,- stride=1)+ stride=1,+ )self.att = ESEModule(out_channels)def forward(self, x):@@ -104,14 +108,16 @@ class HG_Block(nn.Module):class HG_Stage(nn.Module):- def __init__(self,- in_channels,- mid_channels,- out_channels,- block_num,- layer_num,- downsample=True,- stride=[2, 1]):+ def __init__(+ self,+ in_channels,+ mid_channels,+ out_channels,+ block_num,+ layer_num,+ downsample=True,+ stride=[2, 1],+ ):super().__init__()self.downsample = downsampleif downsample:@@ -121,24 +127,19 @@ class HG_Stage(nn.Module):kernel_size=3,stride=stride,groups=in_channels,- use_act=False)+ use_act=False,+ )blocks_list = []blocks_list.append(- HG_Block(- in_channels,- mid_channels,- out_channels,- layer_num,- identity=False))+ HG_Block(in_channels, mid_channels, out_channels, layer_num, identity=False)+ )for _ in range(block_num - 1):blocks_list.append(HG_Block(- out_channels,- mid_channels,- out_channels,- layer_num,- identity=True))+ out_channels, mid_channels, out_channels, layer_num, identity=True+ )+ )self.blocks = nn.Sequential(*blocks_list)def forward(self, x):@@ -164,29 +165,31 @@ class PPHGNet(nn.Module):"""def __init__(- self,- stem_channels,- stage_config,- layer_num,- in_channels=3,- det=False,- out_indices=None):+ self,+ stem_channels,+ stage_config,+ layer_num,+ in_channels=3,+ det=False,+ out_indices=None,+ ):super().__init__()self.det = det- self.out_indices = out_indices if out_indices is not None else [- 0, 1, 2, 3- ]+ self.out_indices = out_indices if out_indices is not None else [0, 1, 2, 3]# stemstem_channels.insert(0, in_channels)- self.stem = nn.Sequential(* [- ConvBNAct(- in_channels=stem_channels[i],- out_channels=stem_channels[i + 1],- kernel_size=3,- stride=2 if i == 0 else 1) for i in range(- len(stem_channels) - 1)- ])+ self.stem = nn.Sequential(+ *[+ ConvBNAct(+ in_channels=stem_channels[i],+ out_channels=stem_channels[i + 1],+ kernel_size=3,+ stride=2 if i == 0 else 1,+ )+ for i in range(len(stem_channels) - 1)+ ]+ )if self.det:self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)@@ -194,11 +197,25 @@ class PPHGNet(nn.Module):self.stages = nn.ModuleList()self.out_channels = []for block_id, k in enumerate(stage_config):- in_channels, mid_channels, out_channels, block_num, downsample, stride = stage_config[- k]+ (+ in_channels,+ mid_channels,+ out_channels,+ block_num,+ downsample,+ stride,+ ) = stage_config[k]self.stages.append(- HG_Stage(in_channels, mid_channels, out_channels, block_num,- layer_num, downsample, stride))+ HG_Stage(+ in_channels,+ mid_channels,+ out_channels,+ block_num,+ layer_num,+ downsample,+ stride,+ )+ )if block_id in self.out_indices:self.out_channels.append(out_channels)@@ -237,32 +254,6 @@ class PPHGNet(nn.Module):return x-def PPHGNet_tiny(pretrained=False, use_ssld=False, **kwargs):- """- PPHGNet_tiny- Args:- pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.- If str, means the path of the pretrained model.- use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.- Returns:- model: nn.Layer. Specific `PPHGNet_tiny` model depends on args.- """- stage_config = {- # in_channels, mid_channels, out_channels, blocks, downsample- "stage1": [96, 96, 224, 1, False, [2, 1]],- "stage2": [224, 128, 448, 1, True, [1, 2]],- "stage3": [448, 160, 512, 2, True, [2, 1]],- "stage4": [512, 192, 768, 1, True, [2, 1]],- }-- model = PPHGNet(- stem_channels=[48, 48, 96],- stage_config=stage_config,- layer_num=5,- **kwargs)- return model--def PPHGNet_small(pretrained=False, use_ssld=False, det=False, **kwargs):"""PPHGNet_small@@ -294,31 +285,6 @@ def PPHGNet_small(pretrained=False, use_ssld=False, det=False, **kwargs):stage_config=stage_config_det if det else stage_config_rec,layer_num=6,det=det,- **kwargs)- return model---def PPHGNet_base(pretrained=False, use_ssld=True, **kwargs):- """- PPHGNet_base- Args:- pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.- If str, means the path of the pretrained model.- use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.- Returns:- model: nn.Layer. Specific `PPHGNet_base` model depends on args.- """- stage_config = {- # in_channels, mid_channels, out_channels, blocks, downsample- "stage1": [160, 192, 320, 1, False, [2, 1]],- "stage2": [320, 224, 640, 2, True, [1, 2]],- "stage3": [640, 256, 960, 3, True, [2, 1]],- "stage4": [960, 288, 1280, 2, True, [2, 1]],- }-- model = PPHGNet(- stem_channels=[96, 96, 160],- stage_config=stage_config,- layer_num=7,- **kwargs)+ **kwargs+ )return modeldiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_lcnetv3.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_lcnetv3.pyold mode 100755new mode 100644index a25bfeb2..e2bd4572--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_lcnetv3.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_lcnetv3.py@@ -12,43 +12,54 @@# See the License for the specific language governing permissions and# limitations under the License.-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function+from __future__ import absolute_import, division, print_functionimport torch-import torch.nn as nnimport torch.nn.functional as F-from pytorchocr.modeling.common import Activation+from torch import nn-# from paddle.nn.initializer import Constant, KaimingNormal-# from paddle.nn import AdaptiveAvgPool2D, BatchNorm2D, Conv2D, Dropout, Hardsigmoid, Hardswish, Identity, Linear, ReLU-# from paddle.regularizer import L2Decay+from ..common import ActivationNET_CONFIG_det = {"blocks2":- #k, in_c, out_c, s, use_se+ # k, in_c, out_c, s, use_se[[3, 16, 32, 1, False]],"blocks3": [[3, 32, 64, 2, False], [3, 64, 64, 1, False]],"blocks4": [[3, 64, 128, 2, False], [3, 128, 128, 1, False]],- "blocks5":- [[3, 128, 256, 2, False], [5, 256, 256, 1, False], [5, 256, 256, 1, False],- [5, 256, 256, 1, False], [5, 256, 256, 1, False]],- "blocks6": [[5, 256, 512, 2, True], [5, 512, 512, 1, True],- [5, 512, 512, 1, False], [5, 512, 512, 1, False]]+ "blocks5": [+ [3, 128, 256, 2, False],+ [5, 256, 256, 1, False],+ [5, 256, 256, 1, False],+ [5, 256, 256, 1, False],+ [5, 256, 256, 1, False],+ ],+ "blocks6": [+ [5, 256, 512, 2, True],+ [5, 512, 512, 1, True],+ [5, 512, 512, 1, False],+ [5, 512, 512, 1, False],+ ],}NET_CONFIG_rec = {"blocks2":- #k, in_c, out_c, s, use_se+ # k, in_c, out_c, s, use_se[[3, 16, 32, 1, False]],"blocks3": [[3, 32, 64, 1, False], [3, 64, 64, 1, False]],"blocks4": [[3, 64, 128, (2, 1), False], [3, 128, 128, 1, False]],- "blocks5":- [[3, 128, 256, (1, 2), False], [5, 256, 256, 1, False],- [5, 256, 256, 1, False], [5, 256, 256, 1, False], [5, 256, 256, 1, False]],- "blocks6": [[5, 256, 512, (2, 1), True], [5, 512, 512, 1, True],- [5, 512, 512, (2, 1), False], [5, 512, 512, 1, False]]+ "blocks5": [+ [3, 128, 256, (1, 2), False],+ [5, 256, 256, 1, False],+ [5, 256, 256, 1, False],+ [5, 256, 256, 1, False],+ [5, 256, 256, 1, False],+ ],+ "blocks6": [+ [5, 256, 512, (2, 1), True],+ [5, 512, 512, 1, True],+ [5, 512, 512, (2, 1), False],+ [5, 512, 512, 1, False],+ ],}@@ -62,8 +73,7 @@ def make_divisible(v, divisor=16, min_value=None):class LearnableAffineBlock(nn.Module):- def __init__(self, scale_value=1.0, bias_value=0.0, lr_mult=1.0,- lab_lr=0.1):+ def __init__(self, scale_value=1.0, bias_value=0.0, lr_mult=1.0, lab_lr=0.1):super().__init__()self.scale = nn.Parameter(torch.Tensor([scale_value]))self.bias = nn.Parameter(torch.Tensor([bias_value]))@@ -73,13 +83,9 @@ class LearnableAffineBlock(nn.Module):class ConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride,- groups=1,- lr_mult=1.0):+ def __init__(+ self, in_channels, out_channels, kernel_size, stride, groups=1, lr_mult=1.0+ ):super().__init__()self.conv = nn.Conv2d(in_channels=in_channels,@@ -88,7 +94,8 @@ class ConvBNLayer(nn.Module):stride=stride,padding=(kernel_size - 1) // 2,groups=groups,- bias=False)+ bias=False,+ )self.bn = nn.BatchNorm2d(out_channels,@@ -115,15 +122,17 @@ class Act(nn.Module):class LearnableRepLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride=1,- groups=1,- num_conv_branches=1,- lr_mult=1.0,- lab_lr=0.1):+ def __init__(+ self,+ in_channels,+ out_channels,+ kernel_size,+ stride=1,+ groups=1,+ num_conv_branches=1,+ lr_mult=1.0,+ lab_lr=0.1,+ ):super().__init__()self.is_repped = Falseself.groups = groups@@ -134,27 +143,35 @@ class LearnableRepLayer(nn.Module):self.num_conv_branches = num_conv_branchesself.padding = (kernel_size - 1) // 2- self.identity = nn.BatchNorm2d(- num_features=in_channels,- ) if out_channels == in_channels and stride == 1 else None+ self.identity = (+ nn.BatchNorm2d(+ num_features=in_channels,+ )+ if out_channels == in_channels and stride == 1+ else None+ )++ self.conv_kxk = nn.ModuleList(+ [+ ConvBNLayer(+ in_channels,+ out_channels,+ kernel_size,+ stride,+ groups=groups,+ lr_mult=lr_mult,+ )+ for _ in range(self.num_conv_branches)+ ]+ )- self.conv_kxk = nn.ModuleList([+ self.conv_1x1 = (ConvBNLayer(- in_channels,- out_channels,- kernel_size,- stride,- groups=groups,- lr_mult=lr_mult) for _ in range(self.num_conv_branches)- ])-- self.conv_1x1 = ConvBNLayer(- in_channels,- out_channels,- 1,- stride,- groups=groups,- lr_mult=lr_mult) if kernel_size > 1 else None+ in_channels, out_channels, 1, stride, groups=groups, lr_mult=lr_mult+ )+ if kernel_size > 1+ else None+ )self.lab = LearnableAffineBlock(lr_mult=lr_mult, lab_lr=lab_lr)self.act = Act(lr_mult=lr_mult, lab_lr=lab_lr)@@ -192,7 +209,8 @@ class LearnableRepLayer(nn.Module):kernel_size=self.kernel_size,stride=self.stride,padding=self.padding,- groups=self.groups)+ groups=self.groups,+ )self.reparam_conv.weight.data = kernelself.reparam_conv.bias.data = biasself.is_repped = True@@ -205,8 +223,9 @@ class LearnableRepLayer(nn.Module):def _get_kernel_bias(self):kernel_conv_1x1, bias_conv_1x1 = self._fuse_bn_tensor(self.conv_1x1)- kernel_conv_1x1 = self._pad_kernel_1x1_to_kxk(kernel_conv_1x1,- self.kernel_size // 2)+ kernel_conv_1x1 = self._pad_kernel_1x1_to_kxk(+ kernel_conv_1x1, self.kernel_size // 2+ )kernel_identity, bias_identity = self._fuse_bn_tensor(self.identity)@@ -233,15 +252,16 @@ class LearnableRepLayer(nn.Module):eps = branch.bn._epsilonelse:assert isinstance(branch, nn.BatchNorm2d)- if not hasattr(self, 'id_tensor'):+ if not hasattr(self, "id_tensor"):input_dim = self.in_channels // self.groupskernel_value = torch.zeros(- (self.in_channels, input_dim, self.kernel_size,- self.kernel_size),- dtype=branch.weight.dtype)+ (self.in_channels, input_dim, self.kernel_size, self.kernel_size),+ dtype=branch.weight.dtype,+ )for i in range(self.in_channels):- kernel_value[i, i % input_dim, self.kernel_size // 2,- self.kernel_size // 2] = 1+ kernel_value[+ i, i % input_dim, self.kernel_size // 2, self.kernel_size // 2+ ] = 1self.id_tensor = kernel_valuekernel = self.id_tensorrunning_mean = branch._mean@@ -287,15 +307,17 @@ class SELayer(nn.Module):class LCNetV3Block(nn.Module):- def __init__(self,- in_channels,- out_channels,- stride,- dw_size,- use_se=False,- conv_kxk_num=4,- lr_mult=1.0,- lab_lr=0.1):+ def __init__(+ self,+ in_channels,+ out_channels,+ stride,+ dw_size,+ use_se=False,+ conv_kxk_num=4,+ lr_mult=1.0,+ lab_lr=0.1,+ ):super().__init__()self.use_se = use_seself.dw_conv = LearnableRepLayer(@@ -306,7 +328,8 @@ class LCNetV3Block(nn.Module):groups=in_channels,num_conv_branches=conv_kxk_num,lr_mult=lr_mult,- lab_lr=lab_lr)+ lab_lr=lab_lr,+ )if use_se:self.se = SELayer(in_channels, lr_mult=lr_mult)self.pw_conv = LearnableRepLayer(@@ -316,7 +339,8 @@ class LCNetV3Block(nn.Module):stride=1,num_conv_branches=conv_kxk_num,lr_mult=lr_mult,- lab_lr=lab_lr)+ lab_lr=lab_lr,+ )def forward(self, x):x = self.dw_conv(x)@@ -327,13 +351,15 @@ class LCNetV3Block(nn.Module):class PPLCNetV3(nn.Module):- def __init__(self,- scale=1.0,- conv_kxk_num=4,- lr_mult_list=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0],- lab_lr=0.1,- det=False,- **kwargs):+ def __init__(+ self,+ scale=1.0,+ conv_kxk_num=4,+ lr_mult_list=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0],+ lab_lr=0.1,+ det=False,+ **kwargs+ ):super().__init__()self.scale = scaleself.lr_mult_list = lr_mult_list@@ -341,90 +367,102 @@ class PPLCNetV3(nn.Module):self.net_config = NET_CONFIG_det if self.det else NET_CONFIG_rec- assert isinstance(self.lr_mult_list, (- list, tuple- )), "lr_mult_list should be in (list, tuple) but got {}".format(- type(self.lr_mult_list))- assert len(self.lr_mult_list- ) == 6, "lr_mult_list length should be 6 but got {}".format(- len(self.lr_mult_list))+ assert isinstance(+ self.lr_mult_list, (list, tuple)+ ), "lr_mult_list should be in (list, tuple) but got {}".format(+ type(self.lr_mult_list)+ )+ assert (+ len(self.lr_mult_list) == 6+ ), "lr_mult_list length should be 6 but got {}".format(len(self.lr_mult_list))self.conv1 = ConvBNLayer(in_channels=3,out_channels=make_divisible(16 * scale),kernel_size=3,stride=2,- lr_mult=self.lr_mult_list[0])-- self.blocks2 = nn.Sequential(*[- LCNetV3Block(- in_channels=make_divisible(in_c * scale),- out_channels=make_divisible(out_c * scale),- dw_size=k,- stride=s,- use_se=se,- conv_kxk_num=conv_kxk_num,- lr_mult=self.lr_mult_list[1],- lab_lr=lab_lr)- for i, (k, in_c, out_c, s, se- ) in enumerate(self.net_config["blocks2"])- ])-- self.blocks3 = nn.Sequential(*[- LCNetV3Block(- in_channels=make_divisible(in_c * scale),- out_channels=make_divisible(out_c * scale),- dw_size=k,- stride=s,- use_se=se,- conv_kxk_num=conv_kxk_num,- lr_mult=self.lr_mult_list[2],- lab_lr=lab_lr)- for i, (k, in_c, out_c, s, se- ) in enumerate(self.net_config["blocks3"])- ])-- self.blocks4 = nn.Sequential(*[- LCNetV3Block(- in_channels=make_divisible(in_c * scale),- out_channels=make_divisible(out_c * scale),- dw_size=k,- stride=s,- use_se=se,- conv_kxk_num=conv_kxk_num,- lr_mult=self.lr_mult_list[3],- lab_lr=lab_lr)- for i, (k, in_c, out_c, s, se- ) in enumerate(self.net_config["blocks4"])- ])-- self.blocks5 = nn.Sequential(*[- LCNetV3Block(- in_channels=make_divisible(in_c * scale),- out_channels=make_divisible(out_c * scale),- dw_size=k,- stride=s,- use_se=se,- conv_kxk_num=conv_kxk_num,- lr_mult=self.lr_mult_list[4],- lab_lr=lab_lr)- for i, (k, in_c, out_c, s, se- ) in enumerate(self.net_config["blocks5"])- ])-- self.blocks6 = nn.Sequential(*[- LCNetV3Block(- in_channels=make_divisible(in_c * scale),- out_channels=make_divisible(out_c * scale),- dw_size=k,- stride=s,- use_se=se,- conv_kxk_num=conv_kxk_num,- lr_mult=self.lr_mult_list[5],- lab_lr=lab_lr)- for i, (k, in_c, out_c, s, se- ) in enumerate(self.net_config["blocks6"])- ])+ lr_mult=self.lr_mult_list[0],+ )++ self.blocks2 = nn.Sequential(+ *[+ LCNetV3Block(+ in_channels=make_divisible(in_c * scale),+ out_channels=make_divisible(out_c * scale),+ dw_size=k,+ stride=s,+ use_se=se,+ conv_kxk_num=conv_kxk_num,+ lr_mult=self.lr_mult_list[1],+ lab_lr=lab_lr,+ )+ for i, (k, in_c, out_c, s, se) in enumerate(self.net_config["blocks2"])+ ]+ )++ self.blocks3 = nn.Sequential(+ *[+ LCNetV3Block(+ in_channels=make_divisible(in_c * scale),+ out_channels=make_divisible(out_c * scale),+ dw_size=k,+ stride=s,+ use_se=se,+ conv_kxk_num=conv_kxk_num,+ lr_mult=self.lr_mult_list[2],+ lab_lr=lab_lr,+ )+ for i, (k, in_c, out_c, s, se) in enumerate(self.net_config["blocks3"])+ ]+ )++ self.blocks4 = nn.Sequential(+ *[+ LCNetV3Block(+ in_channels=make_divisible(in_c * scale),+ out_channels=make_divisible(out_c * scale),+ dw_size=k,+ stride=s,+ use_se=se,+ conv_kxk_num=conv_kxk_num,+ lr_mult=self.lr_mult_list[3],+ lab_lr=lab_lr,+ )+ for i, (k, in_c, out_c, s, se) in enumerate(self.net_config["blocks4"])+ ]+ )++ self.blocks5 = nn.Sequential(+ *[+ LCNetV3Block(+ in_channels=make_divisible(in_c * scale),+ out_channels=make_divisible(out_c * scale),+ dw_size=k,+ stride=s,+ use_se=se,+ conv_kxk_num=conv_kxk_num,+ lr_mult=self.lr_mult_list[4],+ lab_lr=lab_lr,+ )+ for i, (k, in_c, out_c, s, se) in enumerate(self.net_config["blocks5"])+ ]+ )++ self.blocks6 = nn.Sequential(+ *[+ LCNetV3Block(+ in_channels=make_divisible(in_c * scale),+ out_channels=make_divisible(out_c * scale),+ dw_size=k,+ stride=s,+ use_se=se,+ conv_kxk_num=conv_kxk_num,+ lr_mult=self.lr_mult_list[5],+ lab_lr=lab_lr,+ )+ for i, (k, in_c, out_c, s, se) in enumerate(self.net_config["blocks6"])+ ]+ )self.out_channels = make_divisible(512 * scale)if self.det:@@ -436,15 +474,19 @@ class PPLCNetV3(nn.Module):make_divisible(self.net_config["blocks6"][-1][2] * scale),]- self.layer_list = nn.ModuleList([- nn.Conv2d(self.out_channels[0], int(mv_c[0] * scale), 1, 1, 0),- nn.Conv2d(self.out_channels[1], int(mv_c[1] * scale), 1, 1, 0),- nn.Conv2d(self.out_channels[2], int(mv_c[2] * scale), 1, 1, 0),- nn.Conv2d(self.out_channels[3], int(mv_c[3] * scale), 1, 1, 0)- ])+ self.layer_list = nn.ModuleList(+ [+ nn.Conv2d(self.out_channels[0], int(mv_c[0] * scale), 1, 1, 0),+ nn.Conv2d(self.out_channels[1], int(mv_c[1] * scale), 1, 1, 0),+ nn.Conv2d(self.out_channels[2], int(mv_c[2] * scale), 1, 1, 0),+ nn.Conv2d(self.out_channels[3], int(mv_c[3] * scale), 1, 1, 0),+ ]+ )self.out_channels = [- int(mv_c[0] * scale), int(mv_c[1] * scale),- int(mv_c[2] * scale), int(mv_c[3] * scale)+ int(mv_c[0] * scale),+ int(mv_c[1] * scale),+ int(mv_c[2] * scale),+ int(mv_c[3] * scale),]def forward(self, x):diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_lcnetv3_bak.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_lcnetv3_bak.pydeleted file mode 100755index 2c5d18bd..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_lcnetv3_bak.py+++ /dev/null@@ -1,444 +0,0 @@-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation--NET_CONFIG_det = {- "blocks2":- # k, in_c, out_c, s, use_se- [[3, 16, 32, 1, False]],- "blocks3": [[3, 32, 64, 2, False], [3, 64, 64, 1, False]],- "blocks4": [[3, 64, 128, 2, False], [3, 128, 128, 1, False]],- "blocks5":- [[3, 128, 256, 2, False], [5, 256, 256, 1, False], [5, 256, 256, 1, False],- [5, 256, 256, 1, False], [5, 256, 256, 1, False]],- "blocks6": [[5, 256, 512, 2, True], [5, 512, 512, 1, True],- [5, 512, 512, 1, False], [5, 512, 512, 1, False]]-}--NET_CONFIG_rec = {- "blocks2":- # k, in_c, out_c, s, use_se- [[3, 16, 32, 1, False]],- "blocks3": [[3, 32, 64, 1, False], [3, 64, 64, 1, False]],- "blocks4": [[3, 64, 128, (2, 1), False], [3, 128, 128, 1, False]],- "blocks5":- [[3, 128, 256, (1, 2), False], [5, 256, 256, 1, False],- [5, 256, 256, 1, False], [5, 256, 256, 1, False], [5, 256, 256, 1, False]],- "blocks6": [[5, 256, 512, (2, 1), True], [5, 512, 512, 1, True],- [5, 512, 512, (2, 1), False], [5, 512, 512, 1, False]]-}---def make_divisible(v, divisor=16, min_value=None):- if min_value is None:- min_value = divisor- new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)- if new_v < 0.9 * v:- new_v += divisor- return new_v---class LearnableAffineBlock(nn.Module):- def __init__(self, scale_value=1.0, bias_value=0.0, lr_mult=1.0,- lab_lr=0.1):- super().__init__()- self.scale = nn.Parameter(torch.Tensor([scale_value]))- self.bias = nn.Parameter(torch.Tensor([bias_value]))-- def forward(self, x):- return self.scale * x + self.bias---class ConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride,- groups=1,- lr_mult=1.0):- super().__init__()- self.conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=(kernel_size - 1) // 2,- groups=groups,- bias=False)-- self.bn = nn.BatchNorm2d(out_channels)-- def forward(self, x):- x = self.conv(x)- x = self.bn(x)- return x---class Act(nn.Module):- def __init__(self, act="hard_swish", lr_mult=1.0, lab_lr=0.1):- super().__init__()- assert act in ['hard_swish', 'relu']- self.act = Activation(act)- self.lab = LearnableAffineBlock(lr_mult=lr_mult, lab_lr=lab_lr)-- def forward(self, x):- return self.lab(self.act(x))---class LearnableRepLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride=1,- groups=1,- num_conv_branches=1,- lr_mult=1.0,- lab_lr=0.1):- super().__init__()- self.is_repped = False- self.groups = groups- self.stride = stride- self.kernel_size = kernel_size- self.in_channels = in_channels- self.out_channels = out_channels- self.num_conv_branches = num_conv_branches- self.padding = (kernel_size - 1) // 2- self.identity = nn.BatchNorm2d(in_channels) if out_channels == in_channels and stride == 1 else None-- self.conv_kxk = nn.ModuleList([- ConvBNLayer(- in_channels,- out_channels,- kernel_size,- stride,- groups=groups,- lr_mult=lr_mult) for _ in range(self.num_conv_branches)- ])-- self.conv_1x1 = ConvBNLayer(- in_channels,- out_channels,- 1,- stride,- groups=groups,- lr_mult=lr_mult) if kernel_size > 1 else None- self.lab = LearnableAffineBlock(lr_mult=lr_mult, lab_lr=lab_lr)- self.act = Act(lr_mult=lr_mult, lab_lr=lab_lr)-- def forward(self, x):- # for export- if self.is_repped:- out = self.lab(self.reparam_conv(x))- if self.stride != 2:- out = self.act(out)- return out-- out = 0- if self.identity is not None:- out += self.identity(x)-- if self.conv_1x1 is not None:- out += self.conv_1x1(x)-- for conv in self.conv_kxk:- out += conv(x)-- out = self.lab(out)- if self.stride != 2:- out = self.act(out)- return out-- def rep(self):- if self.is_repped:- return- kernel, bias = self._get_kernel_bias()- self.reparam_conv = nn.Conv2d(- in_channels=self.in_channels,- out_channels=self.out_channels,- kernel_size=self.kernel_size,- stride=self.stride,- padding=self.padding,- groups=self.groups)- self.reparam_conv.weight.data = kernel- self.reparam_conv.bias.data = bias- self.is_repped = True-- def _pad_kernel_1x1_to_kxk(self, kernel1x1, pad):- if not isinstance(kernel1x1, torch.Tensor):- return 0- else:- return nn.functional.pad(kernel1x1, [pad, pad, pad, pad])-- def _get_kernel_bias(self):- kernel_conv_1x1, bias_conv_1x1 = self._fuse_bn_tensor(self.conv_1x1)- kernel_conv_1x1 = self._pad_kernel_1x1_to_kxk(kernel_conv_1x1,- self.kernel_size // 2)-- kernel_identity, bias_identity = self._fuse_bn_tensor(self.identity)-- kernel_conv_kxk = 0- bias_conv_kxk = 0- for conv in self.conv_kxk:- kernel, bias = self._fuse_bn_tensor(conv)- kernel_conv_kxk += kernel- bias_conv_kxk += bias-- kernel_reparam = kernel_conv_kxk + kernel_conv_1x1 + kernel_identity- bias_reparam = bias_conv_kxk + bias_conv_1x1 + bias_identity- return kernel_reparam, bias_reparam-- def _fuse_bn_tensor(self, branch):- if not branch:- return 0, 0- elif isinstance(branch, ConvBNLayer):- kernel = branch.conv.weight- running_mean = branch.bn.running_mean- running_var = branch.bn.running_var- gamma = branch.bn.weight- beta = branch.bn.bias- eps = branch.bn.eps- else:- assert isinstance(branch, nn.BatchNorm2d)- if not hasattr(self, 'id_tensor'):- input_dim = self.in_channels // self.groups- kernel_value = torch.zeros(- (self.in_channels, input_dim, self.kernel_size,- self.kernel_size),- dtype=branch.weight.dtype)- for i in range(self.in_channels):- kernel_value[i, i % input_dim, self.kernel_size // 2,- self.kernel_size // 2] = 1- self.id_tensor = kernel_value- kernel = self.id_tensor- running_mean = branch.running_mean- running_var = branch.running_var- gamma = branch.weight- beta = branch.bias- eps = branch.eps- std = (running_var + eps).sqrt()- t = (gamma / std).reshape((-1, 1, 1, 1))- return kernel * t, beta - running_mean * gamma / std---class SELayer(nn.Module):- def __init__(self, channel, reduction=4, lr_mult=1.0):- super().__init__()- self.avg_pool = nn.AdaptiveAvgPool2d(1)- self.conv1 = nn.Conv2d(- in_channels=channel,- out_channels=channel // reduction,- kernel_size=1,- stride=1,- padding=0)- self.relu = nn.ReLU()- self.conv2 = nn.Conv2d(- in_channels=channel // reduction,- out_channels=channel,- kernel_size=1,- stride=1,- padding=0)- self.hardsigmoid = Activation('hard_sigmoid')-- def forward(self, x):- identity = x- x = self.avg_pool(x)- x = self.conv1(x)- x = self.relu(x)- x = self.conv2(x)- x = self.hardsigmoid(x)- x = x * identity- return x---class LCNetV3Block(nn.Module):- def __init__(self,- in_channels,- out_channels,- stride,- dw_size,- use_se=False,- conv_kxk_num=4,- lr_mult=1.0,- lab_lr=0.1):- super().__init__()- self.use_se = use_se- self.dw_conv = LearnableRepLayer(- in_channels=in_channels,- out_channels=in_channels,- kernel_size=dw_size,- stride=stride,- groups=in_channels,- num_conv_branches=conv_kxk_num,- lr_mult=lr_mult,- lab_lr=lab_lr)- if use_se:- self.se = SELayer(in_channels, lr_mult=lr_mult)- self.pw_conv = LearnableRepLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=1,- stride=1,- num_conv_branches=conv_kxk_num,- lr_mult=lr_mult,- lab_lr=lab_lr)-- def forward(self, x):- x = self.dw_conv(x)- if self.use_se:- x = self.se(x)- x = self.pw_conv(x)- return x---class PPLCNetV3(nn.Module):- def __init__(self,- scale=1.0,- conv_kxk_num=4,- lr_mult_list=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0],- lab_lr=0.1,- det=False,- **kwargs):- super().__init__()- self.scale = scale- self.lr_mult_list = lr_mult_list- self.det = det-- self.net_config = NET_CONFIG_det if self.det else NET_CONFIG_rec-- assert isinstance(self.lr_mult_list, (- list, tuple- )), "lr_mult_list should be in (list, tuple) but got {}".format(- type(self.lr_mult_list))- assert len(self.lr_mult_list- ) == 6, "lr_mult_list length should be 6 but got {}".format(- len(self.lr_mult_list))-- self.conv1 = ConvBNLayer(- in_channels=3,- out_channels=make_divisible(16 * scale),- kernel_size=3,- stride=2,- lr_mult=self.lr_mult_list[0])-- self.blocks2 = nn.Sequential(*[- LCNetV3Block(- in_channels=make_divisible(in_c * scale),- out_channels=make_divisible(out_c * scale),- dw_size=k,- stride=s,- use_se=se,- conv_kxk_num=conv_kxk_num,- lr_mult=self.lr_mult_list[1],- lab_lr=lab_lr)- for i, (k, in_c, out_c, s, se- ) in enumerate(self.net_config["blocks2"])- ])-- self.blocks3 = nn.Sequential(*[- LCNetV3Block(- in_channels=make_divisible(in_c * scale),- out_channels=make_divisible(out_c * scale),- dw_size=k,- stride=s,- use_se=se,- conv_kxk_num=conv_kxk_num,- lr_mult=self.lr_mult_list[2],- lab_lr=lab_lr)- for i, (k, in_c, out_c, s, se- ) in enumerate(self.net_config["blocks3"])- ])-- self.blocks4 = nn.Sequential(*[- LCNetV3Block(- in_channels=make_divisible(in_c * scale),- out_channels=make_divisible(out_c * scale),- dw_size=k,- stride=s,- use_se=se,- conv_kxk_num=conv_kxk_num,- lr_mult=self.lr_mult_list[3],- lab_lr=lab_lr)- for i, (k, in_c, out_c, s, se- ) in enumerate(self.net_config["blocks4"])- ])-- self.blocks5 = nn.Sequential(*[- LCNetV3Block(- in_channels=make_divisible(in_c * scale),- out_channels=make_divisible(out_c * scale),- dw_size=k,- stride=s,- use_se=se,- conv_kxk_num=conv_kxk_num,- lr_mult=self.lr_mult_list[4],- lab_lr=lab_lr)- for i, (k, in_c, out_c, s, se- ) in enumerate(self.net_config["blocks5"])- ])-- self.blocks6 = nn.Sequential(*[- LCNetV3Block(- in_channels=make_divisible(in_c * scale),- out_channels=make_divisible(out_c * scale),- dw_size=k,- stride=s,- use_se=se,- conv_kxk_num=conv_kxk_num,- lr_mult=self.lr_mult_list[5],- lab_lr=lab_lr)- for i, (k, in_c, out_c, s, se- ) in enumerate(self.net_config["blocks6"])- ])- self.out_channels = make_divisible(512 * scale)-- if self.det:- mv_c = [16, 24, 56, 480]- self.out_channels = [- make_divisible(self.net_config["blocks3"][-1][2] * scale),- make_divisible(self.net_config["blocks4"][-1][2] * scale),- make_divisible(self.net_config["blocks5"][-1][2] * scale),- make_divisible(self.net_config["blocks6"][-1][2] * scale),- ]-- self.layer_list = nn.ModuleList([- nn.Conv2d(self.out_channels[0], int(mv_c[0] * scale), 1, 1, 0),- nn.Conv2d(self.out_channels[1], int(mv_c[1] * scale), 1, 1, 0),- nn.Conv2d(self.out_channels[2], int(mv_c[2] * scale), 1, 1, 0),- nn.Conv2d(self.out_channels[3], int(mv_c[3] * scale), 1, 1, 0)- ])- self.out_channels = [- int(mv_c[0] * scale), int(mv_c[1] * scale),- int(mv_c[2] * scale), int(mv_c[3] * scale)- ]-- def forward(self, x):- out_list = []- x = self.conv1(x)-- x = self.blocks2(x)- x = self.blocks3(x)- out_list.append(x)- x = self.blocks4(x)- out_list.append(x)- x = self.blocks5(x)- out_list.append(x)- import numpy as np- x = torch.Tensor(np.load('../PaddleOCR4debug/tmp.npy'))- x = self.blocks6(x)- out_list.append(x)-- if self.det:- out_list[0] = self.layer_list[0](out_list[0])- out_list[1] = self.layer_list[1](out_list[1])- out_list[2] = self.layer_list[2](out_list[2])- out_list[3] = self.layer_list[3](out_list[3])- return out_list-- if self.training:- x = F.adaptive_avg_pool2d(x, [1, 40])- else:- x = F.avg_pool2d(x, [3, 2])- return x\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_mobilenet_v3.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_mobilenet_v3.pyold mode 100755new mode 100644index 52cc7a13..d284a6d4--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_mobilenet_v3.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_mobilenet_v3.py@@ -1,77 +1,84 @@-import os, sys-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation+from torch import nn++from .det_mobilenet_v3 import ConvBNLayer, ResidualUnit, make_divisible-from .det_mobilenet_v3 import ResidualUnit, ConvBNLayer, make_divisibleclass MobileNetV3(nn.Module):- def __init__(self,- in_channels=3,- model_name='small',- scale=0.5,- large_stride=None,- small_stride=None,- **kwargs):+ def __init__(+ self,+ in_channels=3,+ model_name="small",+ scale=0.5,+ large_stride=None,+ small_stride=None,+ **kwargs+ ):super(MobileNetV3, self).__init__()if small_stride is None:small_stride = [2, 2, 2, 2]if large_stride is None:large_stride = [1, 2, 2, 2]- assert isinstance(large_stride, list), "large_stride type must " \- "be list but got {}".format(type(large_stride))- assert isinstance(small_stride, list), "small_stride type must " \- "be list but got {}".format(type(small_stride))- assert len(large_stride) == 4, "large_stride length must be " \- "4 but got {}".format(len(large_stride))- assert len(small_stride) == 4, "small_stride length must be " \- "4 but got {}".format(len(small_stride))+ assert isinstance(+ large_stride, list+ ), "large_stride type must " "be list but got {}".format(type(large_stride))+ assert isinstance(+ small_stride, list+ ), "small_stride type must " "be list but got {}".format(type(small_stride))+ assert (+ len(large_stride) == 4+ ), "large_stride length must be " "4 but got {}".format(len(large_stride))+ assert (+ len(small_stride) == 4+ ), "small_stride length must be " "4 but got {}".format(len(small_stride))if model_name == "large":cfg = [# k, exp, c, se, nl, s,- [3, 16, 16, False, 'relu', large_stride[0]],- [3, 64, 24, False, 'relu', (large_stride[1], 1)],- [3, 72, 24, False, 'relu', 1],- [5, 72, 40, True, 'relu', (large_stride[2], 1)],- [5, 120, 40, True, 'relu', 1],- [5, 120, 40, True, 'relu', 1],- [3, 240, 80, False, 'hard_swish', 1],- [3, 200, 80, False, 'hard_swish', 1],- [3, 184, 80, False, 'hard_swish', 1],- [3, 184, 80, False, 'hard_swish', 1],- [3, 480, 112, True, 'hard_swish', 1],- [3, 672, 112, True, 'hard_swish', 1],- [5, 672, 160, True, 'hard_swish', (large_stride[3], 1)],- [5, 960, 160, True, 'hard_swish', 1],- [5, 960, 160, True, 'hard_swish', 1],+ [3, 16, 16, False, "relu", large_stride[0]],+ [3, 64, 24, False, "relu", (large_stride[1], 1)],+ [3, 72, 24, False, "relu", 1],+ [5, 72, 40, True, "relu", (large_stride[2], 1)],+ [5, 120, 40, True, "relu", 1],+ [5, 120, 40, True, "relu", 1],+ [3, 240, 80, False, "hard_swish", 1],+ [3, 200, 80, False, "hard_swish", 1],+ [3, 184, 80, False, "hard_swish", 1],+ [3, 184, 80, False, "hard_swish", 1],+ [3, 480, 112, True, "hard_swish", 1],+ [3, 672, 112, True, "hard_swish", 1],+ [5, 672, 160, True, "hard_swish", (large_stride[3], 1)],+ [5, 960, 160, True, "hard_swish", 1],+ [5, 960, 160, True, "hard_swish", 1],]cls_ch_squeeze = 960elif model_name == "small":cfg = [# k, exp, c, se, nl, s,- [3, 16, 16, True, 'relu', (small_stride[0], 1)],- [3, 72, 24, False, 'relu', (small_stride[1], 1)],- [3, 88, 24, False, 'relu', 1],- [5, 96, 40, True, 'hard_swish', (small_stride[2], 1)],- [5, 240, 40, True, 'hard_swish', 1],- [5, 240, 40, True, 'hard_swish', 1],- [5, 120, 48, True, 'hard_swish', 1],- [5, 144, 48, True, 'hard_swish', 1],- [5, 288, 96, True, 'hard_swish', (small_stride[3], 1)],- [5, 576, 96, True, 'hard_swish', 1],- [5, 576, 96, True, 'hard_swish', 1],+ [3, 16, 16, True, "relu", (small_stride[0], 1)],+ [3, 72, 24, False, "relu", (small_stride[1], 1)],+ [3, 88, 24, False, "relu", 1],+ [5, 96, 40, True, "hard_swish", (small_stride[2], 1)],+ [5, 240, 40, True, "hard_swish", 1],+ [5, 240, 40, True, "hard_swish", 1],+ [5, 120, 48, True, "hard_swish", 1],+ [5, 144, 48, True, "hard_swish", 1],+ [5, 288, 96, True, "hard_swish", (small_stride[3], 1)],+ [5, 576, 96, True, "hard_swish", 1],+ [5, 576, 96, True, "hard_swish", 1],]cls_ch_squeeze = 576else:- raise NotImplementedError("mode[" + model_name +- "_model] is not implemented!")+ raise NotImplementedError(+ "mode[" + model_name + "_model] is not implemented!"+ )supported_scale = [0.35, 0.5, 0.75, 1.0, 1.25]- assert scale in supported_scale, \- "supported scales are {} but input scale is {}".format(supported_scale, scale)+ assert (+ scale in supported_scale+ ), "supported scales are {} but input scale is {}".format(+ supported_scale, scale+ )inplanes = 16# conv1@@ -83,12 +90,13 @@ class MobileNetV3(nn.Module):padding=1,groups=1,if_act=True,- act='hard_swish',- name='conv1')+ act="hard_swish",+ name="conv1",+ )i = 0block_list = []inplanes = make_divisible(inplanes * scale)- for (k, exp, c, se, nl, s) in cfg:+ for k, exp, c, se, nl, s in cfg:block_list.append(ResidualUnit(in_channels=inplanes,@@ -98,7 +106,9 @@ class MobileNetV3(nn.Module):stride=s,use_se=se,act=nl,- name='conv' + str(i + 2)))+ name="conv" + str(i + 2),+ )+ )inplanes = make_divisible(scale * c)i += 1self.blocks = nn.Sequential(*block_list)@@ -111,8 +121,9 @@ class MobileNetV3(nn.Module):padding=0,groups=1,if_act=True,- act='hard_swish',- name='conv_last')+ act="hard_swish",+ name="conv_last",+ )self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)self.out_channels = make_divisible(scale * cls_ch_squeeze)@@ -122,4 +133,4 @@ class MobileNetV3(nn.Module):x = self.blocks(x)x = self.conv2(x)x = self.pool(x)- return x\ No newline at end of file+ return xdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_mv1_enhance.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_mv1_enhance.pyold mode 100755new mode 100644index b4f96434..447c48f6--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_mv1_enhance.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_mv1_enhance.py@@ -2,7 +2,8 @@ import os, sysimport torchimport torch.nn as nnimport torch.nn.functional as F-from pytorchocr.modeling.common import Activation++from ..common import Activationclass ConvBNLayer(nn.Module):diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_nrtr_mtb.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_nrtr_mtb.pydeleted file mode 100755index 33e375cd..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_nrtr_mtb.py+++ /dev/null@@ -1,36 +0,0 @@--import torch-from torch import nn---class MTB(nn.Module):- def __init__(self, cnn_num, in_channels):- super(MTB, self).__init__()- self.block = nn.Sequential()- self.out_channels = in_channels- self.cnn_num = cnn_num- if self.cnn_num == 2:- for i in range(self.cnn_num):- self.block.add_module(- 'conv_{}'.format(i),- nn.Conv2d(- in_channels=in_channels- if i == 0 else 32 * (2**(i - 1)),- out_channels=32 * (2**i),- kernel_size=3,- stride=2,- padding=1))- self.block.add_module('relu_{}'.format(i), nn.ReLU())- self.block.add_module('bn_{}'.format(i),- nn.BatchNorm2d(32 * (2**i)))--- def forward(self, images):- x = self.block(images)- if self.cnn_num == 2:- # (b, w, h, c)- x = x.permute(0, 3, 2, 1)- x_shape = x.shape- x = torch.reshape(- x, (x_shape[0], x_shape[1], x_shape[2] * x_shape[3]))- return xdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_resnet_31.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_resnet_31.pydeleted file mode 100755index ab7c30f8..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_resnet_31.py+++ /dev/null@@ -1,200 +0,0 @@-"""-This code is refer from:-https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textrecog/layers/conv_layer.py-https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textrecog/backbones/resnet31_ocr.py-"""--from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import torch-import torch.nn as nn-import torch.nn.functional as F-# import paddle-# from paddle import ParamAttr-# import paddle.nn as nn-# import paddle.nn.functional as F---__all__ = ["ResNet31"]---def conv3x3(in_channel, out_channel, stride=1):- return nn.Conv2d(- in_channel,- out_channel,- kernel_size=3,- stride=stride,- padding=1,- bias=False)---class BasicBlock(nn.Module):- expansion = 1-- def __init__(self, in_channels, channels, stride=1, downsample=False):- super().__init__()- self.conv1 = conv3x3(in_channels, channels, stride)- self.bn1 = nn.BatchNorm2d(channels)- self.relu = nn.ReLU()- self.conv2 = conv3x3(channels, channels)- self.bn2 = nn.BatchNorm2d(channels)- self.downsample = downsample- if downsample:- self.downsample = nn.Sequential(- nn.Conv2d(- in_channels,- channels * self.expansion,- 1,- stride,- bias=False),- nn.BatchNorm2d(channels * self.expansion), )- else:- self.downsample = nn.Sequential()- 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:- residual = self.downsample(x)-- out += residual- out = self.relu(out)-- return out---class ResNet31(nn.Module):- '''- Args:- in_channels (int): Number of channels of input image tensor.- layers (list[int]): List of BasicBlock number for each stage.- channels (list[int]): List of out_channels of Conv2d layer.- out_indices (None | Sequence[int]): Indices of output stages.- last_stage_pool (bool): If True, add `MaxPool2d` layer to last stage.- '''-- def __init__(self,- in_channels=3,- layers=[1, 2, 5, 3],- channels=[64, 128, 256, 256, 512, 512, 512],- out_indices=None,- last_stage_pool=False):- super(ResNet31, self).__init__()- assert isinstance(in_channels, int)- assert isinstance(last_stage_pool, bool)-- self.out_indices = out_indices- self.last_stage_pool = last_stage_pool-- # conv 1 (Conv Conv)- self.conv1_1 = nn.Conv2d(- in_channels, channels[0], kernel_size=3, stride=1, padding=1)- self.bn1_1 = nn.BatchNorm2d(channels[0])- self.relu1_1 = nn.ReLU(inplace=True)-- self.conv1_2 = nn.Conv2d(- channels[0], channels[1], kernel_size=3, stride=1, padding=1)- self.bn1_2 = nn.BatchNorm2d(channels[1])- self.relu1_2 = nn.ReLU(inplace=True)-- # conv 2 (Max-pooling, Residual block, Conv)- self.pool2 = nn.MaxPool2d(- kernel_size=2, stride=2, padding=0, ceil_mode=True)- self.block2 = self._make_layer(channels[1], channels[2], layers[0])- self.conv2 = nn.Conv2d(- channels[2], channels[2], kernel_size=3, stride=1, padding=1)- self.bn2 = nn.BatchNorm2d(channels[2])- self.relu2 = nn.ReLU(inplace=True)-- # conv 3 (Max-pooling, Residual block, Conv)- self.pool3 = nn.MaxPool2d(- kernel_size=2, stride=2, padding=0, ceil_mode=True)- self.block3 = self._make_layer(channels[2], channels[3], layers[1])- self.conv3 = nn.Conv2d(- channels[3], channels[3], kernel_size=3, stride=1, padding=1)- self.bn3 = nn.BatchNorm2d(channels[3])- self.relu3 = nn.ReLU(inplace=True)-- # conv 4 (Max-pooling, Residual block, Conv)- self.pool4 = nn.MaxPool2d(- kernel_size=(2, 1), stride=(2, 1), padding=0, ceil_mode=True)- self.block4 = self._make_layer(channels[3], channels[4], layers[2])- self.conv4 = nn.Conv2d(- channels[4], channels[4], kernel_size=3, stride=1, padding=1)- self.bn4 = nn.BatchNorm2d(channels[4])- self.relu4 = nn.ReLU(inplace=True)-- # conv 5 ((Max-pooling), Residual block, Conv)- self.pool5 = None- if self.last_stage_pool:- self.pool5 = nn.MaxPool2d(- kernel_size=2, stride=2, padding=0, ceil_mode=True)- self.block5 = self._make_layer(channels[4], channels[5], layers[3])- self.conv5 = nn.Conv2d(- channels[5], channels[5], kernel_size=3, stride=1, padding=1)- self.bn5 = nn.BatchNorm2d(channels[5])- self.relu5 = nn.ReLU(inplace=True)-- self.out_channels = channels[-1]-- def _make_layer(self, input_channels, output_channels, blocks):- layers = []- for _ in range(blocks):- downsample = None- if input_channels != output_channels:- downsample = nn.Sequential(- nn.Conv2d(- input_channels,- output_channels,- kernel_size=1,- stride=1,- bias=False),- nn.BatchNorm2d(output_channels), )-- layers.append(- BasicBlock(- input_channels, output_channels, downsample=downsample))- input_channels = output_channels- return nn.Sequential(*layers)-- def forward(self, x):- x = self.conv1_1(x)- x = self.bn1_1(x)- x = self.relu1_1(x)-- x = self.conv1_2(x)- x = self.bn1_2(x)- x = self.relu1_2(x)-- outs = []- for i in range(4):- layer_index = i + 2- pool_layer = getattr(self, 'pool{}'.format(layer_index))- block_layer = getattr(self, 'block{}'.format(layer_index))- conv_layer = getattr(self, 'conv{}'.format(layer_index))- bn_layer = getattr(self, 'bn{}'.format(layer_index))- relu_layer = getattr(self, 'relu{}'.format(layer_index))-- if pool_layer is not None:- x = pool_layer(x)- x = block_layer(x)- x = conv_layer(x)- x = bn_layer(x)- x = relu_layer(x)-- outs.append(x)-- if self.out_indices is not None:- return tuple([outs[i] for i in self.out_indices])-- return x\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_resnet_fpn.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_resnet_fpn.pydeleted file mode 100755index e9bad7b7..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_resnet_fpn.py+++ /dev/null@@ -1,278 +0,0 @@-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import os, sys-import numpy as np-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation--__all__ = ["ResNetFPN"]--class ResNetFPN(nn.Module):- def __init__(self, in_channels=1, layers=50, **kwargs):- super(ResNetFPN, self).__init__()- supported_layers = {- 18: {- 'depth': [2, 2, 2, 2],- 'block_class': BasicBlock- },- 34: {- 'depth': [3, 4, 6, 3],- 'block_class': BasicBlock- },- 50: {- 'depth': [3, 4, 6, 3],- 'block_class': BottleneckBlock- },- 101: {- 'depth': [3, 4, 23, 3],- 'block_class': BottleneckBlock- },- 152: {- 'depth': [3, 8, 36, 3],- 'block_class': BottleneckBlock- }- }- stride_list = [(2, 2), (2, 2), (1, 1), (1, 1)]- num_filters = [64, 128, 256, 512]- self.depth = supported_layers[layers]['depth']- self.conv = ConvBNLayer(- in_channels=in_channels,- out_channels=64,- kernel_size=7,- stride=2,- act="relu",- name="conv1")- self.block_list = nn.ModuleList()- in_ch = 64- if layers >= 50:- for block in range(len(self.depth)):- for i in range(self.depth[block]):- if layers in [101, 152] and block == 2:- if i == 0:- conv_name = "res" + str(block + 2) + "a"- else:- conv_name = "res" + str(block + 2) + "b" + str(i)- else:- conv_name = "res" + str(block + 2) + chr(97 + i)-- bottlenectBlock = BottleneckBlock(- in_channels=in_ch,- out_channels=num_filters[block],- stride=stride_list[block] if i == 0 else 1,- name=conv_name)-- in_ch = num_filters[block] * 4- self.block_list.add_module("bottleneckBlock_{}_{}".format(block, i), bottlenectBlock)-- else:- for block in range(len(self.depth)):- for i in range(self.depth[block]):- conv_name = "res" + str(block + 2) + chr(97 + i)- if i == 0 and block != 0:- stride = (2, 1)- else:- stride = (1, 1)-- basicBlock = BasicBlock(- in_channels=in_ch,- out_channels=num_filters[block],- stride=stride_list[block] if i == 0 else 1,- is_first=block == i == 0,- name=conv_name)- in_ch = basicBlock.out_channels- self.block_list.add_module(conv_name, basicBlock)- out_ch_list = [in_ch // 4, in_ch // 2, in_ch]- self.base_block = nn.ModuleList()- self.conv_trans = []- self.bn_block = []- for i in [-2, -3]:- in_channels = out_ch_list[i + 1] + out_ch_list[i]- bb_0 = nn.Conv2d(- in_channels=in_channels,- out_channels=out_ch_list[i],- kernel_size=1,- bias=True)- self.base_block.add_module("F_{}_base_block_0".format(i), bb_0)- bb_1 = nn.Conv2d(- in_channels=out_ch_list[i],- out_channels=out_ch_list[i],- kernel_size=3,- padding=1,- bias=True)- self.base_block.add_module("F_{}_base_block_1".format(i), bb_1)- bb_2 = nn.Sequential(- nn.BatchNorm2d(out_ch_list[i]),- Activation("relu")- )- self.base_block.add_module("F_{}_base_block_2".format(i), bb_2)-- bb_3 = nn.Conv2d(- in_channels=out_ch_list[i],- out_channels=512,- kernel_size=1,- bias=True)- self.base_block.add_module("F_{}_base_block_3".format(i), bb_3)- self.out_channels = 512-- def __call__(self, x):- x = self.conv(x)- fpn_list = []- F = []- for i in range(len(self.depth)):- fpn_list.append(np.sum(self.depth[:i + 1]))-- for i, block in enumerate(self.block_list):- x = block(x)- for number in fpn_list:- if i + 1 == number:- F.append(x)- base = F[-1]-- j = 0- for i, block in enumerate(self.base_block):- if i % 3 == 0 and i < 6:- j = j + 1- b, c, w, h = F[-j - 1].shape- if [w, h] == list(base.shape[2:]):- base = base- else:- base = self.conv_trans[j - 1](base)- base = self.bn_block[j - 1](base)- base = torch.cat([base, F[-j - 1]], dim=1)- base = block(base)- return base---class ConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride=1,- groups=1,- act=None,- name=None):- super(ConvBNLayer, self).__init__()- self.conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=2 if stride == (1, 1) else kernel_size,- dilation=2 if stride == (1, 1) else 1,- stride=stride,- padding=(kernel_size - 1) // 2,- groups=groups,- bias=False, )-- if name == "conv1":- bn_name = "bn_" + name- else:- bn_name = "bn" + name[3:]-- self.bn = nn.BatchNorm2d(out_channels)- self.act = act- if self.act is not None:- self._act = Activation(act_type=self.act, inplace=True)-- def __call__(self, x):- x = self.conv(x)- x = self.bn(x)- if self.act is not None:- x = self._act(x)- return x---class ShortCut(nn.Module):- def __init__(self, in_channels, out_channels, stride, name, is_first=False):- super(ShortCut, self).__init__()- self.use_conv = True-- if in_channels != out_channels or stride != 1 or is_first == True:- if stride == (1, 1):- self.conv = ConvBNLayer(- in_channels, out_channels, 1, 1, name=name)- else: # stride==(2,2)- self.conv = ConvBNLayer(- in_channels, out_channels, 1, stride, name=name)- else:- self.use_conv = False-- def forward(self, x):- if self.use_conv:- x = self.conv(x)- return x---class BottleneckBlock(nn.Module):- def __init__(self, in_channels, out_channels, stride, name):- super(BottleneckBlock, self).__init__()- self.conv0 = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=1,- act='relu',- name=name + "_branch2a")- self.conv1 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels,- kernel_size=3,- stride=stride,- act='relu',- name=name + "_branch2b")-- self.conv2 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels * 4,- kernel_size=1,- act=None,- name=name + "_branch2c")-- self.short = ShortCut(- in_channels=in_channels,- out_channels=out_channels * 4,- stride=stride,- is_first=False,- name=name + "_branch1")- self.out_channels = out_channels * 4-- def forward(self, x):- y = self.conv0(x)- y = self.conv1(y)- y = self.conv2(y)- y = y + self.short(x)- y = F.relu(y)- return y---class BasicBlock(nn.Module):- def __init__(self, in_channels, out_channels, stride, name, is_first):- super(BasicBlock, self).__init__()- self.conv0 = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=3,- act='relu',- stride=stride,- name=name + "_branch2a")- self.conv1 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels,- kernel_size=3,- act=None,- name=name + "_branch2b")- self.short = ShortCut(- in_channels=in_channels,- out_channels=out_channels,- stride=stride,- is_first=is_first,- name=name + "_branch1")- self.out_channels = out_channels-- def forward(self, x):- y = self.conv0(x)- y = self.conv1(y)- y = y + self.short(x)- return F.relu(y)diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_resnet_vd.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_resnet_vd.pydeleted file mode 100755index b8a2ed34..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_resnet_vd.py+++ /dev/null@@ -1,260 +0,0 @@-import os, sys-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation--class ConvBNLayer(nn.Module):- def __init__(- self,- in_channels,- out_channels,- kernel_size,- stride=1,- groups=1,- is_vd_mode=False,- act=None,- name=None, ):- super(ConvBNLayer, self).__init__()- self.act = act- self.is_vd_mode = is_vd_mode- self._pool2d_avg = nn.AvgPool2d(- kernel_size=stride, stride=stride, padding=0, ceil_mode=True)-- self._conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=1 if is_vd_mode else stride,- padding=(kernel_size - 1) // 2,- groups=groups,- bias=False)-- self._batch_norm = nn.BatchNorm2d(- out_channels,)- if self.act is not None:- self._act = Activation(act_type=act, inplace=True)-- def forward(self, inputs):- if self.is_vd_mode:- inputs = self._pool2d_avg(inputs)- y = self._conv(inputs)- y = self._batch_norm(y)- if self.act is not None:- y = self._act(y)- return y---class BottleneckBlock(nn.Module):- def __init__(self,- in_channels,- out_channels,- stride,- shortcut=True,- if_first=False,- name=None):- super(BottleneckBlock, self).__init__()-- self.conv0 = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=1,- act='relu',- name=name + "_branch2a")- self.conv1 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels,- kernel_size=3,- stride=stride,- act='relu',- name=name + "_branch2b")- self.conv2 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels * 4,- kernel_size=1,- act=None,- name=name + "_branch2c")-- if not shortcut:- self.short = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels * 4,- kernel_size=1,- stride=stride,- is_vd_mode=not if_first and stride[0] != 1,- name=name + "_branch1")-- self.shortcut = shortcut-- def forward(self, inputs):- y = self.conv0(inputs)-- conv1 = self.conv1(y)- conv2 = self.conv2(conv1)-- if self.shortcut:- short = inputs- else:- short = self.short(inputs)- y = short + conv2- y = F.relu(y)- return y---class BasicBlock(nn.Module):- def __init__(self,- in_channels,- out_channels,- stride,- shortcut=True,- if_first=False,- name=None):- super(BasicBlock, self).__init__()- self.stride = stride- self.conv0 = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=3,- stride=stride,- act='relu',- name=name + "_branch2a")- self.conv1 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels,- kernel_size=3,- act=None,- name=name + "_branch2b")-- if not shortcut:- self.short = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=1,- stride=stride,- is_vd_mode=not if_first and stride[0] != 1,- name=name + "_branch1")-- self.shortcut = shortcut-- def forward(self, inputs):- y = self.conv0(inputs)- conv1 = self.conv1(y)-- if self.shortcut:- short = inputs- else:- short = self.short(inputs)- y = short + conv1- y = F.relu(y)- return y---class ResNet(nn.Module):- def __init__(self, in_channels=3, layers=50, **kwargs):- super(ResNet, self).__init__()-- self.layers = layers- supported_layers = [18, 34, 50, 101, 152, 200]- assert layers in supported_layers, \- "supported layers are {} but input layer is {}".format(- supported_layers, layers)-- if layers == 18:- depth = [2, 2, 2, 2]- elif layers == 34 or layers == 50:- depth = [3, 4, 6, 3]- elif layers == 101:- depth = [3, 4, 23, 3]- elif layers == 152:- depth = [3, 8, 36, 3]- elif layers == 200:- depth = [3, 12, 48, 3]- num_channels = [64, 256, 512,- 1024] if layers >= 50 else [64, 64, 128, 256]- num_filters = [64, 128, 256, 512]-- self.conv1_1 = ConvBNLayer(- in_channels=in_channels,- out_channels=32,- kernel_size=3,- stride=1,- act='relu',- name="conv1_1")- self.conv1_2 = ConvBNLayer(- in_channels=32,- out_channels=32,- kernel_size=3,- stride=1,- act='relu',- name="conv1_2")- self.conv1_3 = ConvBNLayer(- in_channels=32,- out_channels=64,- kernel_size=3,- stride=1,- act='relu',- name="conv1_3")- self.pool2d_max = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)-- # self.block_list = list()- self.block_list = nn.Sequential()- if layers >= 50:- for block in range(len(depth)):- shortcut = False- for i in range(depth[block]):- if layers in [101, 152, 200] and block == 2:- if i == 0:- conv_name = "res" + str(block + 2) + "a"- else:- conv_name = "res" + str(block + 2) + "b" + str(i)- else:- conv_name = "res" + str(block + 2) + chr(97 + i)-- if i == 0 and block != 0:- stride = (2, 1)- else:- stride = (1, 1)-- bottleneck_block = BottleneckBlock(in_channels=num_channels[block] if i == 0 else num_filters[block] * 4,- out_channels=num_filters[block],- stride=stride,- shortcut=shortcut,- if_first=block == i == 0,- name=conv_name)- shortcut = True- # self.block_list.append(bottleneck_block)- self.block_list.add_module('bb_%d_%d' % (block, i), bottleneck_block)- self.out_channels = num_filters[block]- else:- for block in range(len(depth)):- shortcut = False- for i in range(depth[block]):- conv_name = "res" + str(block + 2) + chr(97 + i)- if i == 0 and block != 0:- stride = (2, 1)- else:- stride = (1, 1)-- basic_block = BasicBlock(in_channels=num_channels[block] if i == 0 else num_filters[block],- out_channels=num_filters[block],- stride=stride,- shortcut=shortcut,- if_first=block == i == 0,- name=conv_name)-- shortcut = True- # self.block_list.append(basic_block)- self.block_list.add_module('bb_%d_%d' % (block, i), basic_block)- self.out_channels = num_filters[block]- self.out_pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)-- def forward(self, inputs):- y = self.conv1_1(inputs)- y = self.conv1_2(y)- y = self.conv1_3(y)- y = self.pool2d_max(y)- for block in self.block_list:- y = block(y)- y = self.out_pool(y)-- return y\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_svtrnet.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_svtrnet.pyold mode 100755new mode 100644index 1ba3d4f2..3a117736--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_svtrnet.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_svtrnet.py@@ -1,17 +1,19 @@-import torch-import torch.nn as nn-from pytorchocr.modeling.common import Activationimport numpy as np+import torch+from torch import nn++from ..common import Activation-def drop_path(x, drop_prob=0., training=False):++def drop_path(x, drop_prob=0.0, training=False):"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ..."""- if drop_prob == 0. or not training:+ if drop_prob == 0.0 or not training:return xkeep_prob = torch.as_tensor(1 - drop_prob)- shape = (x.shape[0], ) + (1, ) * (x.ndim - 1)+ shape = (x.shape[0],) + (1,) * (x.ndim - 1)random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype)random_tensor = torch.floor(random_tensor) # binarizeoutput = x.divide(keep_prob) * random_tensor@@ -19,15 +21,17 @@ def drop_path(x, drop_prob=0., training=False):class ConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size=3,- stride=1,- padding=0,- bias_attr=False,- groups=1,- act='gelu'):+ def __init__(+ self,+ in_channels,+ out_channels,+ kernel_size=3,+ stride=1,+ padding=0,+ bias_attr=False,+ groups=1,+ act="gelu",+ ):super().__init__()self.conv = nn.Conv2d(in_channels=in_channels,@@ -36,7 +40,8 @@ class ConvBNLayer(nn.Module):stride=stride,padding=padding,groups=groups,- bias=bias_attr)+ bias=bias_attr,+ )self.norm = nn.BatchNorm2d(out_channels)self.act = Activation(act_type=act, inplace=True)@@ -48,8 +53,7 @@ class ConvBNLayer(nn.Module):class DropPath(nn.Module):- """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).- """+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""def __init__(self, drop_prob=None):super(DropPath, self).__init__()@@ -68,12 +72,14 @@ class Identity(nn.Module):class Mlp(nn.Module):- def __init__(self,- in_features,- hidden_features=None,- out_features=None,- act_layer='gelu',- drop=0.):+ def __init__(+ self,+ in_features,+ hidden_features=None,+ out_features=None,+ act_layer="gelu",+ drop=0.0,+ ):super().__init__()out_features = out_features or in_featureshidden_features = hidden_features or in_features@@ -93,11 +99,12 @@ class Mlp(nn.Module):class ConvMixer(nn.Module):def __init__(- self,- dim,- num_heads=8,- HW=[8, 25],- local_k=[3, 3], ):+ self,+ dim,+ num_heads=8,+ HW=[8, 25],+ local_k=[3, 3],+ ):super().__init__()self.HW = HWself.dim = dim@@ -105,9 +112,10 @@ class ConvMixer(nn.Module):dim,dim,local_k,- 1, [local_k[0] // 2, local_k[1] // 2],+ 1,+ [local_k[0] // 2, local_k[1] // 2],groups=num_heads,- )+ )def forward(self, x):h = self.HW[0]@@ -119,16 +127,18 @@ class ConvMixer(nn.Module):class Attention(nn.Module):- def __init__(self,- dim,- num_heads=8,- mixer='Global',- HW=[8, 25],- local_k=[7, 11],- qkv_bias=False,- qk_scale=None,- attn_drop=0.,- proj_drop=0.):+ def __init__(+ self,+ dim,+ num_heads=8,+ mixer="Global",+ HW=[8, 25],+ local_k=[7, 11],+ qkv_bias=False,+ qk_scale=None,+ attn_drop=0.0,+ proj_drop=0.0,+ ):super().__init__()self.num_heads = num_headshead_dim = dim // num_heads@@ -143,16 +153,19 @@ class Attention(nn.Module):W = HW[1]self.N = H * Wself.C = dim- if mixer == 'Local' and HW is not None:+ if mixer == "Local" and HW is not None:hk = local_k[0]wk = local_k[1]mask = torch.ones(H * W, H + hk - 1, W + wk - 1, dtype=torch.float32)for h in range(0, H):for w in range(0, W):- mask[h * W + w, h:h + hk, w:w + wk] = 0.- mask_paddle = mask[:, hk // 2:H + hk // 2, wk // 2:W + wk //- 2].flatten(1)- mask_inf = torch.full([H * W, H * W], fill_value=float("-Inf"), dtype=torch.float32)+ mask[h * W + w, h : h + hk, w : w + wk] = 0.0+ mask_paddle = mask[:, hk // 2 : H + hk // 2, wk // 2 : W + wk // 2].flatten(+ 1+ )+ mask_inf = torch.full(+ [H * W, H * W], fill_value=float("-Inf"), dtype=torch.float32+ )mask = torch.where(mask_paddle < 1, mask_paddle, mask_inf)self.mask = mask.unsqueeze(0).unsqueeze(1)# self.mask = mask[None, None, :]@@ -165,11 +178,13 @@ class Attention(nn.Module):else:_, N, C = x.shapeqkv = self.qkv(x)- qkv = qkv.reshape((-1, N, 3, self.num_heads, C // self.num_heads)).permute(2, 0, 3, 1, 4)+ qkv = qkv.reshape((-1, N, 3, self.num_heads, C // self.num_heads)).permute(+ 2, 0, 3, 1, 4+ )q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]- attn = (q.matmul(k.permute(0, 1, 3, 2)))- if self.mixer == 'Local':+ attn = q.matmul(k.permute(0, 1, 3, 2))+ if self.mixer == "Local":attn += self.maskattn = nn.functional.softmax(attn, dim=-1)attn = self.attn_drop(attn)@@ -181,28 +196,30 @@ class Attention(nn.Module):class Block(nn.Module):- def __init__(self,- dim,- num_heads,- mixer='Global',- local_mixer=[7, 11],- HW=None,- mlp_ratio=4.,- qkv_bias=False,- qk_scale=None,- drop=0.,- attn_drop=0.,- drop_path=0.,- act_layer='gelu',- norm_layer='nn.LayerNorm',- epsilon=1e-6,- prenorm=True):+ def __init__(+ self,+ dim,+ num_heads,+ mixer="Global",+ local_mixer=[7, 11],+ HW=None,+ mlp_ratio=4.0,+ qkv_bias=False,+ qk_scale=None,+ drop=0.0,+ attn_drop=0.0,+ drop_path=0.0,+ act_layer="gelu",+ norm_layer="nn.LayerNorm",+ epsilon=1e-6,+ prenorm=True,+ ):super().__init__()if isinstance(norm_layer, str):self.norm1 = eval(norm_layer)(dim, eps=epsilon)else:self.norm1 = norm_layer(dim)- if mixer == 'Global' or mixer == 'Local':+ if mixer == "Global" or mixer == "Local":self.mixer = Attention(dim,num_heads=num_heads,@@ -212,24 +229,26 @@ class Block(nn.Module):qkv_bias=qkv_bias,qk_scale=qk_scale,attn_drop=attn_drop,- proj_drop=drop)- elif mixer == 'Conv':- self.mixer = ConvMixer(- dim, num_heads=num_heads, HW=HW, local_k=local_mixer)+ proj_drop=drop,+ )+ elif mixer == "Conv":+ self.mixer = ConvMixer(dim, num_heads=num_heads, HW=HW, local_k=local_mixer)else:raise TypeError("The mixer must be one of [Global, Local, Conv]")- self.drop_path = DropPath(drop_path) if drop_path > 0. else Identity()+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else Identity()if isinstance(norm_layer, str):self.norm2 = eval(norm_layer)(dim, eps=epsilon)else:self.norm2 = norm_layer(dim)mlp_hidden_dim = int(dim * mlp_ratio)self.mlp_ratio = mlp_ratio- self.mlp = Mlp(in_features=dim,- hidden_features=mlp_hidden_dim,- act_layer=act_layer,- drop=drop)+ self.mlp = Mlp(+ in_features=dim,+ hidden_features=mlp_hidden_dim,+ act_layer=act_layer,+ drop=drop,+ )self.prenorm = prenormdef forward(self, x):@@ -243,25 +262,24 @@ class Block(nn.Module):class PatchEmbed(nn.Module):- """ Image to Patch Embedding- """+ """Image to Patch Embedding"""- def __init__(self,- img_size=[32, 100],- in_channels=3,- embed_dim=768,- sub_num=2,- patch_size=[4, 4],- mode='pope',- ):+ def __init__(+ self,+ img_size=[32, 100],+ in_channels=3,+ embed_dim=768,+ sub_num=2,+ patch_size=[4, 4],+ mode="pope",+ ):super().__init__()- num_patches = (img_size[1] // (2 ** sub_num)) * \- (img_size[0] // (2 ** sub_num))+ num_patches = (img_size[1] // (2**sub_num)) * (img_size[0] // (2**sub_num))self.img_size = img_sizeself.num_patches = num_patchesself.embed_dim = embed_dimself.norm = None- if mode == 'pope':+ if mode == "pope":if sub_num == 2:self.proj = nn.Sequential(ConvBNLayer(@@ -270,16 +288,19 @@ class PatchEmbed(nn.Module):kernel_size=3,stride=2,padding=1,- act='gelu',- bias_attr=True),+ act="gelu",+ bias_attr=True,+ ),ConvBNLayer(in_channels=embed_dim // 2,out_channels=embed_dim,kernel_size=3,stride=2,padding=1,- act='gelu',- bias_attr=True))+ act="gelu",+ bias_attr=True,+ ),+ )if sub_num == 3:self.proj = nn.Sequential(ConvBNLayer(@@ -288,55 +309,66 @@ class PatchEmbed(nn.Module):kernel_size=3,stride=2,padding=1,- act='gelu',- bias_attr=True),+ act="gelu",+ bias_attr=True,+ ),ConvBNLayer(in_channels=embed_dim // 4,out_channels=embed_dim // 2,kernel_size=3,stride=2,padding=1,- act='gelu',- bias_attr=True),+ act="gelu",+ bias_attr=True,+ ),ConvBNLayer(in_channels=embed_dim // 2,out_channels=embed_dim,kernel_size=3,stride=2,padding=1,- act='gelu',- bias_attr=True))- elif mode == 'linear':+ act="gelu",+ bias_attr=True,+ ),+ )+ elif mode == "linear":self.proj = nn.Conv2d(- 1, embed_dim, kernel_size=patch_size, stride=patch_size)- self.num_patches = img_size[0] // patch_size[0] * img_size[- 1] // patch_size[1]+ 1, embed_dim, kernel_size=patch_size, stride=patch_size+ )+ self.num_patches = (+ img_size[0] // patch_size[0] * img_size[1] // patch_size[1]+ )def forward(self, x):B, C, H, W = x.shape- assert H == self.img_size[0] and W == self.img_size[1], \- "Input image size ({}*{}) doesn't match model ({}*{}).".format(- H,W,self.img_size[0],self.img_size[1]- )+ assert (+ H == self.img_size[0] and W == self.img_size[1]+ ), "Input image size ({}*{}) doesn't match model ({}*{}).".format(+ H, W, self.img_size[0], self.img_size[1]+ )x = self.proj(x).flatten(2).permute(0, 2, 1)return xclass SubSample(nn.Module):- def __init__(self,- in_channels,- out_channels,- types='Pool',- stride=[2, 1],- sub_norm='nn.LayerNorm',- act=None):+ def __init__(+ self,+ in_channels,+ out_channels,+ types="Pool",+ stride=[2, 1],+ sub_norm="nn.LayerNorm",+ act=None,+ ):super().__init__()self.types = types- if types == 'Pool':+ if types == "Pool":self.avgpool = nn.AvgPool2d(- kernel_size=[3, 5], stride=stride, padding=[1, 2])+ kernel_size=[3, 5], stride=stride, padding=[1, 2]+ )self.maxpool = nn.MaxPool2d(- kernel_size=[3, 5], stride=stride, padding=[1, 2])+ kernel_size=[3, 5], stride=stride, padding=[1, 2]+ )self.proj = nn.Linear(in_channels, out_channels)else:self.conv = nn.Conv2d(@@ -345,7 +377,7 @@ class SubSample(nn.Module):kernel_size=3,stride=stride,padding=1,- )+ )self.norm = eval(sub_norm)(out_channels)if act is not None:self.act = act()@@ -353,8 +385,7 @@ class SubSample(nn.Module):self.act = Nonedef forward(self, x):-- if self.types == 'Pool':+ if self.types == "Pool":x1 = self.avgpool(x)x2 = self.maxpool(x)x = (x1 + x2) * 0.5@@ -371,46 +402,51 @@ class SubSample(nn.Module):class SVTRNet(nn.Module):def __init__(- self,- img_size=[32, 100],- in_channels=3,- embed_dim=[64, 128, 256],- depth=[3, 6, 3],- num_heads=[2, 4, 8],- mixer=['Local'] * 6 + ['Global'] *- 6, # Local atten, Global atten, Conv- local_mixer=[[7, 11], [7, 11], [7, 11]],- patch_merging='Conv', # Conv, Pool, None- mlp_ratio=4,- qkv_bias=True,- qk_scale=None,- drop_rate=0.,- last_drop=0.0,- attn_drop_rate=0.,- drop_path_rate=0.1,- norm_layer='nn.LayerNorm',- sub_norm='nn.LayerNorm',- epsilon=1e-6,- out_channels=192,- out_char_num=25,- block_unit='Block',- act='gelu',- last_stage=True,- sub_num=2,- prenorm=True,- use_lenhead=False,- **kwargs):+ self,+ img_size=[32, 100],+ in_channels=3,+ embed_dim=[64, 128, 256],+ depth=[3, 6, 3],+ num_heads=[2, 4, 8],+ mixer=["Local"] * 6 + ["Global"] * 6, # Local atten, Global atten, Conv+ local_mixer=[[7, 11], [7, 11], [7, 11]],+ patch_merging="Conv", # Conv, Pool, None+ mlp_ratio=4,+ qkv_bias=True,+ qk_scale=None,+ drop_rate=0.0,+ last_drop=0.0,+ attn_drop_rate=0.0,+ drop_path_rate=0.1,+ norm_layer="nn.LayerNorm",+ sub_norm="nn.LayerNorm",+ epsilon=1e-6,+ out_channels=192,+ out_char_num=25,+ block_unit="Block",+ act="gelu",+ last_stage=True,+ sub_num=2,+ prenorm=True,+ use_lenhead=False,+ **kwargs+ ):super().__init__()self.img_size = img_sizeself.embed_dim = embed_dimself.out_channels = out_channelsself.prenorm = prenorm- patch_merging = None if patch_merging != 'Conv' and patch_merging != 'Pool' else patch_merging+ patch_merging = (+ None+ if patch_merging != "Conv" and patch_merging != "Pool"+ else patch_merging+ )self.patch_embed = PatchEmbed(img_size=img_size,in_channels=in_channels,embed_dim=embed_dim[0],- sub_num=sub_num)+ sub_num=sub_num,+ )num_patches = self.patch_embed.num_patchesself.HW = [img_size[0] // (2**sub_num), img_size[1] // (2**sub_num)]self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim[0]))@@ -418,81 +454,95 @@ class SVTRNet(nn.Module):Block_unit = eval(block_unit)dpr = np.linspace(0, drop_path_rate, sum(depth))- self.blocks1 = nn.ModuleList([- Block_unit(- dim=embed_dim[0],- num_heads=num_heads[0],- mixer=mixer[0:depth[0]][i],- HW=self.HW,- local_mixer=local_mixer[0],- mlp_ratio=mlp_ratio,- qkv_bias=qkv_bias,- qk_scale=qk_scale,- drop=drop_rate,- act_layer=act,- attn_drop=attn_drop_rate,- drop_path=dpr[0:depth[0]][i],- norm_layer=norm_layer,- epsilon=epsilon,- prenorm=prenorm) for i in range(depth[0])- ])+ self.blocks1 = nn.ModuleList(+ [+ Block_unit(+ dim=embed_dim[0],+ num_heads=num_heads[0],+ mixer=mixer[0 : depth[0]][i],+ HW=self.HW,+ local_mixer=local_mixer[0],+ mlp_ratio=mlp_ratio,+ qkv_bias=qkv_bias,+ qk_scale=qk_scale,+ drop=drop_rate,+ act_layer=act,+ attn_drop=attn_drop_rate,+ drop_path=dpr[0 : depth[0]][i],+ norm_layer=norm_layer,+ epsilon=epsilon,+ prenorm=prenorm,+ )+ for i in range(depth[0])+ ]+ )if patch_merging is not None:self.sub_sample1 = SubSample(embed_dim[0],embed_dim[1],sub_norm=sub_norm,stride=[2, 1],- types=patch_merging)+ types=patch_merging,+ )HW = [self.HW[0] // 2, self.HW[1]]else:HW = self.HWself.patch_merging = patch_merging- self.blocks2 = nn.ModuleList([- Block_unit(- dim=embed_dim[1],- num_heads=num_heads[1],- mixer=mixer[depth[0]:depth[0] + depth[1]][i],- HW=HW,- local_mixer=local_mixer[1],- mlp_ratio=mlp_ratio,- qkv_bias=qkv_bias,- qk_scale=qk_scale,- drop=drop_rate,- act_layer=act,- attn_drop=attn_drop_rate,- drop_path=dpr[depth[0]:depth[0] + depth[1]][i],- norm_layer=norm_layer,- epsilon=epsilon,- prenorm=prenorm) for i in range(depth[1])- ])+ self.blocks2 = nn.ModuleList(+ [+ Block_unit(+ dim=embed_dim[1],+ num_heads=num_heads[1],+ mixer=mixer[depth[0] : depth[0] + depth[1]][i],+ HW=HW,+ local_mixer=local_mixer[1],+ mlp_ratio=mlp_ratio,+ qkv_bias=qkv_bias,+ qk_scale=qk_scale,+ drop=drop_rate,+ act_layer=act,+ attn_drop=attn_drop_rate,+ drop_path=dpr[depth[0] : depth[0] + depth[1]][i],+ norm_layer=norm_layer,+ epsilon=epsilon,+ prenorm=prenorm,+ )+ for i in range(depth[1])+ ]+ )if patch_merging is not None:self.sub_sample2 = SubSample(embed_dim[1],embed_dim[2],sub_norm=sub_norm,stride=[2, 1],- types=patch_merging)+ types=patch_merging,+ )HW = [self.HW[0] // 4, self.HW[1]]else:HW = self.HW- self.blocks3 = nn.ModuleList([- Block_unit(- dim=embed_dim[2],- num_heads=num_heads[2],- mixer=mixer[depth[0] + depth[1]:][i],- HW=HW,- local_mixer=local_mixer[2],- mlp_ratio=mlp_ratio,- qkv_bias=qkv_bias,- qk_scale=qk_scale,- drop=drop_rate,- act_layer=act,- attn_drop=attn_drop_rate,- drop_path=dpr[depth[0] + depth[1]:][i],- norm_layer=norm_layer,- epsilon=epsilon,- prenorm=prenorm) for i in range(depth[2])- ])+ self.blocks3 = nn.ModuleList(+ [+ Block_unit(+ dim=embed_dim[2],+ num_heads=num_heads[2],+ mixer=mixer[depth[0] + depth[1] :][i],+ HW=HW,+ local_mixer=local_mixer[2],+ mlp_ratio=mlp_ratio,+ qkv_bias=qkv_bias,+ qk_scale=qk_scale,+ drop=drop_rate,+ act_layer=act,+ attn_drop=attn_drop_rate,+ drop_path=dpr[depth[0] + depth[1] :][i],+ norm_layer=norm_layer,+ epsilon=epsilon,+ prenorm=prenorm,+ )+ for i in range(depth[2])+ ]+ )self.last_stage = last_stageif last_stage:self.avg_pool = nn.AdaptiveAvgPool2d([1, out_char_num])@@ -502,8 +552,9 @@ class SVTRNet(nn.Module):kernel_size=1,stride=1,padding=0,- bias=False)- self.hardswish = Activation('hard_swish', inplace=True) #nn.Hardswish()+ bias=False,+ )+ self.hardswish = Activation("hard_swish", inplace=True) # nn.Hardswish()# self.dropout = nn.Dropout(p=last_drop, mode="downscale_in_infer")self.dropout = nn.Dropout(p=last_drop)if not prenorm:@@ -511,9 +562,10 @@ class SVTRNet(nn.Module):self.use_lenhead = use_lenheadif use_lenhead:self.len_conv = nn.Linear(embed_dim[2], self.out_channels)- self.hardswish_len = Activation('hard_swish', inplace=True)# nn.Hardswish()- self.dropout_len = nn.Dropout(- p=last_drop)+ self.hardswish_len = Activation(+ "hard_swish", inplace=True+ ) # nn.Hardswish()+ self.dropout_len = nn.Dropout(p=last_drop)torch.nn.init.xavier_normal_(self.pos_embed)self.apply(self._init_weights)@@ -521,7 +573,7 @@ class SVTRNet(nn.Module):def _init_weights(self, m):# weight initializationif isinstance(m, nn.Conv2d):- nn.init.kaiming_normal_(m.weight, mode='fan_out')+ nn.init.kaiming_normal_(m.weight, mode="fan_out")if m.bias is not None:nn.init.zeros_(m.bias)elif isinstance(m, nn.BatchNorm2d):@@ -532,7 +584,7 @@ class SVTRNet(nn.Module):if m.bias is not None:nn.init.zeros_(m.bias)elif isinstance(m, nn.ConvTranspose2d):- nn.init.kaiming_normal_(m.weight, mode='fan_out')+ nn.init.kaiming_normal_(m.weight, mode="fan_out")if m.bias is not None:nn.init.zeros_(m.bias)elif isinstance(m, nn.LayerNorm):@@ -548,13 +600,17 @@ class SVTRNet(nn.Module):if self.patch_merging is not None:x = self.sub_sample1(x.permute(0, 2, 1).reshape(- [-1, self.embed_dim[0], self.HW[0], self.HW[1]]))+ [-1, self.embed_dim[0], self.HW[0], self.HW[1]]+ )+ )for blk in self.blocks2:x = blk(x)if self.patch_merging is not None:x = self.sub_sample2(x.permute(0, 2, 1).reshape(- [-1, self.embed_dim[1], self.HW[0] // 2, self.HW[1]]))+ [-1, self.embed_dim[1], self.HW[0] // 2, self.HW[1]]+ )+ )for blk in self.blocks3:x = blk(x)if not self.prenorm:@@ -572,11 +628,11 @@ class SVTRNet(nn.Module):else:h = self.HW[0]x = self.avg_pool(- x.permute(0, 2, 1).reshape(- [-1, self.embed_dim[2], h, self.HW[1]]))+ x.permute(0, 2, 1).reshape([-1, self.embed_dim[2], h, self.HW[1]])+ )x = self.last_conv(x)x = self.hardswish(x)x = self.dropout(x)if self.use_lenhead:return x, len_x- return x\ No newline at end of file+ return xdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_vitstr.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_vitstr.pydeleted file mode 100755index 1e225013..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_vitstr.py+++ /dev/null@@ -1,120 +0,0 @@-"""-This code is refer from:-https://github.com/roatienza/deep-text-recognition-benchmark/blob/master/modules/vitstr.py-"""--import numpy as np-import torch-import torch.nn as nn-from pytorchocr.modeling.backbones.rec_svtrnet import Block, PatchEmbed--# import paddle-# import paddle.nn as nn-# from ppocr.modeling.backbones.rec_svtrnet import Block, PatchEmbed, zeros_, trunc_normal_, ones_--scale_dim_heads = {'tiny': [192, 3], 'small': [384, 6], 'base': [768, 12]}---class ViTSTR(nn.Module):- def __init__(self,- img_size=[224, 224],- in_channels=1,- scale='tiny',- seqlen=27,- patch_size=[16, 16],- embed_dim=None,- depth=12,- num_heads=None,- mlp_ratio=4,- qkv_bias=True,- qk_scale=None,- drop_path_rate=0.,- drop_rate=0.,- attn_drop_rate=0.,- norm_layer='nn.LayerNorm',- act_layer='gelu',- epsilon=1e-6,- out_channels=None,- **kwargs):- super().__init__()- self.seqlen = seqlen- embed_dim = embed_dim if embed_dim is not None else scale_dim_heads[- scale][0]- num_heads = num_heads if num_heads is not None else scale_dim_heads[- scale][1]- out_channels = out_channels if out_channels is not None else embed_dim- self.patch_embed = PatchEmbed(- img_size=img_size,- in_channels=in_channels,- embed_dim=embed_dim,- patch_size=patch_size,- mode='linear')- num_patches = self.patch_embed.num_patches-- self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))- self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))-- self.pos_drop = nn.Dropout(p=drop_rate)-- dpr = np.linspace(0, drop_path_rate, depth)- self.blocks = nn.ModuleList([- Block(- dim=embed_dim,- num_heads=num_heads,- mlp_ratio=mlp_ratio,- qkv_bias=qkv_bias,- qk_scale=qk_scale,- drop=drop_rate,- attn_drop=attn_drop_rate,- drop_path=dpr[i],- norm_layer=norm_layer,- act_layer=act_layer,- epsilon=epsilon,- prenorm=False) for i in range(depth)- ])- self.norm = eval(norm_layer)(embed_dim, eps=epsilon)-- self.out_channels = out_channels-- torch.nn.init.xavier_normal_(self.pos_embed)- torch.nn.init.xavier_normal_(self.cls_token)- self.apply(self._init_weights)-- def _init_weights(self, m):- # weight initialization- if isinstance(m, nn.Conv2d):- nn.init.kaiming_normal_(m.weight, mode='fan_out')- if m.bias is not None:- nn.init.zeros_(m.bias)- elif isinstance(m, nn.BatchNorm2d):- nn.init.ones_(m.weight)- nn.init.zeros_(m.bias)- elif isinstance(m, nn.Linear):- nn.init.normal_(m.weight, 0, 0.01)- if m.bias is not None:- nn.init.zeros_(m.bias)- elif isinstance(m, nn.ConvTranspose2d):- nn.init.kaiming_normal_(m.weight, mode='fan_out')- if m.bias is not None:- nn.init.zeros_(m.bias)- elif isinstance(m, nn.LayerNorm):- nn.init.ones_(m.weight)- nn.init.zeros_(m.bias)-- def forward_features(self, x):- B = x.shape[0]- x = self.patch_embed(x)- # cls_tokens = paddle.tile(self.cls_token, repeat_times=[B, 1, 1])- cls_tokens = self.cls_token.repeat(B, 1, 1)- x = torch.cat((cls_tokens, x), dim=1)- x = x + self.pos_embed- x = self.pos_drop(x)- for blk in self.blocks:- x = blk(x)- x = self.norm(x)- return x-- def forward(self, x):- x = self.forward_features(x)- x = x[:, :self.seqlen]- return x.permute(0, 2, 1).unsqueeze(2)diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/table_mobilenet_v3.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/table_mobilenet_v3.pydeleted file mode 100755index fa61e059..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/table_mobilenet_v3.py+++ /dev/null@@ -1,270 +0,0 @@-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import torch-import torch.nn as nn-import torch.nn.functional as F--__all__ = ['MobileNetV3']---def make_divisible(v, divisor=8, min_value=None):- if min_value is None:- min_value = divisor- new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)- if new_v < 0.9 * v:- new_v += divisor- return new_v--def hard_sigmoid(x, slope=0.1666667, offset=0.5,):- return torch.clamp(slope * x + offset, 0., 1.)--def hard_swish(x, inplace=True):- return x * F.relu6(x + 3., inplace=inplace) / 6.--class MobileNetV3(nn.Module):- def __init__(self,- in_channels=3,- model_name='large',- scale=0.5,- disable_se=False,- **kwargs):- """- the MobilenetV3 backbone network for detection module.- Args:- params(dict): the super parameters for build network- """- super(MobileNetV3, self).__init__()-- self.disable_se = disable_se-- if model_name == "large":- cfg = [- # k, exp, c, se, nl, s,- [3, 16, 16, False, 'relu', 1],- [3, 64, 24, False, 'relu', 2],- [3, 72, 24, False, 'relu', 1],- [5, 72, 40, True, 'relu', 2],- [5, 120, 40, True, 'relu', 1],- [5, 120, 40, True, 'relu', 1],- [3, 240, 80, False, 'hardswish', 2],- [3, 200, 80, False, 'hardswish', 1],- [3, 184, 80, False, 'hardswish', 1],- [3, 184, 80, False, 'hardswish', 1],- [3, 480, 112, True, 'hardswish', 1],- [3, 672, 112, True, 'hardswish', 1],- [5, 672, 160, True, 'hardswish', 2],- [5, 960, 160, True, 'hardswish', 1],- [5, 960, 160, True, 'hardswish', 1],- ]- cls_ch_squeeze = 960- elif model_name == "small":- cfg = [- # k, exp, c, se, nl, s,- [3, 16, 16, True, 'relu', 2],- [3, 72, 24, False, 'relu', 2],- [3, 88, 24, False, 'relu', 1],- [5, 96, 40, True, 'hardswish', 2],- [5, 240, 40, True, 'hardswish', 1],- [5, 240, 40, True, 'hardswish', 1],- [5, 120, 48, True, 'hardswish', 1],- [5, 144, 48, True, 'hardswish', 1],- [5, 288, 96, True, 'hardswish', 2],- [5, 576, 96, True, 'hardswish', 1],- [5, 576, 96, True, 'hardswish', 1],- ]- cls_ch_squeeze = 576- else:- raise NotImplementedError("mode[" + model_name +- "_model] is not implemented!")-- supported_scale = [0.35, 0.5, 0.75, 1.0, 1.25]- assert scale in supported_scale, \- "supported scale are {} but input scale is {}".format(supported_scale, scale)- inplanes = 16- # conv1- self.conv = ConvBNLayer(- in_channels=in_channels,- out_channels=make_divisible(inplanes * scale),- kernel_size=3,- stride=2,- padding=1,- groups=1,- if_act=True,- act='hardswish',- name='conv1')-- self.stages = nn.ModuleList()- self.out_channels = []- block_list = []- i = 0- inplanes = make_divisible(inplanes * scale)- for (k, exp, c, se, nl, s) in cfg:- se = se and not self.disable_se- start_idx = 2 if model_name == 'large' else 0- if s == 2 and i > start_idx:- self.out_channels.append(inplanes)- self.stages.append(nn.Sequential(*block_list))- block_list = []- block_list.append(- ResidualUnit(- in_channels=inplanes,- mid_channels=make_divisible(scale * exp),- out_channels=make_divisible(scale * c),- kernel_size=k,- stride=s,- use_se=se,- act=nl,- name="conv" + str(i + 2)))- inplanes = make_divisible(scale * c)- i += 1- block_list.append(- ConvBNLayer(- in_channels=inplanes,- out_channels=make_divisible(scale * cls_ch_squeeze),- kernel_size=1,- stride=1,- padding=0,- groups=1,- if_act=True,- act='hardswish',- name='conv_last'))- self.stages.append(nn.Sequential(*block_list))- self.out_channels.append(make_divisible(scale * cls_ch_squeeze))- # for i, stage in enumerate(self.stages):- # self.add_module(module=stage, name="stage{}".format(i))-- def forward(self, x):- x = self.conv(x)- out_list = []- for stage in self.stages:- x = stage(x)- out_list.append(x)- return out_list---class ConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride,- padding,- groups=1,- if_act=True,- act=None,- name=None):- super(ConvBNLayer, self).__init__()- self.if_act = if_act- self.act = act- self.conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=padding,- groups=groups,- bias=False)-- self.bn = nn.BatchNorm2d(- out_channels,- )-- def forward(self, x):- x = self.conv(x)- x = self.bn(x)- if self.if_act:- if self.act == "relu":- x = F.relu(x)- elif self.act == "hardswish":- x = hard_swish(x)- else:- print("The activation function({}) is selected incorrectly.".- format(self.act))- exit()- return x---class ResidualUnit(nn.Module):- def __init__(self,- in_channels,- mid_channels,- out_channels,- kernel_size,- stride,- use_se,- act=None,- name=''):- super(ResidualUnit, self).__init__()- self.if_shortcut = stride == 1 and in_channels == out_channels- self.if_se = use_se-- self.expand_conv = ConvBNLayer(- in_channels=in_channels,- out_channels=mid_channels,- kernel_size=1,- stride=1,- padding=0,- if_act=True,- act=act,- name=name + "_expand")- self.bottleneck_conv = ConvBNLayer(- in_channels=mid_channels,- out_channels=mid_channels,- kernel_size=kernel_size,- stride=stride,- padding=int((kernel_size - 1) // 2),- groups=mid_channels,- if_act=True,- act=act,- name=name + "_depthwise")- if self.if_se:- self.mid_se = SEModule(mid_channels, name=name + "_se")- self.linear_conv = ConvBNLayer(- in_channels=mid_channels,- out_channels=out_channels,- kernel_size=1,- stride=1,- padding=0,- if_act=False,- act=None,- name=name + "_linear")-- def forward(self, inputs):- x = self.expand_conv(inputs)- x = self.bottleneck_conv(x)- if self.if_se:- x = self.mid_se(x)- x = self.linear_conv(x)- if self.if_shortcut:- x = torch.add(inputs, x)- return x---class SEModule(nn.Module):- def __init__(self, in_channels, reduction=4, name=""):- super(SEModule, self).__init__()- self.avg_pool = nn.AdaptiveAvgPool2d(1)- self.conv1 = nn.Conv2d(- in_channels=in_channels,- out_channels=in_channels // reduction,- kernel_size=1,- stride=1,- padding=0,- bias=True)- self.conv2 = nn.Conv2d(- in_channels=in_channels // reduction,- out_channels=in_channels,- kernel_size=1,- stride=1,- padding=0,- bias=True)-- def forward(self, inputs):- outputs = self.avg_pool(inputs)- outputs = self.conv1(outputs)- outputs = F.relu(outputs)- outputs = self.conv2(outputs)- outputs = hard_sigmoid(outputs, slope=0.2, offset=0.5)- return inputs * outputs\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/table_resnet_vd.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/table_resnet_vd.pydeleted file mode 100755index 77bfe4af..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/table_resnet_vd.py+++ /dev/null@@ -1,269 +0,0 @@-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation--__all__ = ["ResNet"]---class ConvBNLayer(nn.Module):- def __init__(- self,- in_channels,- out_channels,- kernel_size,- stride=1,- groups=1,- is_vd_mode=False,- act=None,- name=None, ):- super(ConvBNLayer, self).__init__()-- self.is_vd_mode = is_vd_mode- self._pool2d_avg = nn.AvgPool2d(- kernel_size=2, stride=2, padding=0, ceil_mode=True)- self._conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=(kernel_size - 1) // 2,- groups=groups,- bias=False)- if name == "conv1":- bn_name = "bn_" + name- else:- bn_name = "bn" + name[3:]- self._batch_norm = nn.BatchNorm2d(- out_channels,- )- self.act = act- if self.act is not None:- self._act = Activation(act, inplace=True)--- def forward(self, inputs):- if self.is_vd_mode:- inputs = self._pool2d_avg(inputs)- y = self._conv(inputs)- y = self._batch_norm(y)- if self.act is not None:- y = self._act(y)- return y---class BottleneckBlock(nn.Module):- def __init__(self,- in_channels,- out_channels,- stride,- shortcut=True,- if_first=False,- name=None):- super(BottleneckBlock, self).__init__()-- self.conv0 = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=1,- act='relu',- name=name + "_branch2a")- self.conv1 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels,- kernel_size=3,- stride=stride,- act='relu',- name=name + "_branch2b")- self.conv2 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels * 4,- kernel_size=1,- act=None,- name=name + "_branch2c")-- if not shortcut:- self.short = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels * 4,- kernel_size=1,- stride=1,- is_vd_mode=False if if_first else True,- name=name + "_branch1")-- self.shortcut = shortcut-- def forward(self, inputs):- y = self.conv0(inputs)- conv1 = self.conv1(y)- conv2 = self.conv2(conv1)-- if self.shortcut:- short = inputs- else:- short = self.short(inputs)- y = torch.add(short, conv2)- y = F.relu(y)- return y---class BasicBlock(nn.Module):- def __init__(self,- in_channels,- out_channels,- stride,- shortcut=True,- if_first=False,- name=None):- super(BasicBlock, self).__init__()- self.stride = stride- self.conv0 = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=3,- stride=stride,- act='relu',- name=name + "_branch2a")- self.conv1 = ConvBNLayer(- in_channels=out_channels,- out_channels=out_channels,- kernel_size=3,- act=None,- name=name + "_branch2b")-- if not shortcut:- self.short = ConvBNLayer(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=1,- stride=1,- is_vd_mode=False if if_first else True,- name=name + "_branch1")-- self.shortcut = shortcut-- def forward(self, inputs):- y = self.conv0(inputs)- conv1 = self.conv1(y)-- if self.shortcut:- short = inputs- else:- short = self.short(inputs)- y = torch.add(short, conv1)- y = F.relu(y)- return y---class ResNet(nn.Module):- def __init__(self, in_channels=3, layers=50, **kwargs):- super(ResNet, self).__init__()-- self.layers = layers- supported_layers = [18, 34, 50, 101, 152, 200]- assert layers in supported_layers, \- "supported layers are {} but input layer is {}".format(- supported_layers, layers)-- if layers == 18:- depth = [2, 2, 2, 2]- elif layers == 34 or layers == 50:- depth = [3, 4, 6, 3]- elif layers == 101:- depth = [3, 4, 23, 3]- elif layers == 152:- depth = [3, 8, 36, 3]- elif layers == 200:- depth = [3, 12, 48, 3]- num_channels = [64, 256, 512,- 1024] if layers >= 50 else [64, 64, 128, 256]- num_filters = [64, 128, 256, 512]-- self.conv1_1 = ConvBNLayer(- in_channels=in_channels,- out_channels=32,- kernel_size=3,- stride=2,- act='relu',- name="conv1_1")- self.conv1_2 = ConvBNLayer(- in_channels=32,- out_channels=32,- kernel_size=3,- stride=1,- act='relu',- name="conv1_2")- self.conv1_3 = ConvBNLayer(- in_channels=32,- out_channels=64,- kernel_size=3,- stride=1,- act='relu',- name="conv1_3")- self.pool2d_max = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)-- self.stages = nn.ModuleList()- self.out_channels = []- if layers >= 50:- for block in range(len(depth)):- block_list = nn.Sequential()- shortcut = False- for i in range(depth[block]):- if layers in [101, 152] and block == 2:- if i == 0:- conv_name = "res" + str(block + 2) + "a"- else:- conv_name = "res" + str(block + 2) + "b" + str(i)- else:- conv_name = "res" + str(block + 2) + chr(97 + i)- bottleneck_block = BottleneckBlock(- in_channels=num_channels[block]- if i == 0 else num_filters[block] * 4,- out_channels=num_filters[block],- stride=2 if i == 0 and block != 0 else 1,- shortcut=shortcut,- if_first=block == i == 0,- name=conv_name- )- shortcut = True- # block_list.append(bottleneck_block)- block_list.add_module('bb_%d_%d' % (block, i), bottleneck_block)- self.out_channels.append(num_filters[block] * 4)- # self.stages.append(nn.Sequential(*block_list))- self.stages.append(block_list)- else:- for block in range(len(depth)):- block_list = nn.Sequential()- shortcut = False- for i in range(depth[block]):- conv_name = "res" + str(block + 2) + chr(97 + i)- basic_block = BasicBlock(- in_channels=num_channels[block]- if i == 0 else num_filters[block],- out_channels=num_filters[block],- stride=2 if i == 0 and block != 0 else 1,- shortcut=shortcut,- if_first=block == i == 0,- name=conv_name- )- shortcut = True- # block_list.append(basic_block)- block_list.add_module('bb_%d_%d' % (block, i), basic_block)- self.out_channels.append(num_filters[block])- # self.stages.append(nn.Sequential(*block_list))- self.stages.append(block_list)-- def forward(self, inputs):- y = self.conv1_1(inputs)- y = self.conv1_2(y)- y = self.conv1_3(y)- y = self.pool2d_max(y)- out = []- for block in self.stages:- y = block(y)- out.append(y)- return out\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/common.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/common.pyold mode 100755new mode 100644index 2d6e3d93..ec1b30cc--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/common.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/common.py@@ -1,8 +1,7 @@--import torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nn+class Hswish(nn.Module):def __init__(self, inplace=True):@@ -10,7 +9,8 @@ class Hswish(nn.Module):self.inplace = inplacedef forward(self, x):- return x * F.relu6(x + 3., inplace=self.inplace) / 6.+ return x * F.relu6(x + 3.0, inplace=self.inplace) / 6.0+# out = max(0, min(1, slop*x+offset))# paddle.fluid.layers.hard_sigmoid(x, slope=0.2, offset=0.5, name=None)@@ -22,7 +22,8 @@ class Hsigmoid(nn.Module):def forward(self, x):# torch: F.relu6(x + 3., inplace=self.inplace) / 6.# paddle: F.relu6(1.2 * x + 3., inplace=self.inplace) / 6.- return F.relu6(1.2 * x + 3., inplace=self.inplace) / 6.+ return F.relu6(1.2 * x + 3.0, inplace=self.inplace) / 6.0+class GELU(nn.Module):def __init__(self, inplace=True):@@ -43,31 +44,33 @@ class Swish(nn.Module):x.mul_(torch.sigmoid(x))return xelse:- return x*torch.sigmoid(x)+ return x * torch.sigmoid(x)class Activation(nn.Module):def __init__(self, act_type, inplace=True):super(Activation, self).__init__()act_type = act_type.lower()- if act_type == 'relu':+ if act_type == "relu":self.act = nn.ReLU(inplace=inplace)- elif act_type == 'relu6':+ elif act_type == "relu6":self.act = nn.ReLU6(inplace=inplace)- elif act_type == 'sigmoid':+ elif act_type == "sigmoid":raise NotImplementedError- elif act_type == 'hard_sigmoid':- self.act = Hsigmoid(inplace)#nn.Hardsigmoid(inplace=inplace)#Hsigmoid(inplace)#- elif act_type == 'hard_swish' or act_type == 'hswish':+ elif act_type == "hard_sigmoid":+ self.act = Hsigmoid(+ inplace+ ) # nn.Hardsigmoid(inplace=inplace)#Hsigmoid(inplace)#+ elif act_type == "hard_swish" or act_type == "hswish":self.act = Hswish(inplace=inplace)- elif act_type == 'leakyrelu':+ elif act_type == "leakyrelu":self.act = nn.LeakyReLU(inplace=inplace)- elif act_type == 'gelu':+ elif act_type == "gelu":self.act = GELU(inplace=inplace)- elif act_type == 'swish':+ elif act_type == "swish":self.act = Swish(inplace=inplace)else:raise NotImplementedErrordef forward(self, inputs):- return self.act(inputs)\ No newline at end of file+ return self.act(inputs)diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/__init__.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/__init__.pyold mode 100755new mode 100644index ca9fe89c..00428c43--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/__init__.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/__init__.py@@ -12,40 +12,32 @@# See the License for the specific language governing permissions and# limitations under the License.-__all__ = ['build_head']+__all__ = ["build_head"]def build_head(config, **kwargs):# det headfrom .det_db_head import DBHead, PFHeadLocal- from .det_east_head import EASTHead- from .det_sast_head import SASTHead- from .det_pse_head import PSEHead- from .det_fce_head import FCEHead- from .e2e_pg_head import PGHead# rec headfrom .rec_ctc_head import CTCHead- from .rec_att_head import AttentionHead- from .rec_srn_head import SRNHead- from .rec_nrtr_head import Transformer- from .rec_sar_head import SARHead- from .rec_can_head import CANHeadfrom .rec_multi_head import MultiHead# cls headfrom .cls_head import ClsHead- support_dict = [- 'DBHead', 'PSEHead', 'EASTHead', 'SASTHead', 'CTCHead', 'ClsHead', 'AttentionHead',- 'SRNHead', 'PGHead', 'Transformer', 'TableAttentionHead','SARHead', 'FCEHead',- 'CANHead', 'MultiHead', 'PFHeadLocal',+ support_dict = [+ "DBHead",+ "CTCHead",+ "ClsHead",+ "MultiHead",+ "PFHeadLocal",]- from .table_att_head import TableAttentionHead-- module_name = config.pop('name')- assert module_name in support_dict, Exception('head only support {}'.format(- support_dict))+ module_name = config.pop("name")+ char_num = config.pop("char_num", 6625)+ assert module_name in support_dict, Exception(+ "head only support {}".format(support_dict)+ )module_class = eval(module_name)(**config, **kwargs)- return module_class\ No newline at end of file+ return module_classdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/cls_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/cls_head.pyold mode 100755new mode 100644index 476a2126..9353b9eb--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/cls_head.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/cls_head.py@@ -1,7 +1,7 @@-import os, sysimport torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nn+class ClsHead(nn.Module):"""@@ -12,17 +12,12 @@ class ClsHead(nn.Module):def __init__(self, in_channels, class_dim, **kwargs):super(ClsHead, self).__init__()- self.training = Falseself.pool = nn.AdaptiveAvgPool2d(1)- self.fc = nn.Linear(- in_channels,- class_dim,- bias=True)+ self.fc = nn.Linear(in_channels, class_dim, bias=True)def forward(self, x):x = self.pool(x)x = torch.reshape(x, shape=[x.shape[0], x.shape[1]])x = self.fc(x)- if not self.training:- x = F.softmax(x, dim=1)- return x\ No newline at end of file+ x = F.softmax(x, dim=1)+ return xdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_db_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_db_head.pyold mode 100755new mode 100644index c270e6bd..7c119683--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_db_head.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_db_head.py@@ -1,9 +1,8 @@-import os, sysimport torchimport torch.nn as nnimport torch.nn.functional as F-from pytorchocr.modeling.common import Activation-from pytorchocr.modeling.backbones.det_mobilenet_v3 import ConvBNLayer+from ..common import Activation+from ..backbones.det_mobilenet_v3 import ConvBNLayerclass Head(nn.Module):def __init__(self, in_channels, **kwargs):@@ -76,13 +75,8 @@ class DBHead(nn.Module):def forward(self, x):shrink_maps = self.binarize(x)- if not self.training:- return {'maps': shrink_maps}+ return {'maps': shrink_maps}- threshold_maps = self.thresh(x)- binary_maps = self.step_function(shrink_maps, threshold_maps)- y = torch.cat([shrink_maps, threshold_maps, binary_maps], dim=1)- return {'maps': y}class LocalModule(nn.Module):def __init__(self, in_c, mid_c, use_distance=True):@@ -101,7 +95,7 @@ class PFHeadLocal(DBHead):super(PFHeadLocal, self).__init__(in_channels, k, **kwargs)self.mode = mode- self.up_conv = nn.interpolate(scale_factor=2, mode="nearest")+ self.up_conv = nn.Upsample(scale_factor=2, mode="nearest")if self.mode == 'large':self.cbn_layer = LocalModule(in_channels // 4, in_channels // 4)elif self.mode == 'small':@@ -112,10 +106,4 @@ class PFHeadLocal(DBHead):base_maps = shrink_mapscbn_maps = self.cbn_layer(self.up_conv(f), shrink_maps, None)cbn_maps = F.sigmoid(cbn_maps)- if not self.training:- return {'maps': 0.5 * (base_maps + cbn_maps), 'cbn_maps': cbn_maps}-- threshold_maps = self.thresh(x)- binary_maps = self.step_function(shrink_maps, threshold_maps)- y = torch.cat([cbn_maps, threshold_maps, binary_maps], dim=1)- return {'maps': y, 'distance_maps': cbn_maps, 'cbn_maps': binary_maps}\ No newline at end of file+ return {'maps': 0.5 * (base_maps + cbn_maps), 'cbn_maps': cbn_maps}\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_east_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_east_head.pydeleted file mode 100755index 0df9c483..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_east_head.py+++ /dev/null@@ -1,112 +0,0 @@-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import math-import os, sys-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation-# import paddle-# from paddle import nn-# import paddle.nn.functional as F-# from paddle import ParamAttr---class ConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride,- padding,- groups=1,- if_act=True,- act=None,- name=None):- super(ConvBNLayer, self).__init__()- self.if_act = if_act- self.act = act-- self.conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=padding,- groups=groups,- bias=False)-- self.bn = nn.BatchNorm2d(- out_channels,)- self.act = act- if act is not None:- self._act = Activation(act)-- def forward(self, x):- x = self.conv(x)- x = self.bn(x)- if self.act is not None:- x = self._act(x)- return x---class EASTHead(nn.Module):- """- """- def __init__(self, in_channels, model_name, **kwargs):- super(EASTHead, self).__init__()- self.model_name = model_name- if self.model_name == "large":- num_outputs = [128, 64, 1, 8]- else:- num_outputs = [64, 32, 1, 8]-- self.det_conv1 = ConvBNLayer(- in_channels=in_channels,- out_channels=num_outputs[0],- kernel_size=3,- stride=1,- padding=1,- if_act=True,- act='relu',- name="det_head1")- self.det_conv2 = ConvBNLayer(- in_channels=num_outputs[0],- out_channels=num_outputs[1],- kernel_size=3,- stride=1,- padding=1,- if_act=True,- act='relu',- name="det_head2")- self.score_conv = ConvBNLayer(- in_channels=num_outputs[1],- out_channels=num_outputs[2],- kernel_size=1,- stride=1,- padding=0,- if_act=False,- act=None,- name="f_score")- self.geo_conv = ConvBNLayer(- in_channels=num_outputs[1],- out_channels=num_outputs[3],- kernel_size=1,- stride=1,- padding=0,- if_act=False,- act=None,- name="f_geo")-- def forward(self, x):- f_det = self.det_conv1(x)- f_det = self.det_conv2(f_det)- f_score = self.score_conv(f_det)- f_score = torch.sigmoid(f_score)- f_geo = self.geo_conv(f_det)- f_geo = (torch.sigmoid(f_geo) - 0.5) * 2 * 800-- pred = {'f_score': f_score, 'f_geo': f_geo}- return pred\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_fce_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_fce_head.pydeleted file mode 100755index 22773c97..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_fce_head.py+++ /dev/null@@ -1,82 +0,0 @@-"""-This code is refer from:-https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textdet/dense_heads/fce_head.py-"""--import torch-import torch.nn as nn-import torch.nn.functional as F--# from paddle import nn-# from paddle import ParamAttr-# import paddle.nn.functional as F-# from paddle.nn.initializer import Normal-# import paddle-from functools import partial---def multi_apply(func, *args, **kwargs):- pfunc = partial(func, **kwargs) if kwargs else func- map_results = map(pfunc, *args)- return tuple(map(list, zip(*map_results)))---class FCEHead(nn.Module):- """The class for implementing FCENet head.- FCENet(CVPR2021): Fourier Contour Embedding for Arbitrary-shaped Text- Detection.-- [https://arxiv.org/abs/2104.10442]-- Args:- in_channels (int): The number of input channels.- scales (list[int]) : The scale of each layer.- fourier_degree (int) : The maximum Fourier transform degree k.- """-- def __init__(self, in_channels, fourier_degree=5):- super().__init__()- assert isinstance(in_channels, int)-- self.downsample_ratio = 1.0- self.in_channels = in_channels- self.fourier_degree = fourier_degree- self.out_channels_cls = 4- self.out_channels_reg = (2 * self.fourier_degree + 1) * 2-- self.out_conv_cls = nn.Conv2d(- in_channels=self.in_channels,- out_channels=self.out_channels_cls,- kernel_size=3,- stride=1,- padding=1,- groups=1,- bias=True)- self.out_conv_reg = nn.Conv2d(- in_channels=self.in_channels,- out_channels=self.out_channels_reg,- kernel_size=3,- stride=1,- padding=1,- groups=1,- bias=True)-- def forward(self, feats, targets=None):- cls_res, reg_res = multi_apply(self.forward_single, feats)- level_num = len(cls_res)- outs = {}- if not self.training:- for i in range(level_num):- tr_pred = F.softmax(cls_res[i][:, 0:2, :, :], dim=1)- tcl_pred = F.softmax(cls_res[i][:, 2:, :, :], dim=1)- outs['level_{}'.format(i)] = torch.cat(- [tr_pred, tcl_pred, reg_res[i]], dim=1)- else:- preds = [[cls_res[i], reg_res[i]] for i in range(level_num)]- outs['levels'] = preds- return outs-- def forward_single(self, x):- cls_predict = self.out_conv_cls(x)- reg_predict = self.out_conv_reg(x)- return cls_predict, reg_predictdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_pse_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_pse_head.pydeleted file mode 100755index c032212b..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_pse_head.py+++ /dev/null@@ -1,25 +0,0 @@-"""-This code is refer from:-https://github.com/whai362/PSENet/blob/python3/models/head/psenet_head.py-"""--# from paddle import nn-from torch import nn---class PSEHead(nn.Module):- def __init__(self, in_channels, hidden_dim=256, out_channels=7, **kwargs):- super(PSEHead, self).__init__()- self.conv1 = nn.Conv2d(- in_channels, hidden_dim, kernel_size=3, stride=1, padding=1)- self.bn1 = nn.BatchNorm2d(hidden_dim)- self.relu1 = nn.ReLU()-- self.conv2 = nn.Conv2d(- hidden_dim, out_channels, kernel_size=1, stride=1, padding=0)-- def forward(self, x, **kwargs):- out = self.conv1(x)- out = self.relu1(self.bn1(out))- out = self.conv2(out)- return {'maps': out}diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_sast_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_sast_head.pydeleted file mode 100755index 5b104e6f..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_sast_head.py+++ /dev/null@@ -1,118 +0,0 @@-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import math-import os, sys-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation-# import paddle-# from paddle import nn-# import paddle.nn.functional as F-# from paddle import ParamAttr---class ConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride,- groups=1,- if_act=True,- act=None,- name=None):- super(ConvBNLayer, self).__init__()- self.if_act = if_act-- self.conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=(kernel_size - 1) // 2,- groups=groups,- bias=False)-- self.bn = nn.BatchNorm2d(- out_channels,)- self.act = act- if act is not None:- self._act = Activation(act)-- def forward(self, x):- x = self.conv(x)- x = self.bn(x)- if self.act is not None:- x = self._act(x)- return x---class SAST_Header1(nn.Module):- def __init__(self, in_channels, **kwargs):- super(SAST_Header1, self).__init__()- out_channels = [64, 64, 128]- self.score_conv = nn.Sequential(- ConvBNLayer(in_channels, out_channels[0], 1, 1, act='relu', name='f_score1'),- ConvBNLayer(out_channels[0], out_channels[1], 3, 1, act='relu', name='f_score2'),- ConvBNLayer(out_channels[1], out_channels[2], 1, 1, act='relu', name='f_score3'),- ConvBNLayer(out_channels[2], 1, 3, 1, act=None, name='f_score4')- )- self.border_conv = nn.Sequential(- ConvBNLayer(in_channels, out_channels[0], 1, 1, act='relu', name='f_border1'),- ConvBNLayer(out_channels[0], out_channels[1], 3, 1, act='relu', name='f_border2'),- ConvBNLayer(out_channels[1], out_channels[2], 1, 1, act='relu', name='f_border3'),- ConvBNLayer(out_channels[2], 4, 3, 1, act=None, name='f_border4')- )-- def forward(self, x):- f_score = self.score_conv(x)- f_score = torch.sigmoid(f_score)- f_border = self.border_conv(x)- return f_score, f_border---class SAST_Header2(nn.Module):- def __init__(self, in_channels, **kwargs):- super(SAST_Header2, self).__init__()- out_channels = [64, 64, 128]- self.tvo_conv = nn.Sequential(- ConvBNLayer(in_channels, out_channels[0], 1, 1, act='relu', name='f_tvo1'),- ConvBNLayer(out_channels[0], out_channels[1], 3, 1, act='relu', name='f_tvo2'),- ConvBNLayer(out_channels[1], out_channels[2], 1, 1, act='relu', name='f_tvo3'),- ConvBNLayer(out_channels[2], 8, 3, 1, act=None, name='f_tvo4')- )- self.tco_conv = nn.Sequential(- ConvBNLayer(in_channels, out_channels[0], 1, 1, act='relu', name='f_tco1'),- ConvBNLayer(out_channels[0], out_channels[1], 3, 1, act='relu', name='f_tco2'),- ConvBNLayer(out_channels[1], out_channels[2], 1, 1, act='relu', name='f_tco3'),- ConvBNLayer(out_channels[2], 2, 3, 1, act=None, name='f_tco4')- )-- def forward(self, x):- f_tvo = self.tvo_conv(x)- f_tco = self.tco_conv(x)- return f_tvo, f_tco---class SASTHead(nn.Module):- """- """- def __init__(self, in_channels, **kwargs):- super(SASTHead, self).__init__()-- self.head1 = SAST_Header1(in_channels)- self.head2 = SAST_Header2(in_channels)-- def forward(self, x):- f_score, f_border = self.head1(x)- f_tvo, f_tco = self.head2(x)-- predicts = {}- predicts['f_score'] = f_score- predicts['f_border'] = f_border- predicts['f_tvo'] = f_tvo- predicts['f_tco'] = f_tco- return predicts\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/e2e_pg_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/e2e_pg_head.pydeleted file mode 100755index e3e21302..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/e2e_pg_head.py+++ /dev/null@@ -1,234 +0,0 @@---from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import math-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation---class ConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride,- padding,- groups=1,- if_act=True,- act=None,- name=None):- super(ConvBNLayer, self).__init__()- self.if_act = if_act- self.act = act- self.conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=padding,- groups=groups,- bias=False)-- self.bn = nn.BatchNorm2d(out_channels)- self.act = act- if self.act is not None:- self._act = Activation(act_type=self.act, inplace=True)-- def forward(self, x):- x = self.conv(x)- x = self.bn(x)- if self.act is not None:- x = self._act(x)- return x---class PGHead(nn.Module):- """- """-- def __init__(self, in_channels, **kwargs):- super(PGHead, self).__init__()- self.conv_f_score1 = ConvBNLayer(- in_channels=in_channels,- out_channels=64,- kernel_size=1,- stride=1,- padding=0,- act='relu',- name="conv_f_score{}".format(1))- self.conv_f_score2 = ConvBNLayer(- in_channels=64,- out_channels=64,- kernel_size=3,- stride=1,- padding=1,- act='relu',- name="conv_f_score{}".format(2))- self.conv_f_score3 = ConvBNLayer(- in_channels=64,- out_channels=128,- kernel_size=1,- stride=1,- padding=0,- act='relu',- name="conv_f_score{}".format(3))-- self.conv1 = nn.Conv2d(- in_channels=128,- out_channels=1,- kernel_size=3,- stride=1,- padding=1,- groups=1,- bias=False)-- self.conv_f_boder1 = ConvBNLayer(- in_channels=in_channels,- out_channels=64,- kernel_size=1,- stride=1,- padding=0,- act='relu',- name="conv_f_boder{}".format(1))- self.conv_f_boder2 = ConvBNLayer(- in_channels=64,- out_channels=64,- kernel_size=3,- stride=1,- padding=1,- act='relu',- name="conv_f_boder{}".format(2))- self.conv_f_boder3 = ConvBNLayer(- in_channels=64,- out_channels=128,- kernel_size=1,- stride=1,- padding=0,- act='relu',- name="conv_f_boder{}".format(3))- self.conv2 = nn.Conv2d(- in_channels=128,- out_channels=4,- kernel_size=3,- stride=1,- padding=1,- groups=1,- bias=False)- self.conv_f_char1 = ConvBNLayer(- in_channels=in_channels,- out_channels=128,- kernel_size=1,- stride=1,- padding=0,- act='relu',- name="conv_f_char{}".format(1))- self.conv_f_char2 = ConvBNLayer(- in_channels=128,- out_channels=128,- kernel_size=3,- stride=1,- padding=1,- act='relu',- name="conv_f_char{}".format(2))- self.conv_f_char3 = ConvBNLayer(- in_channels=128,- out_channels=256,- kernel_size=1,- stride=1,- padding=0,- act='relu',- name="conv_f_char{}".format(3))- self.conv_f_char4 = ConvBNLayer(- in_channels=256,- out_channels=256,- kernel_size=3,- stride=1,- padding=1,- act='relu',- name="conv_f_char{}".format(4))- self.conv_f_char5 = ConvBNLayer(- in_channels=256,- out_channels=256,- kernel_size=1,- stride=1,- padding=0,- act='relu',- name="conv_f_char{}".format(5))- self.conv3 = nn.Conv2d(- in_channels=256,- out_channels=37,- kernel_size=3,- stride=1,- padding=1,- groups=1,- bias=False)-- self.conv_f_direc1 = ConvBNLayer(- in_channels=in_channels,- out_channels=64,- kernel_size=1,- stride=1,- padding=0,- act='relu',- name="conv_f_direc{}".format(1))- self.conv_f_direc2 = ConvBNLayer(- in_channels=64,- out_channels=64,- kernel_size=3,- stride=1,- padding=1,- act='relu',- name="conv_f_direc{}".format(2))- self.conv_f_direc3 = ConvBNLayer(- in_channels=64,- out_channels=128,- kernel_size=1,- stride=1,- padding=0,- act='relu',- name="conv_f_direc{}".format(3))- self.conv4 = nn.Conv2d(- in_channels=128,- out_channels=2,- kernel_size=3,- stride=1,- padding=1,- groups=1,- bias=False)-- def forward(self, x):- f_score = self.conv_f_score1(x)- f_score = self.conv_f_score2(f_score)- f_score = self.conv_f_score3(f_score)- f_score = self.conv1(f_score)- f_score = torch.sigmoid(f_score)-- # f_border- f_border = self.conv_f_boder1(x)- f_border = self.conv_f_boder2(f_border)- f_border = self.conv_f_boder3(f_border)- f_border = self.conv2(f_border)-- f_char = self.conv_f_char1(x)- f_char = self.conv_f_char2(f_char)- f_char = self.conv_f_char3(f_char)- f_char = self.conv_f_char4(f_char)- f_char = self.conv_f_char5(f_char)- f_char = self.conv3(f_char)-- f_direction = self.conv_f_direc1(x)- f_direction = self.conv_f_direc2(f_direction)- f_direction = self.conv_f_direc3(f_direction)- f_direction = self.conv4(f_direction)-- predicts = {}- predicts['f_score'] = f_score- predicts['f_border'] = f_border- predicts['f_char'] = f_char- predicts['f_direction'] = f_direction- return predictsdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/multiheadAttention.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/multiheadAttention.pydeleted file mode 100755index cbd887c5..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/multiheadAttention.py+++ /dev/null@@ -1,150 +0,0 @@-import torch-from torch import nn-import torch.nn.functional as F-from torch.nn import Linear-from torch.nn.init import xavier_uniform_---class MultiheadAttention(nn.Module):- """Allows the model to jointly attend to information- from different representation subspaces.- See reference: Attention Is All You Need-- .. math::- \text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O- \text{where} head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)-- Args:- embed_dim: total dimension of the model- num_heads: parallel attention layers, or heads-- """-- def __init__(self,- embed_dim,- num_heads,- dropout=0.,- bias=True,- add_bias_kv=False,- add_zero_attn=False):- super(MultiheadAttention, self).__init__()- self.embed_dim = embed_dim- self.num_heads = num_heads- self.dropout = dropout- self.head_dim = embed_dim // num_heads- assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"- self.scaling = self.head_dim**-0.5- self.out_proj = Linear(embed_dim, embed_dim, bias=bias)- self._reset_parameters()- self.conv1 = torch.nn.Conv2d(- in_channels=embed_dim, out_channels=embed_dim, kernel_size=(1, 1))- self.conv2 = torch.nn.Conv2d(- in_channels=embed_dim, out_channels=embed_dim, kernel_size=(1, 1))- self.conv3 = torch.nn.Conv2d(- in_channels=embed_dim, out_channels=embed_dim, kernel_size=(1, 1))-- def _reset_parameters(self):- xavier_uniform_(self.out_proj.weight)-- def forward(self,- query,- key,- value,- key_padding_mask=None,- incremental_state=None,- attn_mask=None):- """- Inputs of forward function- query: [target length, batch size, embed dim]- key: [sequence length, batch size, embed dim]- value: [sequence length, batch size, embed dim]- key_padding_mask: if True, mask padding based on batch size- incremental_state: if provided, previous time steps are cashed- need_weights: output attn_output_weights- static_kv: key and value are static-- Outputs of forward function- attn_output: [target length, batch size, embed dim]- attn_output_weights: [batch size, target length, sequence length]- """- q_shape = query.shape- src_shape = key.shape- q = self._in_proj_q(query)- k = self._in_proj_k(key)- v = self._in_proj_v(value)- q *= self.scaling- # q = paddle.transpose(- # paddle.reshape(- # q, [q_shape[0], q_shape[1], self.num_heads, self.head_dim]),- # [1, 2, 0, 3])- q = torch.reshape(q, (q_shape[0], q_shape[1], self.num_heads, self.head_dim))- q = q.permute(1, 2, 0, 3)- # k = paddle.transpose(- # paddle.reshape(- # k, [src_shape[0], q_shape[1], self.num_heads, self.head_dim]),- # [1, 2, 0, 3])- k = torch.reshape(k, (src_shape[0], q_shape[1], self.num_heads, self.head_dim))- k = k.permute(1, 2, 0, 3)- # v = paddle.transpose(- # paddle.reshape(- # v, [src_shape[0], q_shape[1], self.num_heads, self.head_dim]),- # [1, 2, 0, 3])- v = torch.reshape(v, (src_shape[0], q_shape[1], self.num_heads, self.head_dim))- v = v.permute(1, 2, 0, 3)- if key_padding_mask is not None:- assert key_padding_mask.shape[0] == q_shape[1]- assert key_padding_mask.shape[1] == src_shape[0]- attn_output_weights = torch.matmul(q,- k.permute(0, 1, 3, 2))- if attn_mask is not None:- attn_mask = torch.unsqueeze(torch.unsqueeze(attn_mask, 0), 0)- attn_output_weights += attn_mask- if key_padding_mask is not None:- attn_output_weights = torch.reshape(- attn_output_weights,- [q_shape[1], self.num_heads, q_shape[0], src_shape[0]])- key = torch.unsqueeze(torch.unsqueeze(key_padding_mask, 1), 2)- key = key.type(torch.float32)- y = torch.full(- size=key.shape, fill_value=float("-Inf"), dtype=torch.float32)- y = torch.where(key == 0., key, y)- attn_output_weights += y- attn_output_weights = F.softmax(- attn_output_weights.type(torch.float32),- dim=-1,- dtype=torch.float32 if attn_output_weights.dtype == torch.float16- else attn_output_weights.dtype)- attn_output_weights = F.dropout(- attn_output_weights, p=self.dropout, training=self.training)-- attn_output = torch.matmul(attn_output_weights, v)- attn_output = torch.reshape(- attn_output.permute(2, 0, 1, 3),- [q_shape[0], q_shape[1], self.embed_dim])- attn_output = self.out_proj(attn_output)-- return attn_output-- def _in_proj_q(self, query):- query = query.permute(1, 2, 0)- query = torch.unsqueeze(query, dim=2)- res = self.conv1(query)- res = torch.squeeze(res, dim=2)- res = res.permute(2, 0, 1)- return res-- def _in_proj_k(self, key):- key = key.permute(1, 2, 0)- key = torch.unsqueeze(key, dim=2)- res = self.conv2(key)- res = torch.squeeze(res, dim=2)- res = res.permute(2, 0, 1)- return res-- def _in_proj_v(self, value):- value = value.permute(1, 2, 0) #(1, 2, 0)- value = torch.unsqueeze(value, dim=2)- res = self.conv3(value)- res = torch.squeeze(res, dim=2)- res = res.permute(2, 0, 1)- return resdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_att_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_att_head.pydeleted file mode 100755index a057c52c..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_att_head.py+++ /dev/null@@ -1,190 +0,0 @@-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import numpy as np-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation---class AttentionHead(nn.Module):- def __init__(self, in_channels, out_channels, hidden_size, **kwargs):- super(AttentionHead, self).__init__()- self.input_size = in_channels- self.hidden_size = hidden_size- self.num_classes = out_channels-- self.attention_cell = AttentionGRUCell(- in_channels, hidden_size, out_channels, use_gru=False)- self.generator = nn.Linear(hidden_size, out_channels)-- def _char_to_onehot(self, input_char, onehot_dim):- input_ont_hot = F.one_hot(input_char.type(torch.int64), onehot_dim)- return input_ont_hot-- def forward(self, inputs, targets=None, batch_max_length=25):- batch_size = inputs.size()[0]- num_steps = batch_max_length-- hidden = torch.zeros((batch_size, self.hidden_size))- output_hiddens = []-- if targets is not None:- for i in range(num_steps):- char_onehots = self._char_to_onehot(- targets[:, i], onehot_dim=self.num_classes)- (outputs, hidden), alpha = self.attention_cell(hidden, inputs,- char_onehots)- output_hiddens.append(torch.unsqueeze(outputs, dim=1))- output = torch.cat(output_hiddens, dim=1)- probs = self.generator(output)-- else:- targets = torch.zeros([batch_size], dtype=torch.int32)- probs = None- char_onehots = None- outputs = None- alpha = None-- for i in range(num_steps):- char_onehots = self._char_to_onehot(- targets, onehot_dim=self.num_classes)- (outputs, hidden), alpha = self.attention_cell(hidden, inputs,- char_onehots)- probs_step = self.generator(outputs)- if probs is None:- probs = torch.unsqueeze(probs_step, dim=1)- else:- probs = torch.cat(- [probs, torch.unsqueeze(- probs_step, dim=1)], dim=1)- next_input = probs_step.argmax(dim=1)- targets = next_input-- return probs---class AttentionGRUCell(nn.Module):- def __init__(self, input_size, hidden_size, num_embeddings, use_gru=False):- super(AttentionGRUCell, self).__init__()- self.i2h = nn.Linear(input_size, hidden_size, bias=False)- self.h2h = nn.Linear(hidden_size, hidden_size)- self.score = nn.Linear(hidden_size, 1, bias=False)-- self.rnn = nn.GRUCell(- input_size=input_size + num_embeddings, hidden_size=hidden_size, bias=True)-- self.hidden_size = hidden_size-- def forward(self, prev_hidden, batch_H, char_onehots):-- batch_H_proj = self.i2h(batch_H)- prev_hidden_proj = torch.unsqueeze(self.h2h(prev_hidden), dim=1)-- res = torch.add(batch_H_proj, prev_hidden_proj)- res = torch.tanh(res)- e = self.score(res)-- alpha = F.softmax(e, dim=1)- alpha = alpha.permute(0, 2, 1)- context = torch.squeeze(torch.matmul(alpha, batch_H), dim=1)- concat_context = torch.cat([context, char_onehots.float()], 1)-- cur_hidden = self.rnn(concat_context, prev_hidden)-- return (cur_hidden, cur_hidden), alpha---class AttentionLSTM(nn.Module):- def __init__(self, in_channels, out_channels, hidden_size, **kwargs):- super(AttentionLSTM, self).__init__()- self.input_size = in_channels- self.hidden_size = hidden_size- self.num_classes = out_channels-- self.attention_cell = AttentionLSTMCell(- in_channels, hidden_size, out_channels, use_gru=False)- self.generator = nn.Linear(hidden_size, out_channels)-- def _char_to_onehot(self, input_char, onehot_dim):- input_ont_hot = F.one_hot(input_char.type(torch.int64), onehot_dim)- return input_ont_hot-- def forward(self, inputs, targets=None, batch_max_length=25):- batch_size = inputs.shape[0]- num_steps = batch_max_length-- hidden = (torch.zeros((batch_size, self.hidden_size)), torch.zeros(- (batch_size, self.hidden_size)))- output_hiddens = []-- if targets is not None:- for i in range(num_steps):- # one-hot vectors for a i-th char- char_onehots = self._char_to_onehot(- targets[:, i], onehot_dim=self.num_classes)- hidden, alpha = self.attention_cell(hidden, inputs,- char_onehots)-- hidden = (hidden[1][0], hidden[1][1])- output_hiddens.append(torch.unsqueeze(hidden[0], dim=1))- output = torch.cat(output_hiddens, dim=1)- probs = self.generator(output)-- else:- targets = torch.zeros([batch_size], dtype=torch.int32)- probs = None-- for i in range(num_steps):- char_onehots = self._char_to_onehot(- targets, onehot_dim=self.num_classes)- hidden, alpha = self.attention_cell(hidden, inputs,- char_onehots)- probs_step = self.generator(hidden[0])- hidden = (hidden[1][0], hidden[1][1])- if probs is None:- probs = torch.unsqueeze(probs_step, dim=1)- else:- probs = torch.cat(- [probs, torch.unsqueeze(- probs_step, dim=1)], dim=1)-- next_input = probs_step.argmax(dim=1)-- targets = next_input-- return probs---class AttentionLSTMCell(nn.Module):- def __init__(self, input_size, hidden_size, num_embeddings, use_gru=False):- super(AttentionLSTMCell, self).__init__()- self.i2h = nn.Linear(input_size, hidden_size, bias=False)- self.h2h = nn.Linear(hidden_size, hidden_size)- self.score = nn.Linear(hidden_size, 1, bias=False)- if not use_gru:- self.rnn = nn.LSTMCell(- input_size=input_size + num_embeddings, hidden_size=hidden_size)- else:- self.rnn = nn.GRUCell(- input_size=input_size + num_embeddings, hidden_size=hidden_size)-- self.hidden_size = hidden_size-- def forward(self, prev_hidden, batch_H, char_onehots):- batch_H_proj = self.i2h(batch_H)- prev_hidden_proj = torch.unsqueeze(self.h2h(prev_hidden[0]), dim=1)- res = torch.add(batch_H_proj, prev_hidden_proj)- res = torch.tanh(res)- e = self.score(res)-- alpha = F.softmax(e, dim=1)- alpha = alpha.permute(0, 2, 1)- context = torch.squeeze(torch.matmul(alpha, batch_H), dim=1)- concat_context = torch.cat([context, char_onehots.float()], 1)-- cur_hidden = self.rnn(concat_context, prev_hidden)-- return cur_hidden, alphadiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_can_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_can_head.pydeleted file mode 100755index 4d097f58..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_can_head.py+++ /dev/null@@ -1,288 +0,0 @@-"""-This code is refer from:-https://github.com/LBH1024/CAN/models/can.py-https://github.com/LBH1024/CAN/models/counting.py-https://github.com/LBH1024/CAN/models/decoder.py-https://github.com/LBH1024/CAN/models/attention.py--"""--from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import torch.nn as nn-import torch-import math-'''-Counting Module-'''---class ChannelAtt(nn.Module):- def __init__(self, channel, reduction):- super(ChannelAtt, self).__init__()- self.avg_pool = nn.AdaptiveAvgPool2d(1)-- self.fc = nn.Sequential(- nn.Linear(channel, channel // reduction),- nn.ReLU(), nn.Linear(channel // reduction, channel), nn.Sigmoid())-- def forward(self, x):- b, c, _, _ = x.shape- y = self.avg_pool(x).view(b, c)- y = self.fc(y).view(b, c, 1, 1)- return x * y---class CountingDecoder(nn.Module):- def __init__(self, in_channel, out_channel, kernel_size):- super(CountingDecoder, self).__init__()- self.in_channel = in_channel- self.out_channel = out_channel-- self.trans_layer = nn.Sequential(- nn.Conv2d(- self.in_channel,- 512,- kernel_size=kernel_size,- padding=kernel_size // 2,- bias=False),- nn.BatchNorm2d(512))-- self.channel_att = ChannelAtt(512, 16)-- self.pred_layer = nn.Sequential(- nn.Conv2d(- 512, self.out_channel, kernel_size=1, bias=False),- nn.Sigmoid())-- def forward(self, x, mask):- b, _, h, w = x.shape- x = self.trans_layer(x)- x = self.channel_att(x)- x = self.pred_layer(x)-- if mask is not None:- x = x * mask- x = x.view(b, self.out_channel, -1)- x1 = torch.sum(x, dim=-1)-- return x1, x.view(b, self.out_channel, h, w)---'''-Attention Decoder-'''---class PositionEmbeddingSine(nn.Module):- def __init__(self,- num_pos_feats=64,- temperature=10000,- normalize=False,- scale=None):- super().__init__()- self.num_pos_feats = num_pos_feats- self.temperature = temperature- self.normalize = normalize- if scale is not None and normalize is False:- raise ValueError("normalize should be True if scale is passed")- if scale is None:- scale = 2 * math.pi- self.scale = scale-- def forward(self, x, mask):- y_embed = mask.cumsum(1, dtype=torch.float32)- x_embed = mask.cumsum(2, dtype=torch.float32)-- if self.normalize:- eps = 1e-6- y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale- x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale- dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)- # dim_d = paddle.expand(paddle.to_tensor(2), dim_t.shape)- # dim_t = self.temperature**(2 * (dim_t / dim_d).astype('int64') /- # self.num_pos_feats)- dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)-- pos_x = torch.unsqueeze(x_embed, 3) / dim_t- pos_y = torch.unsqueeze(y_embed, 3) / dim_t-- pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)- pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)-- pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)-- return pos---class AttDecoder(nn.Module):- def __init__(self, ratio, is_train, input_size, hidden_size,- encoder_out_channel, dropout, dropout_ratio, word_num,- counting_decoder_out_channel, attention):- super(AttDecoder, self).__init__()- self.input_size = input_size- self.hidden_size = hidden_size- self.out_channel = encoder_out_channel- self.attention_dim = attention['attention_dim']- self.dropout_prob = dropout- self.ratio = ratio- self.word_num = word_num-- self.counting_num = counting_decoder_out_channel- self.is_train = is_train-- self.init_weight = nn.Linear(self.out_channel, self.hidden_size)- self.embedding = nn.Embedding(self.word_num, self.input_size)- self.word_input_gru = nn.GRUCell(self.input_size, self.hidden_size)- self.word_attention = Attention(hidden_size, attention['attention_dim'])-- self.encoder_feature_conv = nn.Conv2d(- self.out_channel,- self.attention_dim,- kernel_size=attention['word_conv_kernel'],- padding=attention['word_conv_kernel'] // 2)-- self.word_state_weight = nn.Linear(self.hidden_size, self.hidden_size)- self.word_embedding_weight = nn.Linear(self.input_size,- self.hidden_size)- self.word_context_weight = nn.Linear(self.out_channel, self.hidden_size)- self.counting_context_weight = nn.Linear(self.counting_num,- self.hidden_size)- self.word_convert = nn.Linear(self.hidden_size, self.word_num)-- if dropout:- self.dropout = nn.Dropout(dropout_ratio)-- def forward(self, cnn_features, labels, counting_preds, images_mask):- if self.is_train:- _, num_steps = labels.shape- else:- num_steps = 36-- batch_size, _, height, width = cnn_features.shape- images_mask = images_mask[:, :, ::self.ratio, ::self.ratio]-- word_probs = torch.zeros((batch_size, num_steps, self.word_num)).to(device=cnn_features.device)- word_alpha_sum = torch.zeros((batch_size, 1, height, width)).to(device=cnn_features.device)-- hidden = self.init_hidden(cnn_features, images_mask)- counting_context_weighted = self.counting_context_weight(counting_preds)- cnn_features_trans = self.encoder_feature_conv(cnn_features)-- position_embedding = PositionEmbeddingSine(256, normalize=True)- pos = position_embedding(cnn_features_trans, images_mask[:, 0, :, :])-- cnn_features_trans = cnn_features_trans + pos-- word = torch.ones([batch_size]).long().to(device=cnn_features.device) # init word as sos- for i in range(num_steps):- word_embedding = self.embedding(word)- hidden = self.word_input_gru(word_embedding, hidden)- word_context_vec, _, word_alpha_sum = self.word_attention(- cnn_features, cnn_features_trans, hidden, word_alpha_sum,- images_mask)-- current_state = self.word_state_weight(hidden)- word_weighted_embedding = self.word_embedding_weight(word_embedding)- word_context_weighted = self.word_context_weight(word_context_vec)-- if self.dropout_prob:- word_out_state = self.dropout(- current_state + word_weighted_embedding +- word_context_weighted + counting_context_weighted)- else:- word_out_state = current_state + word_weighted_embedding + word_context_weighted + counting_context_weighted-- word_prob = self.word_convert(word_out_state)- word_probs[:, i] = word_prob-- if self.is_train:- word = labels[:, i]- else:- word = word_prob.argmax(1)- word = torch.mul(- word, labels[:, i]- ) # labels are oneslike tensor in infer/predict mode, torch.multiply-- return word_probs-- def init_hidden(self, features, feature_mask):- average = torch.sum(torch.sum(features * feature_mask, dim=-1),- dim=-1) / torch.sum(- (torch.sum(feature_mask, dim=-1)), dim=-1)- average = self.init_weight(average)- return torch.tanh(average)---'''-Attention Module-'''---class Attention(nn.Module):- def __init__(self, hidden_size, attention_dim):- super(Attention, self).__init__()- self.hidden = hidden_size- self.attention_dim = attention_dim- self.hidden_weight = nn.Linear(self.hidden, self.attention_dim)- self.attention_conv = nn.Conv2d(- 1, 512, kernel_size=11, padding=5, bias=False)- self.attention_weight = nn.Linear(- 512, self.attention_dim, bias=False)- self.alpha_convert = nn.Linear(self.attention_dim, 1)-- def forward(self,- cnn_features,- cnn_features_trans,- hidden,- alpha_sum,- image_mask=None):- query = self.hidden_weight(hidden)- alpha_sum_trans = self.attention_conv(alpha_sum)- coverage_alpha = self.attention_weight(alpha_sum_trans.permute(0, 2, 3, 1))- alpha_score = torch.tanh(- query[:, None, None, :] + coverage_alpha + cnn_features_trans.permute(0, 2, 3, 1)- )- energy = self.alpha_convert(alpha_score)- energy = energy - energy.max()- energy_exp = torch.exp(torch.squeeze(energy, -1))-- if image_mask is not None:- energy_exp = energy_exp * torch.squeeze(image_mask, 1)- alpha = energy_exp / (energy_exp.sum(-1).sum(-1)[:,None,None] + 1e-10)- alpha_sum = torch.unsqueeze(alpha, 1) + alpha_sum- context_vector = torch.sum(- torch.sum((torch.unsqueeze(alpha, 1) * cnn_features), -1), -1)-- return context_vector, alpha, alpha_sum---class CANHead(nn.Module):- def __init__(self, in_channel, out_channel, ratio, attdecoder, **kwargs):- super(CANHead, self).__init__()-- self.in_channel = in_channel- self.out_channel = out_channel-- self.counting_decoder1 = CountingDecoder(self.in_channel,- self.out_channel, 3) # mscm- self.counting_decoder2 = CountingDecoder(self.in_channel,- self.out_channel, 5)-- self.decoder = AttDecoder(ratio, **attdecoder)-- self.ratio = ratio-- def forward(self, inputs, targets=None):- cnn_features, images_mask, labels = inputs-- counting_mask = images_mask[:, :, ::self.ratio, ::self.ratio]- counting_preds1, _ = self.counting_decoder1(cnn_features, counting_mask)- counting_preds2, _ = self.counting_decoder2(cnn_features, counting_mask)- counting_preds = (counting_preds1 + counting_preds2) / 2-- word_probs = self.decoder(cnn_features, labels, counting_preds,- images_mask)- return word_probs, counting_preds, counting_preds1, counting_preds2diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_ctc_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_ctc_head.pyold mode 100755new mode 100644index f4f870be..42e2fabb--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_ctc_head.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_ctc_head.py@@ -1,22 +1,24 @@-import os, sys-import torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nn+class CTCHead(nn.Module):- def __init__(self,- in_channels,- out_channels=6625,- fc_decay=0.0004,- mid_channels=None,- return_feats=False,- **kwargs):+ def __init__(+ self,+ in_channels,+ out_channels=6625,+ fc_decay=0.0004,+ mid_channels=None,+ return_feats=False,+ **kwargs+ ):super(CTCHead, self).__init__()if mid_channels is None:self.fc = nn.Linear(in_channels,out_channels,- bias=True,)+ bias=True,+ )else:self.fc1 = nn.Linear(in_channels,@@ -33,7 +35,6 @@ class CTCHead(nn.Module):self.mid_channels = mid_channelsself.return_feats = return_feats-def forward(self, x, labels=None):if self.mid_channels is None:predicts = self.fc(x)@@ -50,4 +51,4 @@ class CTCHead(nn.Module):predicts = F.softmax(predicts, dim=2)result = predicts- return result\ No newline at end of file+ return resultdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_multi_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_multi_head.pyold mode 100755new mode 100644index a79714d9..a4807cbb--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_multi_head.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_multi_head.py@@ -1,10 +1,8 @@-import torch-import torch.nn as nn+from torch import nn-from pytorchocr.modeling.necks.rnn import Im2Seq, SequenceEncoder-from .rec_nrtr_head import Transformer+from ..necks.rnn import Im2Seq, SequenceEncoderfrom .rec_ctc_head import CTCHead-from .rec_sar_head import SARHead+class FCTranspose(nn.Module):def __init__(self, in_channels, out_channels, only_transpose=False):@@ -23,66 +21,38 @@ class FCTranspose(nn.Module):class MultiHead(nn.Module):def __init__(self, in_channels, out_channels_list, **kwargs):super().__init__()- self.head_list = kwargs.pop('head_list')+ self.head_list = kwargs.pop("head_list")- self.gtc_head = 'sar'+ self.gtc_head = "sar"assert len(self.head_list) >= 2for idx, head_name in enumerate(self.head_list):name = list(head_name)[0]- if name == 'SARHead':+ if name == "SARHead":pass- # # sar head- # sar_args = self.head_list[idx][name]- # self.sar_head = eval(name)(in_channels=in_channels, \- # out_channels=out_channels_list['SARLabelDecode'], **sar_args)- elif name == 'NRTRHead':++ elif name == "NRTRHead":pass- # gtc_args = self.head_list[idx][name]- # max_text_length = gtc_args.get('max_text_length', 25)- # nrtr_dim = gtc_args.get('nrtr_dim', 256)- # num_decoder_layers = gtc_args.get('num_decoder_layers', 4)- # self.before_gtc = nn.Sequential(- # nn.Flatten(2), FCTranspose(in_channels, nrtr_dim))- # self.gtc_head = Transformer(- # d_model=nrtr_dim,- # nhead=nrtr_dim // 32,- # num_encoder_layers=-1,- # beam_size=-1,- # num_decoder_layers=num_decoder_layers,- # max_len=max_text_length,- # dim_feedforward=nrtr_dim * 4,- # out_channels=out_channels_list['NRTRLabelDecode'])- elif name == 'CTCHead':+ elif name == "CTCHead":# ctc neckself.encoder_reshape = Im2Seq(in_channels)- neck_args = self.head_list[idx][name]['Neck']- encoder_type = neck_args.pop('name')- self.ctc_encoder = SequenceEncoder(in_channels=in_channels, \- encoder_type=encoder_type, **neck_args)+ neck_args = self.head_list[idx][name]["Neck"]+ encoder_type = neck_args.pop("name")+ self.ctc_encoder = SequenceEncoder(+ in_channels=in_channels, encoder_type=encoder_type, **neck_args+ )# ctc head- head_args = self.head_list[idx][name].get('Head', {})+ head_args = self.head_list[idx][name].get("Head", {})if head_args is None:head_args = {}- self.ctc_head = eval(name)(in_channels=self.ctc_encoder.out_channels, \- out_channels=out_channels_list['CTCLabelDecode'], **head_args)++ self.ctc_head = CTCHead(+ in_channels=self.ctc_encoder.out_channels,+ out_channels=out_channels_list["CTCLabelDecode"],+ **head_args,+ )else:- raise NotImplementedError(- '{} is not supported in MultiHead yet'.format(name))+ raise NotImplementedError(f"{name} is not supported in MultiHead yet")def forward(self, x, data=None):ctc_encoder = self.ctc_encoder(x)- ctc_out = self.ctc_head(ctc_encoder)- head_out = dict()- head_out['ctc'] = ctc_out- head_out['res'] = ctc_out- head_out['ctc_neck'] = ctc_encoder- # eval mode- if not self.training:- return ctc_out- if self.gtc_head == 'sar':- sar_out = self.sar_head(x, data[1:])['res']- head_out['sar'] = sar_out- else:- gtc_out = self.gtc_head(self.before_gtc(x), data[1:])['res']- head_out['nrtr'] = gtc_out- return head_out+ return self.ctc_head(ctc_encoder)diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_nrtr_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_nrtr_head.pydeleted file mode 100755index 13cb09ac..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_nrtr_head.py+++ /dev/null@@ -1,812 +0,0 @@-import math-import torch-import copy-from torch import nn-import torch.nn.functional as F-from torch.nn import ModuleList as LayerList-from torch.nn.init import xavier_uniform_-from torch.nn import Dropout, LayerNorm, Conv2d-import numpy as np-from pytorchocr.modeling.heads.multiheadAttention import MultiheadAttention-from torch.nn.init import xavier_normal_---class Transformer(nn.Module):- """A transformer model. User is able to modify the attributes as needed. The architechture- is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer,- Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and- Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information- Processing Systems, pages 6000-6010.-- Args:- d_model: the number of expected features in the encoder/decoder inputs (default=512).- nhead: the number of heads in the multiheadattention models (default=8).- num_encoder_layers: the number of sub-encoder-layers in the encoder (default=6).- num_decoder_layers: the number of sub-decoder-layers in the decoder (default=6).- dim_feedforward: the dimension of the feedforward network model (default=2048).- dropout: the dropout value (default=0.1).- custom_encoder: custom encoder (default=None).- custom_decoder: custom decoder (default=None).-- """-- def __init__(self,- d_model=512,- nhead=8,- num_encoder_layers=6,- beam_size=0,- num_decoder_layers=6,- max_len=25,- dim_feedforward=1024,- attention_dropout_rate=0.0,- residual_dropout_rate=0.1,- custom_encoder=None,- custom_decoder=None,- in_channels=0,- out_channels=0,- scale_embedding=True):- super(Transformer, self).__init__()- self.out_channels = out_channels # out_channels + 1- self.max_len = max_len- self.embedding = Embeddings(- d_model=d_model,- vocab=self.out_channels,- padding_idx=0,- scale_embedding=scale_embedding)- self.positional_encoding = PositionalEncoding(- dropout=residual_dropout_rate,- dim=d_model, )- if custom_encoder is not None:- self.encoder = custom_encoder- else:- if num_encoder_layers > 0:- encoder_layer = TransformerEncoderLayer(- d_model, nhead, dim_feedforward, attention_dropout_rate,- residual_dropout_rate)- self.encoder = TransformerEncoder(encoder_layer,- num_encoder_layers)- else:- self.encoder = None-- if custom_decoder is not None:- self.decoder = custom_decoder- else:- decoder_layer = TransformerDecoderLayer(- d_model, nhead, dim_feedforward, attention_dropout_rate,- residual_dropout_rate)- self.decoder = TransformerDecoder(decoder_layer, num_decoder_layers)-- self._reset_parameters()- self.beam_size = beam_size- self.d_model = d_model- self.nhead = nhead- self.tgt_word_prj = nn.Linear(- d_model, self.out_channels, bias=False)- w0 = np.random.normal(0.0, d_model ** -0.5,- (self.out_channels, d_model)).astype(np.float32)- self.tgt_word_prj.weight.data = torch.from_numpy(w0)- self.apply(self._init_weights)-- def _init_weights(self, m):-- if isinstance(m, nn.Conv2d):- xavier_normal_(m.weight)- if m.bias is not None:- torch.nn.init.zeros_(m.bias)-- def forward_train(self, src, tgt):- tgt = tgt[:, :-1]-- tgt_key_padding_mask = self.generate_padding_mask(tgt)- tgt = self.embedding(tgt).permute(1, 0, 2)- tgt = self.positional_encoding(tgt)- tgt_mask = self.generate_square_subsequent_mask(tgt.shape[0], tgt.device)-- if self.encoder is not None:- src = self.positional_encoding(src.permute(1, 0, 2))- memory = self.encoder(src)- else:- memory = src.squeeze(2).permute(2, 0, 1)- output = self.decoder(- tgt,- memory,- tgt_mask=tgt_mask,- memory_mask=None,- tgt_key_padding_mask=tgt_key_padding_mask,- memory_key_padding_mask=None)- output = output.permute(1, 0, 2)- logit = self.tgt_word_prj(output)- return logit-- def forward(self, src, targets=None):- """Take in and process masked source/target sequences.- Args:- src: the sequence to the encoder (required).- tgt: the sequence to the decoder (required).- Shape:- - src: :math:`(S, N, E)`.- - tgt: :math:`(T, N, E)`.- Examples:- >>> output = transformer_model(src, tgt)- """-- if self.training:- max_len = targets[1].max()- tgt = targets[0][:, :2 + max_len]- return self.forward_train(src, tgt)- else:- if self.beam_size > 0:- return self.forward_beam(src)- else:- return self.forward_test(src)-- def forward_test(self, src):- bs = src.shape[0]- if self.encoder is not None:- src = self.positional_encoding(src.permute(1, 0, 2))- memory = self.encoder(src)- else:- memory = torch.squeeze(src, 2).permute(2, 0, 1)- dec_seq = torch.full((bs, 1), 2, dtype=torch.int64)- dec_prob = torch.full((bs, 1), 1., dtype=torch.float32)- for len_dec_seq in range(1, 25):- dec_seq_embed = self.embedding(dec_seq).permute(1, 0, 2)- dec_seq_embed = self.positional_encoding(dec_seq_embed)- tgt_mask = self.generate_square_subsequent_mask(- dec_seq_embed.shape[0])- output = self.decoder(- dec_seq_embed,- memory,- tgt_mask=tgt_mask,- memory_mask=None,- tgt_key_padding_mask=None,- memory_key_padding_mask=None)- dec_output = output.permute(1, 0, 2)- dec_output = dec_output[:, -1, :]- tgt_word_prj = self.tgt_word_prj(dec_output)- word_prob = F.softmax(tgt_word_prj, dim=1)- preds_idx = word_prob.argmax(dim=1)- if torch.equal(- preds_idx,- torch.full(- preds_idx.shape, 3, dtype=torch.int64)):- break- preds_prob = torch.max(word_prob, dim=1).values- dec_seq = torch.cat(- [dec_seq, torch.reshape(preds_idx, (-1, 1))], dim=1)- dec_prob = torch.cat(- [dec_prob, torch.reshape(preds_prob, (-1, 1))], dim=1)- return [dec_seq, dec_prob]-- def forward_beam(self, images):- ''' Translation work in one batch '''-- def get_inst_idx_to_tensor_position_map(inst_idx_list):- ''' Indicate the position of an instance in a tensor. '''- return {- inst_idx: tensor_position- for tensor_position, inst_idx in enumerate(inst_idx_list)- }-- def collect_active_part(beamed_tensor, curr_active_inst_idx,- n_prev_active_inst, n_bm):- ''' Collect tensor parts associated to active instances. '''-- beamed_tensor_shape = beamed_tensor.shape- n_curr_active_inst = len(curr_active_inst_idx)- new_shape = (n_curr_active_inst * n_bm, beamed_tensor_shape[1],- beamed_tensor_shape[2])-- beamed_tensor = beamed_tensor.reshape([n_prev_active_inst, -1])- beamed_tensor = beamed_tensor.index_select(- curr_active_inst_idx, axis=0)- beamed_tensor = beamed_tensor.reshape(new_shape)-- return beamed_tensor-- def collate_active_info(src_enc, inst_idx_to_position_map,- active_inst_idx_list):- # Sentences which are still active are collected,- # so the decoder will not run on completed sentences.-- n_prev_active_inst = len(inst_idx_to_position_map)- active_inst_idx = [- inst_idx_to_position_map[k] for k in active_inst_idx_list- ]- active_inst_idx = torch.tensor(active_inst_idx, dtype=torch.int64)- active_src_enc = collect_active_part(- src_enc.permute(1, 0, 2), active_inst_idx,- n_prev_active_inst, n_bm).permute(1, 0, 2)- active_inst_idx_to_position_map = get_inst_idx_to_tensor_position_map(- active_inst_idx_list)- return active_src_enc, active_inst_idx_to_position_map-- def beam_decode_step(inst_dec_beams, len_dec_seq, enc_output,- inst_idx_to_position_map, n_bm,- memory_key_padding_mask):- ''' Decode and update beam status, and then return active beam idx '''-- def prepare_beam_dec_seq(inst_dec_beams, len_dec_seq):- dec_partial_seq = [- b.get_current_state() for b in inst_dec_beams if not b.done- ]- dec_partial_seq = torch.stack(dec_partial_seq)- dec_partial_seq = dec_partial_seq.reshape([-1, len_dec_seq])- return dec_partial_seq-- def predict_word(dec_seq, enc_output, n_active_inst, n_bm,- memory_key_padding_mask):- dec_seq = self.embedding(dec_seq).permute(1, 0, 2)- dec_seq = self.positional_encoding(dec_seq)- tgt_mask = self.generate_square_subsequent_mask(- dec_seq.shape[0])- dec_output = self.decoder(- dec_seq,- enc_output,- tgt_mask=tgt_mask,- tgt_key_padding_mask=None,- memory_key_padding_mask=memory_key_padding_mask, )- dec_output = dec_output.permute(1, 0, 2)- dec_output = dec_output[:,- -1, :] # Pick the last step: (bh * bm) * d_h- word_prob = F.softmax(self.tgt_word_prj(dec_output), dim=1)- word_prob = torch.reshape(word_prob, (n_active_inst, n_bm, -1))- return word_prob-- def collect_active_inst_idx_list(inst_beams, word_prob,- inst_idx_to_position_map):- active_inst_idx_list = []- for inst_idx, inst_position in inst_idx_to_position_map.items():- is_inst_complete = inst_beams[inst_idx].advance(word_prob[- inst_position])- if not is_inst_complete:- active_inst_idx_list += [inst_idx]-- return active_inst_idx_list-- n_active_inst = len(inst_idx_to_position_map)- dec_seq = prepare_beam_dec_seq(inst_dec_beams, len_dec_seq)- word_prob = predict_word(dec_seq, enc_output, n_active_inst, n_bm,- None)- # Update the beam with predicted word prob information and collect incomplete instances- active_inst_idx_list = collect_active_inst_idx_list(- inst_dec_beams, word_prob, inst_idx_to_position_map)- return active_inst_idx_list-- def collect_hypothesis_and_scores(inst_dec_beams, n_best):- all_hyp, all_scores = [], []- for inst_idx in range(len(inst_dec_beams)):- scores, tail_idxs = inst_dec_beams[inst_idx].sort_scores()- all_scores += [scores[:n_best]]- hyps = [- inst_dec_beams[inst_idx].get_hypothesis(i)- for i in tail_idxs[:n_best]- ]- all_hyp += [hyps]- return all_hyp, all_scores-- with torch.no_grad():- #-- Encode- if self.encoder is not None:- src = self.positional_encoding(images.permute(1, 0, 2))- src_enc = self.encoder(src)- else:- src_enc = images.squeeze(2).transpose([0, 2, 1])-- n_bm = self.beam_size- src_shape = src_enc.shape- inst_dec_beams = [Beam(n_bm) for _ in range(1)]- active_inst_idx_list = list(range(1))- # Repeat data for beam search- # src_enc = paddle.tile(src_enc, [1, n_bm, 1])- src_enc = src_enc.repeat(1, n_bm, 1)- inst_idx_to_position_map = get_inst_idx_to_tensor_position_map(- active_inst_idx_list)- # Decode- for len_dec_seq in range(1, 25):- src_enc_copy = src_enc.clone()- active_inst_idx_list = beam_decode_step(- inst_dec_beams, len_dec_seq, src_enc_copy,- inst_idx_to_position_map, n_bm, None)- if not active_inst_idx_list:- break # all instances have finished their path to <EOS>- src_enc, inst_idx_to_position_map = collate_active_info(- src_enc_copy, inst_idx_to_position_map,- active_inst_idx_list)- batch_hyp, batch_scores = collect_hypothesis_and_scores(inst_dec_beams,- 1)- result_hyp = []- hyp_scores = []- for bs_hyp, score in zip(batch_hyp, batch_scores):- l = len(bs_hyp[0])- bs_hyp_pad = bs_hyp[0] + [3] * (25 - l)- result_hyp.append(bs_hyp_pad)- score = float(score) / l- hyp_score = [score for _ in range(25)]- hyp_scores.append(hyp_score)- return [- torch.tensor(- np.array(result_hyp), dtype=torch.int64),- torch.tensor(hyp_scores)- ]-- def generate_square_subsequent_mask(self, sz):- """Generate a square mask for the sequence. The masked positions are filled with float('-inf').- Unmasked positions are filled with float(0.0).- """- mask = torch.zeros([sz, sz], dtype=torch.float32)- mask_inf = torch.triu(- torch.full(- size=[sz, sz], fill_value=float('-Inf'), dtype=torch.float32),- diagonal=1)- mask = mask + mask_inf- return mask-- def generate_padding_mask(self, x):- # padding_mask = paddle.equal(x, paddle.to_tensor(0, dtype=x.dtype))- padding_mask = (x == torch.tensor(0, dtype=x.dtype))- return padding_mask-- def _reset_parameters(self):- """Initiate parameters in the transformer model."""-- for p in self.parameters():- if p.dim() > 1:- xavier_uniform_(p)---class TransformerEncoder(nn.Module):- """TransformerEncoder is a stack of N encoder layers- Args:- encoder_layer: an instance of the TransformerEncoderLayer() class (required).- num_layers: the number of sub-encoder-layers in the encoder (required).- norm: the layer normalization component (optional).- """-- def __init__(self, encoder_layer, num_layers):- super(TransformerEncoder, self).__init__()- self.layers = _get_clones(encoder_layer, num_layers)- self.num_layers = num_layers-- def forward(self, src):- """Pass the input through the endocder layers in turn.- Args:- src: the sequnce to the encoder (required).- mask: the mask for the src sequence (optional).- src_key_padding_mask: the mask for the src keys per batch (optional).- """- output = src-- for i in range(self.num_layers):- output = self.layers[i](output,- src_mask=None,- src_key_padding_mask=None)-- return output---class TransformerDecoder(nn.Module):- """TransformerDecoder is a stack of N decoder layers-- Args:- decoder_layer: an instance of the TransformerDecoderLayer() class (required).- num_layers: the number of sub-decoder-layers in the decoder (required).- norm: the layer normalization component (optional).-- """-- def __init__(self, decoder_layer, num_layers):- super(TransformerDecoder, self).__init__()- self.layers = _get_clones(decoder_layer, num_layers)- self.num_layers = num_layers-- def forward(self,- tgt,- memory,- tgt_mask=None,- memory_mask=None,- tgt_key_padding_mask=None,- memory_key_padding_mask=None):- """Pass the inputs (and mask) through the decoder layer in turn.-- Args:- tgt: the sequence to the decoder (required).- memory: the sequnce from the last layer of the encoder (required).- tgt_mask: the mask for the tgt sequence (optional).- memory_mask: the mask for the memory sequence (optional).- tgt_key_padding_mask: the mask for the tgt keys per batch (optional).- memory_key_padding_mask: the mask for the memory keys per batch (optional).- """- output = tgt- for i in range(self.num_layers):- output = self.layers[i](- output,- memory,- tgt_mask=tgt_mask,- memory_mask=memory_mask,- tgt_key_padding_mask=tgt_key_padding_mask,- memory_key_padding_mask=memory_key_padding_mask)-- return output---class TransformerEncoderLayer(nn.Module):- """TransformerEncoderLayer is made up of self-attn and feedforward network.- This standard encoder layer is based on the paper "Attention Is All You Need".- Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez,- Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in- Neural Information Processing Systems, pages 6000-6010. Users may modify or implement- in a different way during application.-- Args:- d_model: the number of expected features in the input (required).- nhead: the number of heads in the multiheadattention models (required).- dim_feedforward: the dimension of the feedforward network model (default=2048).- dropout: the dropout value (default=0.1).-- """-- def __init__(self,- d_model,- nhead,- dim_feedforward=2048,- attention_dropout_rate=0.0,- residual_dropout_rate=0.1):- super(TransformerEncoderLayer, self).__init__()- self.self_attn = MultiheadAttention(- d_model, nhead, dropout=attention_dropout_rate)-- self.conv1 = nn.Conv2d(- in_channels=d_model,- out_channels=dim_feedforward,- kernel_size=(1, 1))- self.conv2 = nn.Conv2d(- in_channels=dim_feedforward,- out_channels=d_model,- kernel_size=(1, 1))-- self.norm1 = LayerNorm(d_model)- self.norm2 = LayerNorm(d_model)- self.dropout1 = Dropout(residual_dropout_rate)- self.dropout2 = Dropout(residual_dropout_rate)-- def forward(self, src, src_mask=None, src_key_padding_mask=None):- """Pass the input through the endocder layer.- Args:- src: the sequnce to the encoder layer (required).- src_mask: the mask for the src sequence (optional).- src_key_padding_mask: the mask for the src keys per batch (optional).- """- src2 = self.self_attn(- src,- src,- src,- attn_mask=src_mask,- key_padding_mask=src_key_padding_mask)- src = src + self.dropout1(src2)- src = self.norm1(src)-- src = src.permute(1, 2, 0)- src = torch.unsqueeze(src, 2)- src2 = self.conv2(F.relu(self.conv1(src)))- src2 = torch.squeeze(src2, 2)- src2 = src2.permute(2, 0, 1)- src = torch.squeeze(src, 2)- src = src.permute(2, 0, 1)-- src = src + self.dropout2(src2)- src = self.norm2(src)- return src---class TransformerDecoderLayer(nn.Module):- """TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network.- This standard decoder layer is based on the paper "Attention Is All You Need".- Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez,- Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in- Neural Information Processing Systems, pages 6000-6010. Users may modify or implement- in a different way during application.-- Args:- d_model: the number of expected features in the input (required).- nhead: the number of heads in the multiheadattention models (required).- dim_feedforward: the dimension of the feedforward network model (default=2048).- dropout: the dropout value (default=0.1).-- """-- def __init__(self,- d_model,- nhead,- dim_feedforward=2048,- attention_dropout_rate=0.0,- residual_dropout_rate=0.1):- super(TransformerDecoderLayer, self).__init__()- self.self_attn = MultiheadAttention(- d_model, nhead, dropout=attention_dropout_rate)- self.multihead_attn = MultiheadAttention(- d_model, nhead, dropout=attention_dropout_rate)-- self.conv1 = nn.Conv2d(- in_channels=d_model,- out_channels=dim_feedforward,- kernel_size=(1, 1))- self.conv2 = nn.Conv2d(- in_channels=dim_feedforward,- out_channels=d_model,- kernel_size=(1, 1))-- self.norm1 = LayerNorm(d_model)- self.norm2 = LayerNorm(d_model)- self.norm3 = LayerNorm(d_model)- self.dropout1 = Dropout(residual_dropout_rate)- self.dropout2 = Dropout(residual_dropout_rate)- self.dropout3 = Dropout(residual_dropout_rate)-- def forward(self,- tgt,- memory,- tgt_mask=None,- memory_mask=None,- tgt_key_padding_mask=None,- memory_key_padding_mask=None):- """Pass the inputs (and mask) through the decoder layer.-- Args:- tgt: the sequence to the decoder layer (required).- memory: the sequnce from the last layer of the encoder (required).- tgt_mask: the mask for the tgt sequence (optional).- memory_mask: the mask for the memory sequence (optional).- tgt_key_padding_mask: the mask for the tgt keys per batch (optional).- memory_key_padding_mask: the mask for the memory keys per batch (optional).-- """- tgt2 = self.self_attn(- tgt,- tgt,- tgt,- attn_mask=tgt_mask,- key_padding_mask=tgt_key_padding_mask)- tgt = tgt + self.dropout1(tgt2)- tgt = self.norm1(tgt)- tgt2 = self.multihead_attn(- tgt,- memory,- memory,- attn_mask=memory_mask,- key_padding_mask=memory_key_padding_mask)- tgt = tgt + self.dropout2(tgt2)- tgt = self.norm2(tgt)-- # default- tgt = tgt.permute(1, 2, 0)- tgt = torch.unsqueeze(tgt, 2)- tgt2 = self.conv2(F.relu(self.conv1(tgt)))- tgt2 = torch.squeeze(tgt2, 2)- tgt2 = tgt2.permute(2, 0, 1)- tgt = torch.squeeze(tgt, 2)- tgt = tgt.permute(2, 0, 1)-- tgt = tgt + self.dropout3(tgt2)- tgt = self.norm3(tgt)- return tgt---def _get_clones(module, N):- return LayerList([copy.deepcopy(module) for i in range(N)])---class PositionalEncoding(nn.Module):- """Inject some information about the relative or absolute position of the tokens- in the sequence. The positional encodings have the same dimension as- the embeddings, so that the two can be summed. Here, we use sine and cosine- functions of different frequencies.- .. math::- \text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model))- \text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model))- \text{where pos is the word position and i is the embed idx)- Args:- d_model: the embed dim (required).- dropout: the dropout value (default=0.1).- max_len: the max. length of the incoming sequence (default=5000).- Examples:- >>> pos_encoder = PositionalEncoding(d_model)- """-- def __init__(self, dropout, dim, max_len=5000):- super(PositionalEncoding, self).__init__()- self.dropout = nn.Dropout(p=dropout)-- pe = torch.zeros([max_len, dim])- position = torch.arange(0, max_len, dtype=torch.float32).unsqueeze(1)- div_term = torch.exp(- torch.arange(0, dim, 2).type(torch.float32) *- (-math.log(10000.0) / dim))- pe[:, 0::2] = torch.sin(position * div_term)- pe[:, 1::2] = torch.cos(position * div_term)- pe = torch.unsqueeze(pe, 0)- pe = pe.permute(1, 0, 2)- self.register_buffer('pe', pe)-- def forward(self, x):- """Inputs of forward function- Args:- x: the sequence fed to the positional encoder model (required).- Shape:- x: [sequence length, batch size, embed dim]- output: [sequence length, batch size, embed dim]- Examples:- >>> output = pos_encoder(x)- """- x = x + self.pe[:x.shape[0], :]- return self.dropout(x)---class PositionalEncoding_2d(nn.Module):- """Inject some information about the relative or absolute position of the tokens- in the sequence. The positional encodings have the same dimension as- the embeddings, so that the two can be summed. Here, we use sine and cosine- functions of different frequencies.- .. math::- \text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model))- \text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model))- \text{where pos is the word position and i is the embed idx)- Args:- d_model: the embed dim (required).- dropout: the dropout value (default=0.1).- max_len: the max. length of the incoming sequence (default=5000).- Examples:- >>> pos_encoder = PositionalEncoding(d_model)- """-- def __init__(self, dropout, dim, max_len=5000):- super(PositionalEncoding_2d, self).__init__()- self.dropout = nn.Dropout(p=dropout)-- pe = torch.zeros([max_len, dim])- position = torch.arange(0, max_len, dtype=torch.float32).unsqueeze(1)- div_term = torch.exp(- torch.arange(0, dim, 2).type(torch.float32) *- (-math.log(10000.0) / dim))- pe[:, 0::2] = torch.sin(position * div_term)- pe[:, 1::2] = torch.cos(position * div_term)- pe = torch.unsqueeze(pe, 0).permute(1, 0, 2)- self.register_buffer('pe', pe)-- self.avg_pool_1 = nn.AdaptiveAvgPool2d((1, 1))- self.linear1 = nn.Linear(dim, dim)- self.linear1.weight.data.fill_(1.)- self.avg_pool_2 = nn.AdaptiveAvgPool2d((1, 1))- self.linear2 = nn.Linear(dim, dim)- self.linear2.weight.data.fill_(1.)-- def forward(self, x):- """Inputs of forward function- Args:- x: the sequence fed to the positional encoder model (required).- Shape:- x: [sequence length, batch size, embed dim]- output: [sequence length, batch size, embed dim]- Examples:- >>> output = pos_encoder(x)- """- w_pe = self.pe[:x.shape[-1], :]- w1 = self.linear1(self.avg_pool_1(x).squeeze()).unsqueeze(0)- w_pe = w_pe * w1- w_pe = w_pe.permute(1, 2, 0)- w_pe = torch.unsqueeze(w_pe, 2)-- h_pe = self.pe[:x.shape[-2], :]- w2 = self.linear2(self.avg_pool_2(x).squeeze()).unsqueeze(0)- h_pe = h_pe * w2- h_pe = h_pe.permute(1, 2, 0)- h_pe = torch.unsqueeze(h_pe, 3)-- x = x + w_pe + h_pe- x = torch.reshape(- x, [x.shape[0], x.shape[1], x.shape[2] * x.shape[3]]- ).permute(2,0,1)-- return self.dropout(x)---class Embeddings(nn.Module):- def __init__(self, d_model, vocab, padding_idx, scale_embedding):- super(Embeddings, self).__init__()- self.embedding = nn.Embedding(vocab, d_model, padding_idx=padding_idx)- w0 = np.random.normal(0.0, d_model**-0.5,- (vocab, d_model)).astype(np.float32)- self.embedding.weight.data = torch.from_numpy(w0)- self.d_model = d_model- self.scale_embedding = scale_embedding-- def forward(self, x):- if self.scale_embedding:- x = self.embedding(x)- return x * math.sqrt(self.d_model)- return self.embedding(x)---class Beam():- ''' Beam search '''-- def __init__(self, size, device=False):-- self.size = size- self._done = False- # The score for each translation on the beam.- self.scores = torch.zeros((size, ), dtype=torch.float32)- self.all_scores = []- # The backpointers at each time-step.- self.prev_ks = []- # The outputs at each time-step.- self.next_ys = [torch.full((size, ), 0, dtype=torch.int64)]- self.next_ys[0][0] = 2-- def get_current_state(self):- "Get the outputs for the current timestep."- return self.get_tentative_hypothesis()-- def get_current_origin(self):- "Get the backpointers for the current timestep."- return self.prev_ks[-1]-- @property- def done(self):- return self._done-- def advance(self, word_prob):- "Update beam status and check if finished or not."- num_words = word_prob.shape[1]-- # Sum the previous scores.- if len(self.prev_ks) > 0:- beam_lk = word_prob + self.scores.unsqueeze(1).expand_as(word_prob)- else:- beam_lk = word_prob[0]-- flat_beam_lk = beam_lk.reshape([-1])- best_scores, best_scores_id = flat_beam_lk.topk(self.size, 0, True,- True) # 1st sort- self.all_scores.append(self.scores)- self.scores = best_scores- # bestScoresId is flattened as a (beam x word) array,- # so we need to calculate which word and beam each score came from- prev_k = best_scores_id // num_words- self.prev_ks.append(prev_k)- self.next_ys.append(best_scores_id - prev_k * num_words)- # End condition is when top-of-beam is EOS.- if self.next_ys[-1][0] == 3:- self._done = True- self.all_scores.append(self.scores)-- return self._done-- def sort_scores(self):- "Sort the scores."- return self.scores, torch.tensor(- [i for i in range(int(self.scores.shape[0]))], dtype=torch.int32)-- def get_the_best_score_and_idx(self):- "Get the score of the best in the beam."- scores, ids = self.sort_scores()- return scores[1], ids[1]-- def get_tentative_hypothesis(self):- "Get the decoded sequence for the current timestep."- if len(self.next_ys) == 1:- dec_seq = self.next_ys[0].unsqueeze(1)- else:- _, keys = self.sort_scores()- hyps = [self.get_hypothesis(k) for k in keys]- hyps = [[2] + h for h in hyps]- dec_seq = torch.tensor(hyps, dtype=torch.int64)- return dec_seq-- def get_hypothesis(self, k):- """ Walk back to construct the full hypothesis. """- hyp = []- for j in range(len(self.prev_ks) - 1, -1, -1):- hyp.append(self.next_ys[j + 1][k])- k = self.prev_ks[j][k]- return list(map(lambda x: x.item(), hyp[::-1]))diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_sar_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_sar_head.pydeleted file mode 100755index 128081ce..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_sar_head.py+++ /dev/null@@ -1,403 +0,0 @@-"""-This code is refer from:-https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textrecog/encoders/sar_encoder.py-https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textrecog/decoders/sar_decoder.py-"""--from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--# import math-import torch-import torch.nn as nn-import torch.nn.functional as F-# import paddle-# from paddle import ParamAttr-# import paddle.nn as nn-# import paddle.nn.functional as F---class SAREncoder(nn.Module):- """- Args:- enc_bi_rnn (bool): If True, use bidirectional RNN in encoder.- enc_drop_rnn (float): Dropout probability of RNN layer in encoder.- enc_gru (bool): If True, use GRU, else LSTM in encoder.- d_model (int): Dim of channels from backbone.- d_enc (int): Dim of encoder RNN layer.- mask (bool): If True, mask padding in RNN sequence.- """-- def __init__(self,- enc_bi_rnn=False,- enc_drop_rnn=0.0,- enc_gru=False,- d_model=512,- d_enc=512,- mask=True,- **kwargs):- super().__init__()- assert isinstance(enc_bi_rnn, bool)- assert isinstance(enc_drop_rnn, (int, float))- assert 0 <= enc_drop_rnn < 1.0- assert isinstance(enc_gru, bool)- assert isinstance(d_model, int)- assert isinstance(d_enc, int)- assert isinstance(mask, bool)-- self.enc_bi_rnn = enc_bi_rnn- self.enc_drop_rnn = enc_drop_rnn- self.mask = mask-- # LSTM Encoder- # if enc_bi_rnn:- # direction = 'bidirectional'- # else:- # direction = 'forward'- kwargs = dict(- input_size=d_model,- hidden_size=d_enc,- num_layers=2,- batch_first=True,- dropout=enc_drop_rnn,- bidirectional=enc_bi_rnn)- if enc_gru:- self.rnn_encoder = nn.GRU(**kwargs)- else:- self.rnn_encoder = nn.LSTM(**kwargs)-- # global feature transformation- encoder_rnn_out_size = d_enc * (int(enc_bi_rnn) + 1)- self.linear = nn.Linear(encoder_rnn_out_size, encoder_rnn_out_size)-- def forward(self, feat, img_metas=None):- if img_metas is not None:- assert len(img_metas[0]) == feat.size(0)-- valid_ratios = None- if img_metas is not None and self.mask:- valid_ratios = img_metas[-1]-- h_feat = feat.shape[2] # bsz c h w- feat_v = F.max_pool2d(- feat, kernel_size=(h_feat, 1), stride=1, padding=0)- feat_v = feat_v.squeeze(2) # bsz * C * W- feat_v = feat_v.permute(0, 2, 1).contiguous() # bsz * W * C- holistic_feat = self.rnn_encoder(feat_v)[0] # bsz * T * C-- if valid_ratios is not None:- valid_hf = []- T = holistic_feat.size(1)- for i in range(valid_ratios.size(0)):- valid_step = torch.min(T, torch.ceil(T * valid_ratios[i])) - 1- # valid_step = paddle.minimum(- # T, paddle.ceil(valid_ratios[i] * T).astype('int32')) - 1- valid_hf.append(holistic_feat[i, valid_step, :])- valid_hf = torch.stack(valid_hf, dim=0)- else:- valid_hf = holistic_feat[:, -1, :] # bsz * C- holistic_feat = self.linear(valid_hf) # bsz * C-- return holistic_feat---class BaseDecoder(nn.Module):- def __init__(self, **kwargs):- super().__init__()-- def forward_train(self, feat, out_enc, targets, img_metas):- raise NotImplementedError-- def forward_test(self, feat, out_enc, img_metas):- raise NotImplementedError-- def forward(self,- feat,- out_enc,- label=None,- img_metas=None,- train_mode=True):- self.train_mode = train_mode-- if train_mode:- return self.forward_train(feat, out_enc, label, img_metas)- return self.forward_test(feat, out_enc, img_metas)---class ParallelSARDecoder(BaseDecoder):- """- Args:- out_channels (int): Output class number.- enc_bi_rnn (bool): If True, use bidirectional RNN in encoder.- dec_bi_rnn (bool): If True, use bidirectional RNN in decoder.- dec_drop_rnn (float): Dropout of RNN layer in decoder.- dec_gru (bool): If True, use GRU, else LSTM in decoder.- d_model (int): Dim of channels from backbone.- d_enc (int): Dim of encoder RNN layer.- d_k (int): Dim of channels of attention module.- pred_dropout (float): Dropout probability of prediction layer.- max_seq_len (int): Maximum sequence length for decoding.- mask (bool): If True, mask padding in feature map.- start_idx (int): Index of start token.- padding_idx (int): Index of padding token.- pred_concat (bool): If True, concat glimpse feature from- attention with holistic feature and hidden state.- """-- def __init__(- self,- out_channels, # 90 + unknown + start + padding- enc_bi_rnn=False,- dec_bi_rnn=False,- dec_drop_rnn=0.0,- dec_gru=False,- d_model=512,- d_enc=512,- d_k=64,- pred_dropout=0.0,- max_text_length=30,- mask=True,- pred_concat=True,- **kwargs):- super().__init__()-- self.num_classes = out_channels- self.enc_bi_rnn = enc_bi_rnn- self.d_k = d_k- self.start_idx = out_channels - 2- self.padding_idx = out_channels - 1- self.max_seq_len = max_text_length- self.mask = mask- self.pred_concat = pred_concat-- encoder_rnn_out_size = d_enc * (int(enc_bi_rnn) + 1)- decoder_rnn_out_size = encoder_rnn_out_size * (int(dec_bi_rnn) + 1)-- # 2D attention layer- self.conv1x1_1 = nn.Linear(decoder_rnn_out_size, d_k)- self.conv3x3_1 = nn.Conv2d(- d_model, d_k, kernel_size=3, stride=1, padding=1)- self.conv1x1_2 = nn.Linear(d_k, 1)-- # Decoder RNN layer- # if dec_bi_rnn:- # direction = 'bidirectional'- # else:- # direction = 'forward'-- kwargs = dict(- input_size=encoder_rnn_out_size,- hidden_size=encoder_rnn_out_size,- num_layers=2,- batch_first=True,- dropout=dec_drop_rnn,- bidirectional=dec_bi_rnn)- if dec_gru:- self.rnn_decoder = nn.GRU(**kwargs)- else:- self.rnn_decoder = nn.LSTM(**kwargs)-- # Decoder input embedding- self.embedding = nn.Embedding(- self.num_classes,- encoder_rnn_out_size,- padding_idx=self.padding_idx)-- # Prediction layer- self.pred_dropout = nn.Dropout(pred_dropout)- pred_num_classes = self.num_classes - 1- if pred_concat:- fc_in_channel = decoder_rnn_out_size + d_model + encoder_rnn_out_size- else:- fc_in_channel = d_model- self.prediction = nn.Linear(fc_in_channel, pred_num_classes)-- def _2d_attention(self,- decoder_input,- feat,- holistic_feat,- valid_ratios=None):-- y = self.rnn_decoder(decoder_input)[0]- # y: bsz * (seq_len + 1) * hidden_size-- attn_query = self.conv1x1_1(y) # bsz * (seq_len + 1) * attn_size- bsz, seq_len, attn_size = attn_query.shape- # attn_query = paddle.unsqueeze(attn_query, axis=[3, 4])- attn_query = attn_query.view(bsz, seq_len, attn_size, 1, 1)- # attn_query = attn_query.unsqueeze(3).unsqueeze(4)- # (bsz, seq_len + 1, attn_size, 1, 1)-- attn_key = self.conv3x3_1(feat)- # bsz * attn_size * h * w- attn_key = attn_key.unsqueeze(1)- # bsz * 1 * attn_size * h * w-- attn_weight = torch.tanh(torch.add(attn_key, attn_query))-- # bsz * (seq_len + 1) * attn_size * h * w- attn_weight = attn_weight.permute(0, 1, 3, 4, 2).contiguous()- # bsz * (seq_len + 1) * h * w * attn_size- attn_weight = self.conv1x1_2(attn_weight)- # bsz * (seq_len + 1) * h * w * 1- bsz, T, h, w, c = attn_weight.size()- assert c == 1-- if valid_ratios is not None:- # cal mask of attention weight- for i in range(valid_ratios.size(0)):- valid_width = torch.min(w, torch.ceil(w * valid_ratios[i]))- # valid_width = paddle.minimum(- # w, paddle.ceil(valid_ratios[i] * w).astype("int32"))- if valid_width < w:- attn_weight[i, :, :, valid_width:, :] = float('-inf')-- # attn_weight = paddle.reshape(attn_weight, [bsz, T, -1])- attn_weight = attn_weight.view(bsz, T, -1)- attn_weight = F.softmax(attn_weight, dim=-1)-- attn_weight = attn_weight.view(bsz, T, h, w,- c).permute(0, 1, 4, 2, 3).contiguous()- # attn_weight: bsz * T * c * h * w- # feat: bsz * c * h * w- attn_feat = torch.sum(- torch.mul(feat.unsqueeze(1), attn_weight), (3, 4), keepdim=False)- # bsz * (seq_len + 1) * C-- # Linear transformation- if self.pred_concat:- hf_c = holistic_feat.shape[-1]- holistic_feat = holistic_feat.expand(bsz, seq_len, hf_c)- y = self.prediction(torch.cat((y, attn_feat, holistic_feat), 2))- else:- y = self.prediction(attn_feat)- # bsz * (seq_len + 1) * num_classes- if self.train_mode:- y = self.pred_dropout(y)-- return y-- def forward_train(self, feat, out_enc, label, img_metas):- '''- img_metas: [label, valid_ratio]- '''- if img_metas is not None:- assert img_metas[0].size(0) == feat.size(0)-- valid_ratios = None- if img_metas is not None and self.mask:- valid_ratios = img_metas[-1]-- lab_embedding = self.embedding(label)- # bsz * seq_len * emb_dim- out_enc = out_enc.unsqueeze(1)- # bsz * 1 * emb_dim- in_dec = torch.cat((out_enc, lab_embedding), dim=1)- # bsz * (seq_len + 1) * C- out_dec = self._2d_attention(- in_dec, feat, out_enc, valid_ratios=valid_ratios)-- return out_dec[:, 1:, :] # bsz * seq_len * num_classes-- def forward_test(self, feat, out_enc, img_metas):- if img_metas is not None:- assert len(img_metas[0]) == feat.shape[0]-- valid_ratios = None- if img_metas is not None and self.mask:- valid_ratios = img_metas[-1]-- seq_len = self.max_seq_len- bsz = feat.size(0)- start_token = torch.full(- (bsz, ), fill_value=self.start_idx, device=feat.device,dtype=torch.long)- # bsz- start_token = self.embedding(start_token)- # bsz * emb_dim- emb_dim = start_token.shape[1]- # start_token = start_token.unsqueeze(1).expand(-1, seq_len, -1)- start_token = start_token.unsqueeze(1).expand(bsz, seq_len, emb_dim)- # bsz * seq_len * emb_dim- out_enc = out_enc.unsqueeze(1)- # bsz * 1 * emb_dim- decoder_input = torch.cat((out_enc, start_token), dim=1)- # bsz * (seq_len + 1) * emb_dim-- outputs = []- for i in range(1, seq_len + 1):- decoder_output = self._2d_attention(- decoder_input, feat, out_enc, valid_ratios=valid_ratios)- char_output = decoder_output[:, i, :] # bsz * num_classes- char_output = F.softmax(char_output, -1)- outputs.append(char_output)- _, max_idx = torch.max(char_output, dim=1, keepdim=False)- char_embedding = self.embedding(max_idx) # bsz * emb_dim- if i < seq_len:- decoder_input[:, i + 1, :] = char_embedding-- outputs = torch.stack(outputs, 1) # bsz * seq_len * num_classes-- return outputs---class SARHead(nn.Module):- def __init__(self,- in_channels,- out_channels,- enc_dim=512,- max_text_length=30,- enc_bi_rnn=False,- enc_drop_rnn=0.1,- enc_gru=False,- dec_bi_rnn=False,- dec_drop_rnn=0.0,- dec_gru=False,- d_k=512,- pred_dropout=0.1,- pred_concat=True,- **kwargs):- super(SARHead, self).__init__()-- # encoder module- self.encoder = SAREncoder(- enc_bi_rnn=enc_bi_rnn,- enc_drop_rnn=enc_drop_rnn,- enc_gru=enc_gru,- d_model=in_channels,- d_enc=enc_dim)-- # decoder module- self.decoder = ParallelSARDecoder(- out_channels=out_channels,- enc_bi_rnn=enc_bi_rnn,- dec_bi_rnn=dec_bi_rnn,- dec_drop_rnn=dec_drop_rnn,- dec_gru=dec_gru,- d_model=in_channels,- d_enc=enc_dim,- d_k=d_k,- pred_dropout=pred_dropout,- max_text_length=max_text_length,- pred_concat=pred_concat)-- def forward(self, feat, targets=None):- '''- img_metas: [label, valid_ratio]- '''- holistic_feat = self.encoder(feat, targets) # bsz c-- if self.training:- label = targets[0] # label- final_out = self.decoder(- feat, holistic_feat, label, img_metas=targets)- else:- final_out = self.decoder(- feat,- holistic_feat,- label=None,- img_metas=targets,- train_mode=False)- # (bsz, seq_len, num_classes)-- return final_outdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_srn_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_srn_head.pydeleted file mode 100755index 47ebb7cb..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_srn_head.py+++ /dev/null@@ -1,271 +0,0 @@--from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import math-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation-import numpy as np-from .self_attention import WrapEncoderForFeature-from .self_attention import WrapEncoder--from collections import OrderedDict-gradient_clip = 10--# https://forums.fast.ai/t/lambda-layer/28507/5-class Lambda(nn.Module):- "An easy way to create a pytorch layer for a simple `func`."- def __init__(self, func):- "create a layer that simply calls `func` with `x`"- super().__init__()- self.func=func-- def forward(self, x):- return self.func(x)--class PVAM(nn.Module):- def __init__(self, in_channels, char_num, max_text_length, num_heads,- num_encoder_tus, hidden_dims):- super(PVAM, self).__init__()- self.char_num = char_num- self.max_length = max_text_length- self.num_heads = num_heads- self.num_encoder_TUs = num_encoder_tus- self.hidden_dims = hidden_dims- # Transformer encoder- t = 256- c = 512- self.wrap_encoder_for_feature = WrapEncoderForFeature(- src_vocab_size=1,- max_length=t,- n_layer=self.num_encoder_TUs,- n_head=self.num_heads,- d_key=int(self.hidden_dims / self.num_heads),- d_value=int(self.hidden_dims / self.num_heads),- d_model=self.hidden_dims,- d_inner_hid=self.hidden_dims,- prepostprocess_dropout=0.0,#0.1,- attention_dropout=0.0,#0.1,- relu_dropout=0.0,#0.1,- preprocess_cmd="n",- postprocess_cmd="da",- weight_sharing=True)-- # PVAM- self.flatten0 = Lambda(lambda x: torch.flatten(x, start_dim=0, end_dim=1))- self.fc0 = torch.nn.Linear(- in_features=in_channels,- out_features=in_channels, )- self.emb = torch.nn.Embedding(- num_embeddings=self.max_length, embedding_dim=in_channels)- self.flatten1 = Lambda(lambda x: torch.flatten(x, start_dim=0, end_dim=2))- self.fc1 = torch.nn.Linear(- in_features=in_channels, out_features=1, bias=False)-- def forward(self, inputs, encoder_word_pos, gsrm_word_pos):- b, c, h, w = inputs.shape- conv_features = torch.reshape(inputs, shape=[-1, c, h * w])- conv_features = conv_features.permute(0, 2, 1)- # transformer encoder- b, t, c = conv_features.shape-- enc_inputs = [conv_features, encoder_word_pos, None]- word_features = self.wrap_encoder_for_feature(enc_inputs)-- # pvam- b, t, c = word_features.shape- word_features = self.fc0(word_features)- word_features_ = torch.reshape(word_features, [-1, 1, t, c])- word_features_ = word_features_.repeat([1, self.max_length, 1, 1])- word_pos_feature = self.emb(gsrm_word_pos)- word_pos_feature_ = torch.reshape(word_pos_feature,- [-1, self.max_length, 1, c])- word_pos_feature_ = word_pos_feature_.repeat([1, 1, t, 1])- y = word_pos_feature_ + word_features_- y = torch.tanh(y)- attention_weight = self.fc1(y)- attention_weight = torch.reshape(- attention_weight, shape=[-1, self.max_length, t])- attention_weight = F.softmax(attention_weight, dim=-1)- pvam_features = torch.matmul(attention_weight,- word_features) #[b, max_length, c]- return pvam_features---class GSRM(nn.Module):- def __init__(self, in_channels, char_num, max_text_length, num_heads,- num_encoder_tus, num_decoder_tus, hidden_dims):- super(GSRM, self).__init__()- self.char_num = char_num- self.max_length = max_text_length- self.num_heads = num_heads- self.num_encoder_TUs = num_encoder_tus- self.num_decoder_TUs = num_decoder_tus- self.hidden_dims = hidden_dims-- self.fc0 = torch.nn.Linear(- in_features=in_channels, out_features=self.char_num)- self.wrap_encoder0 = WrapEncoder(- src_vocab_size=self.char_num + 1,- max_length=self.max_length,- n_layer=self.num_decoder_TUs,- n_head=self.num_heads,- d_key=int(self.hidden_dims / self.num_heads),- d_value=int(self.hidden_dims / self.num_heads),- d_model=self.hidden_dims,- d_inner_hid=self.hidden_dims,- prepostprocess_dropout=0.0,- attention_dropout=0.0,- relu_dropout=0.0,- preprocess_cmd="n",- postprocess_cmd="da",- weight_sharing=True)-- self.wrap_encoder1 = WrapEncoder(- src_vocab_size=self.char_num + 1,- max_length=self.max_length,- n_layer=self.num_decoder_TUs,- n_head=self.num_heads,- d_key=int(self.hidden_dims / self.num_heads),- d_value=int(self.hidden_dims / self.num_heads),- d_model=self.hidden_dims,- d_inner_hid=self.hidden_dims,- prepostprocess_dropout=0.0,- attention_dropout=0.0,- relu_dropout=0.0,- preprocess_cmd="n",- postprocess_cmd="da",- weight_sharing=True)-- self.mul = lambda x: torch.matmul(x,- self.wrap_encoder0.prepare_decoder.emb0.weight.t(),- )-- def forward(self, inputs, gsrm_word_pos, gsrm_slf_attn_bias1,- gsrm_slf_attn_bias2):- # ===== GSRM Visual-to-semantic embedding block =====- b, t, c = inputs.shape- pvam_features = torch.reshape(inputs, [-1, c])- word_out = self.fc0(pvam_features)- word_ids = torch.argmax(F.softmax(word_out, dim=-1), dim=1)- word_ids = torch.reshape(word_ids, shape=[-1, t, 1])-- #===== GSRM Semantic reasoning block =====- """- This module is achieved through bi-transformers,- ngram_feature1 is the froward one, ngram_fetaure2 is the backward one- """- pad_idx = self.char_num- word1 = F.pad(word_ids.type(torch.float32), [0, 0, 1, 0, 0, 0], value=1.0 * pad_idx)- word1 = word1.type(torch.int64)- word1 = word1[:, :-1, :]- word2 = word_ids-- enc_inputs_1 = [word1, gsrm_word_pos, gsrm_slf_attn_bias1]- enc_inputs_2 = [word2, gsrm_word_pos, gsrm_slf_attn_bias2]-- gsrm_feature1 = self.wrap_encoder0(enc_inputs_1)- gsrm_feature2 = self.wrap_encoder1(enc_inputs_2)-- gsrm_feature2 = F.pad(gsrm_feature2, [0, 0, 0, 1, 0, 0],- value=0.,- )- gsrm_feature2 = gsrm_feature2[:, 1:, ]- gsrm_features = gsrm_feature1 + gsrm_feature2-- gsrm_out = self.mul(gsrm_features)-- b, t, c = gsrm_out.shape- gsrm_out = torch.reshape(gsrm_out, [-1, c])-- return gsrm_features, word_out, gsrm_out---class VSFD(nn.Module):- def __init__(self, in_channels=512, pvam_ch=512, char_num=38):- super(VSFD, self).__init__()- self.char_num = char_num- self.fc0 = torch.nn.Linear(- in_features=in_channels * 2, out_features=pvam_ch)- self.fc1 = torch.nn.Linear(- in_features=pvam_ch, out_features=self.char_num)-- def forward(self, pvam_feature, gsrm_feature):- b, t, c1 = pvam_feature.shape- b, t, c2 = gsrm_feature.shape- combine_feature_ = torch.cat([pvam_feature, gsrm_feature], dim=2)- img_comb_feature_ = torch.reshape(- combine_feature_, shape=[-1, c1 + c2])- img_comb_feature_map = self.fc0(img_comb_feature_)- img_comb_feature_map = torch.sigmoid(img_comb_feature_map)- img_comb_feature_map = torch.reshape(- img_comb_feature_map, shape=[-1, t, c1])- combine_feature = img_comb_feature_map * pvam_feature + (- 1.0 - img_comb_feature_map) * gsrm_feature- img_comb_feature = torch.reshape(combine_feature, shape=[-1, c1])-- out = self.fc1(img_comb_feature)- return out---class SRNHead(nn.Module):- def __init__(self, in_channels, out_channels, max_text_length, num_heads,- num_encoder_TUs, num_decoder_TUs, hidden_dims, **kwargs):- super(SRNHead, self).__init__()- self.char_num = out_channels- self.max_length = max_text_length- self.num_heads = num_heads- self.num_encoder_TUs = num_encoder_TUs- self.num_decoder_TUs = num_decoder_TUs- self.hidden_dims = hidden_dims-- self.pvam = PVAM(- in_channels=in_channels,- char_num=self.char_num,- max_text_length=self.max_length,- num_heads=self.num_heads,- num_encoder_tus=self.num_encoder_TUs,- hidden_dims=self.hidden_dims)-- self.gsrm = GSRM(- in_channels=in_channels,- char_num=self.char_num,- max_text_length=self.max_length,- num_heads=self.num_heads,- num_encoder_tus=self.num_encoder_TUs,- num_decoder_tus=self.num_decoder_TUs,- hidden_dims=self.hidden_dims)- self.vsfd = VSFD(in_channels=in_channels, char_num=self.char_num)-- self.gsrm.wrap_encoder1.prepare_decoder.emb0 = self.gsrm.wrap_encoder0.prepare_decoder.emb0-- def forward(self, inputs, others):- encoder_word_pos = others[0]- gsrm_word_pos = others[1].type(torch.long)- gsrm_slf_attn_bias1 = others[2]- gsrm_slf_attn_bias2 = others[3]-- pvam_feature = self.pvam(inputs, encoder_word_pos, gsrm_word_pos)-- gsrm_feature, word_out, gsrm_out = self.gsrm(- pvam_feature, gsrm_word_pos, gsrm_slf_attn_bias1,- gsrm_slf_attn_bias2)-- final_out = self.vsfd(pvam_feature, gsrm_feature)- if not self.training:- final_out = F.softmax(final_out, dim=1)-- _, decoded_out = torch.topk(final_out, k=1)-- predicts = OrderedDict([- ('predict', final_out),- ('pvam_feature', pvam_feature),- ('decoded_out', decoded_out),- ('word_out', word_out),- ('gsrm_out', gsrm_out),- ])-- return predictsdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/self_attention.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/self_attention.pydeleted file mode 100755index 3d37c604..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/self_attention.py+++ /dev/null@@ -1,419 +0,0 @@--from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import math--import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation-import numpy as np-gradient_clip = 10---class WrapEncoderForFeature(nn.Module):- def __init__(self,- src_vocab_size,- max_length,- n_layer,- n_head,- d_key,- d_value,- d_model,- d_inner_hid,- prepostprocess_dropout,- attention_dropout,- relu_dropout,- preprocess_cmd,- postprocess_cmd,- weight_sharing,- bos_idx=0):- super(WrapEncoderForFeature, self).__init__()-- self.prepare_encoder = PrepareEncoder(- src_vocab_size,- d_model,- max_length,- prepostprocess_dropout,- bos_idx=bos_idx,- word_emb_param_name="src_word_emb_table")- self.encoder = Encoder(n_layer, n_head, d_key, d_value, d_model,- d_inner_hid, prepostprocess_dropout,- attention_dropout, relu_dropout, preprocess_cmd,- postprocess_cmd)-- def forward(self, enc_inputs):- conv_features, src_pos, src_slf_attn_bias = enc_inputs- enc_input = self.prepare_encoder(conv_features, src_pos)- enc_output = self.encoder(enc_input, src_slf_attn_bias)- return enc_output---class WrapEncoder(nn.Module):- """- embedder + encoder- """-- def __init__(self,- src_vocab_size,- max_length,- n_layer,- n_head,- d_key,- d_value,- d_model,- d_inner_hid,- prepostprocess_dropout,- attention_dropout,- relu_dropout,- preprocess_cmd,- postprocess_cmd,- weight_sharing,- bos_idx=0):- super(WrapEncoder, self).__init__()-- self.prepare_decoder = PrepareDecoder(- src_vocab_size,- d_model,- max_length,- prepostprocess_dropout,- bos_idx=bos_idx)- self.encoder = Encoder(n_layer, n_head, d_key, d_value, d_model,- d_inner_hid, prepostprocess_dropout,- attention_dropout, relu_dropout, preprocess_cmd,- postprocess_cmd)-- def forward(self, enc_inputs):- src_word, src_pos, src_slf_attn_bias = enc_inputs- enc_input = self.prepare_decoder(src_word, src_pos)- enc_output = self.encoder(enc_input, src_slf_attn_bias)- return enc_output---class Encoder(nn.Module):- """- encoder- """-- def __init__(self,- n_layer,- n_head,- d_key,- d_value,- d_model,- d_inner_hid,- prepostprocess_dropout,- attention_dropout,- relu_dropout,- preprocess_cmd="n",- postprocess_cmd="da"):-- super(Encoder, self).__init__()-- self.encoder_layers = nn.ModuleList()- for i in range(n_layer):- encoderLayer = EncoderLayer(n_head, d_key, d_value, d_model, d_inner_hid,- prepostprocess_dropout, attention_dropout,- relu_dropout, preprocess_cmd,- postprocess_cmd)- self.encoder_layers.add_module("layer_%d" % i, encoderLayer)- self.processer = PrePostProcessLayer(preprocess_cmd, d_model,- prepostprocess_dropout)-- def forward(self, enc_input, attn_bias):- for encoder_layer in self.encoder_layers:- enc_output = encoder_layer(enc_input, attn_bias)- enc_input = enc_output- enc_output = self.processer(enc_output)-- return enc_output---class EncoderLayer(nn.Module):- """- EncoderLayer- """-- def __init__(self,- n_head,- d_key,- d_value,- d_model,- d_inner_hid,- prepostprocess_dropout,- attention_dropout,- relu_dropout,- preprocess_cmd="n",- postprocess_cmd="da"):-- super(EncoderLayer, self).__init__()- self.preprocesser1 = PrePostProcessLayer(preprocess_cmd, d_model,- prepostprocess_dropout)- self.self_attn = MultiHeadAttention(d_key, d_value, d_model, n_head,- attention_dropout)- self.postprocesser1 = PrePostProcessLayer(postprocess_cmd, d_model,- prepostprocess_dropout)-- self.preprocesser2 = PrePostProcessLayer(preprocess_cmd, d_model,- prepostprocess_dropout)- self.ffn = FFN(d_inner_hid, d_model, relu_dropout)- self.postprocesser2 = PrePostProcessLayer(postprocess_cmd, d_model,- prepostprocess_dropout)-- def forward(self, enc_input, attn_bias):- attn_output = self.self_attn(- self.preprocesser1(enc_input), None, None, attn_bias)- attn_output = self.postprocesser1(attn_output, enc_input)- ffn_output = self.ffn(self.preprocesser2(attn_output))- ffn_output = self.postprocesser2(ffn_output, attn_output)- return ffn_output---class MultiHeadAttention(nn.Module):- """- Multi-Head Attention- """-- def __init__(self, d_key, d_value, d_model, n_head=1, dropout_rate=0.):- super(MultiHeadAttention, self).__init__()- self.n_head = n_head- self.d_key = d_key- self.d_value = d_value- self.d_model = d_model- self.dropout_rate = dropout_rate- self.q_fc = torch.nn.Linear(- in_features=d_model, out_features=d_key * n_head, bias=False)- self.k_fc = torch.nn.Linear(- in_features=d_model, out_features=d_key * n_head, bias=False)- self.v_fc = torch.nn.Linear(- in_features=d_model, out_features=d_value * n_head, bias=False)- self.proj_fc = torch.nn.Linear(- in_features=d_value * n_head, out_features=d_model, bias=False)-- def _prepare_qkv(self, queries, keys, values, cache=None):- if keys is None: # self-attention- keys, values = queries, queries- static_kv = False- else: # cross-attention- static_kv = True-- q = self.q_fc(queries)- q = torch.reshape(q, shape=[q.size(0), q.size(1), self.n_head, self.d_key])- q = q.permute(0, 2, 1, 3)-- if cache is not None and static_kv and "static_k" in cache:- # for encoder-decoder attention in inference and has cached- k = cache["static_k"]- v = cache["static_v"]- else:- k = self.k_fc(keys)- v = self.v_fc(values)- k = torch.reshape(k, shape=[k.size(0), k.size(1), self.n_head, self.d_key])- k = k.permute(0, 2, 1, 3)- v = torch.reshape(v, shape=[v.size(0), v.size(1), self.n_head, self.d_value])- v = v.permute(0, 2, 1, 3)-- if cache is not None:- if static_kv and not "static_k" in cache:- # for encoder-decoder attention in inference and has not cached- cache["static_k"], cache["static_v"] = k, v- elif not static_kv:- # for decoder self-attention in inference- cache_k, cache_v = cache["k"], cache["v"]- k = torch.cat([cache_k, k], dim=2)- v = torch.cat([cache_v, v], dim=2)- cache["k"], cache["v"] = k, v-- return q, k, v-- def forward(self, queries, keys, values, attn_bias, cache=None):- # compute q ,k ,v- keys = queries if keys is None else keys- values = keys if values is None else values- q, k, v = self._prepare_qkv(queries, keys, values, cache)-- # scale dot product attention- product = torch.matmul(q, k.transpose(2, 3))- product = product * self.d_model**-0.5- if attn_bias is not None:- product += attn_bias- weights = F.softmax(product, dim=-1)- if self.dropout_rate:- weights = F.dropout(- weights, p=self.dropout_rate)- out = torch.matmul(weights, v)-- # combine heads- out = out.permute(0, 2, 1, 3)- out = torch.reshape(out, shape=[out.size(0), out.size(1), out.shape[2] * out.shape[3]])-- # project to output- out = self.proj_fc(out)-- return out---# https://forums.fast.ai/t/lambda-layer/28507/5-class Lambda(nn.Module):- "An easy way to create a pytorch layer for a simple `func`."- def __init__(self, func):- "create a layer that simply calls `func` with `x`"- super().__init__()- self.func=func-- def forward(self, x):- return self.func(x)--class LambdaXY(nn.Module):- "An easy way to create a pytorch layer for a simple `func`."- def __init__(self, func):- "create a layer that simply calls `func` with `x`"- super().__init__()- self.func=func-- def forward(self, x, y):- return self.func(x, y)---class PrePostProcessLayer(nn.Module):- """- PrePostProcessLayer- """-- def __init__(self, process_cmd, d_model, dropout_rate):- super(PrePostProcessLayer, self).__init__()- self.process_cmd = process_cmd- self.functors = nn.ModuleList()- cur_a_len = 0- cur_n_len = 0- cur_d_len = 0- for cmd in self.process_cmd:- if cmd == "a": # add residual connection- self.functors.add_module('add_res_connect_{}'.format(cur_a_len), LambdaXY(lambda x, y: x + y if y is not None else x))- cur_a_len += 1- elif cmd == "n": # add layer normalization- layerNorm = torch.nn.LayerNorm(normalized_shape=d_model,- elementwise_affine=True,- eps=1e-5)- self.functors.add_module("layer_norm_%d" % cur_n_len,- layerNorm)- cur_n_len += 1--- elif cmd == "d": # add dropout- self.functors.add_module('add_drop_{}'.format(cur_d_len),- Lambda(lambda x: F.dropout(- x, p=dropout_rate)- if dropout_rate else x)- )- cur_d_len += 1-- def forward(self, x, residual=None):- for i, (cmd, functor) in enumerate(zip(self.process_cmd, self.functors)):- if cmd == "a":- x = functor(x, residual)- else:- x = functor(x)-- return x---class PrepareEncoder(nn.Module):- def __init__(self,- src_vocab_size,- src_emb_dim,- src_max_len,- dropout_rate=0,- bos_idx=0,- word_emb_param_name=None,- pos_enc_param_name=None):- super(PrepareEncoder, self).__init__()- self.src_emb_dim = src_emb_dim- self.src_max_len = src_max_len- self.emb = torch.nn.Embedding(- num_embeddings=self.src_max_len,- embedding_dim=self.src_emb_dim,- sparse=True,- )- self.dropout_rate = dropout_rate-- def forward(self, src_word, src_pos):- src_word_emb = src_word.type(torch.float32)- src_word_emb = self.src_emb_dim**0.5 * src_word_emb- src_pos = torch.squeeze(src_pos, dim=-1)- src_pos_enc = self.emb(src_pos.type(torch.int64))- src_pos_enc.stop_gradient = True- enc_input = src_word_emb + src_pos_enc- if self.dropout_rate:- out = F.dropout(- enc_input, p=self.dropout_rate)- else:- out = enc_input- return out---class PrepareDecoder(nn.Module):- def __init__(self,- src_vocab_size,- src_emb_dim,- src_max_len,- dropout_rate=0,- bos_idx=0,- word_emb_param_name=None,- pos_enc_param_name=None):- super(PrepareDecoder, self).__init__()- self.src_emb_dim = src_emb_dim- """- self.emb0 = Embedding(num_embeddings=src_vocab_size,- embedding_dim=src_emb_dim)- """- self.emb0 = torch.nn.Embedding(- num_embeddings=src_vocab_size,- embedding_dim=self.src_emb_dim,- padding_idx=bos_idx,- )- self.emb1 = torch.nn.Embedding(- num_embeddings=src_max_len,- embedding_dim=self.src_emb_dim,- )- self.dropout_rate = dropout_rate-- def forward(self, src_word, src_pos):- src_word = torch.squeeze(src_word.type(torch.int64), dim=-1)- src_word_emb = self.emb0(src_word)- src_word_emb = self.src_emb_dim**0.5 * src_word_emb- src_pos = torch.squeeze(src_pos, dim=-1)- src_pos_enc = self.emb1(src_pos)- src_pos_enc.stop_gradient = True- enc_input = src_word_emb + src_pos_enc- if self.dropout_rate:- out = F.dropout(- enc_input, p=self.dropout_rate)- else:- out = enc_input- return out---class FFN(nn.Module):- """- Feed-Forward Network- """-- def __init__(self, d_inner_hid, d_model, dropout_rate):- super(FFN, self).__init__()- self.dropout_rate = dropout_rate- self.fc1 = torch.nn.Linear(- in_features=d_model, out_features=d_inner_hid)- self.fc2 = torch.nn.Linear(- in_features=d_inner_hid, out_features=d_model)-- def forward(self, x):- hidden = self.fc1(x)- hidden = F.relu(hidden)- if self.dropout_rate:- hidden = F.dropout(- hidden, p=self.dropout_rate)- out = self.fc2(hidden)- return outdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/sr_rensnet_transformer.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/sr_rensnet_transformer.pydeleted file mode 100755index 92d93d92..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/sr_rensnet_transformer.py+++ /dev/null@@ -1,419 +0,0 @@-# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.-"""-This code is refer from:-https://github.com/FudanVI/FudanOCR/blob/main/text-gestalt/loss/transformer_english_decomposition.py-"""-import copy-import math-import numpy as np-import torch-import torch.nn as nn-import torch.nn.functional as F---def subsequent_mask(size):- """Generate a square mask for the sequence. The masked positions are filled with float('-inf').- Unmasked positions are filled with float(0.0).- """- mask = torch.ones(1, size, size, dtype=torch.float32)- mask_inf = torch.triu(- torch.full(- size=[1, size, size], fill_value=-np.inf, dtype=torch.float32),- diagonal=1)- mask = mask + mask_inf- padding_mask = torch.equal(mask, torch.Tensor(1).type(mask.dtype))- return padding_mask----def clones(module, N):- return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])---def attention(query, key, value, mask=None, dropout=None, attention_map=None):- d_k = query.shape[-1]- scores = torch.matmul(query,- key.transpose(-2, -1)) / math.sqrt(d_k)-- if mask is not None:- scores = scores.masked_fill(mask == 0, float('-inf'))- else:- pass-- p_attn = F.softmax(scores, dim=-1)-- if dropout is not None:- p_attn = dropout(p_attn)- return torch.matmul(p_attn, value), p_attn---class MultiHeadedAttention(nn.Module):- def __init__(self, h, d_model, dropout=0.1, compress_attention=False):- super(MultiHeadedAttention, self).__init__()- assert d_model % h == 0- self.d_k = d_model // h- self.h = h- self.linears = clones(nn.Linear(d_model, d_model), 4)- self.attn = None- self.dropout = nn.Dropout(p=dropout)- self.compress_attention = compress_attention- self.compress_attention_linear = nn.Linear(h, 1)-- def forward(self, query, key, value, mask=None, attention_map=None):- if mask is not None:- mask = mask.unsqueeze(1)- nbatches = query.size(0)-- query, key, value = \- [l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)- for l, x in zip(self.linears, (query, key, value))]-- x, attention_map = attention(- query,- key,- value,- mask=mask,- dropout=self.dropout,- attention_map=attention_map)-- x = x.transpose(1, 2).contiguous().view(nbatches, -1, self.h * self.d_k)-- return self.linears[-1](x), attention_map---class ResNet(nn.Module):- def __init__(self, num_in, block, layers):- super(ResNet, self).__init__()-- self.conv1 = nn.Conv2d(num_in, 64, kernel_size=3, stride=1, padding=1)- self.bn1 = nn.BatchNorm2d(64)- self.relu1 = nn.ReLU(inplace=True)- self.pool = nn.MaxPool2d((2, 2), (2, 2))-- self.conv2 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)- self.bn2 = nn.BatchNorm2d(128)- self.relu2 = nn.ReLU(inplace=True)-- self.layer1_pool = nn.MaxPool2d((2, 2), (2, 2))- self.layer1 = self._make_layer(block, 128, 256, layers[0])- self.layer1_conv = nn.Conv2d(256, 256, 3, 1, 1)- self.layer1_bn = nn.BatchNorm2d(256)- self.layer1_relu = nn.ReLU(inplace=True)-- self.layer2_pool = nn.MaxPool2d((2, 2), (2, 2))- self.layer2 = self._make_layer(block, 256, 256, layers[1])- self.layer2_conv = nn.Conv2d(256, 256, 3, 1, 1)- self.layer2_bn = nn.BatchNorm2d(256)- self.layer2_relu = nn.ReLU(inplace=True)-- self.layer3_pool = nn.MaxPool2d((2, 2), (2, 2))- self.layer3 = self._make_layer(block, 256, 512, layers[2])- self.layer3_conv = nn.Conv2d(512, 512, 3, 1, 1)- self.layer3_bn = nn.BatchNorm2d(512)- self.layer3_relu = nn.ReLU(inplace=True)-- self.layer4_pool = nn.MaxPool2d((2, 2), (2, 2))- self.layer4 = self._make_layer(block, 512, 512, layers[3])- self.layer4_conv2 = nn.Conv2d(512, 1024, 3, 1, 1)- self.layer4_conv2_bn = nn.BatchNorm2d(1024)- self.layer4_conv2_relu = nn.ReLU(inplace=True)-- def _make_layer(self, block, inplanes, planes, blocks):-- if inplanes != planes:- downsample = nn.Sequential(- nn.Conv2d(inplanes, planes, 3, 1, 1),- nn.BatchNorm2d(- planes), )- else:- downsample = None- layers = []- layers.append(block(inplanes, planes, downsample))- for i in range(1, blocks):- layers.append(block(planes, planes, downsample=None))-- return nn.Sequential(*layers)-- def forward(self, x):- x = self.conv1(x)- x = self.bn1(x)- x = self.relu1(x)- x = self.pool(x)-- x = self.conv2(x)- x = self.bn2(x)- x = self.relu2(x)-- x = self.layer1_pool(x)- x = self.layer1(x)- x = self.layer1_conv(x)- x = self.layer1_bn(x)- x = self.layer1_relu(x)-- x = self.layer2(x)- x = self.layer2_conv(x)- x = self.layer2_bn(x)- x = self.layer2_relu(x)-- x = self.layer3(x)- x = self.layer3_conv(x)- x = self.layer3_bn(x)- x = self.layer3_relu(x)-- x = self.layer4(x)- x = self.layer4_conv2(x)- x = self.layer4_conv2_bn(x)- x = self.layer4_conv2_relu(x)-- return x---class Bottleneck(nn.Module):- def __init__(self, input_dim):- super(Bottleneck, self).__init__()- self.conv1 = nn.Conv2d(input_dim, input_dim, 1)- self.bn1 = nn.BatchNorm2d(input_dim)- self.relu = nn.ReLU()-- self.conv2 = nn.Conv2d(input_dim, input_dim, 3, 1, 1)- self.bn2 = nn.BatchNorm2d(input_dim)-- 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)-- out += residual- out = self.relu(out)-- return out---class PositionalEncoding(nn.Module):- "Implement the PE function."-- def __init__(self, dropout, dim, max_len=5000):- super(PositionalEncoding, self).__init__()- self.dropout = nn.Dropout(p=dropout)-- pe = torch.zeros(max_len, dim)- position = torch.arange(0, max_len).unsqueeze(1).float()- div_term = torch.exp(- torch.arange(0, dim, 2).float() *- (-math.log(10000.0) / dim))- pe[:, 0::2] = torch.sin(position * div_term)- pe[:, 1::2] = torch.cos(position * div_term)- pe = pe.unsqueeze(0)- self.register_buffer('pe', pe)-- def forward(self, x):- x = x + self.pe[:, :x.size(1)]- return self.dropout(x)---class PositionwiseFeedForward(nn.Module):- "Implements FFN equation."-- def __init__(self, d_model, d_ff, dropout=0.1):- super(PositionwiseFeedForward, self).__init__()- self.w_1 = nn.Linear(d_model, d_ff)- self.w_2 = nn.Linear(d_ff, d_model)- self.dropout = nn.Dropout(dropout)-- def forward(self, x):- return self.w_2(self.dropout(F.relu(self.w_1(x))))---class Generator(nn.Module):- "Define standard linear + softmax generation step."-- def __init__(self, d_model, vocab):- super(Generator, self).__init__()- self.proj = nn.Linear(d_model, vocab)- self.relu = nn.ReLU()-- def forward(self, x):- out = self.proj(x)- return out---class Embeddings(nn.Module):- def __init__(self, d_model, vocab):- super(Embeddings, self).__init__()- self.lut = nn.Embedding(vocab, d_model)- self.d_model = d_model-- def forward(self, x):- embed = self.lut(x) * math.sqrt(self.d_model)- return embed---class LayerNorm(nn.Module):- "Construct a layernorm module (See citation for details)."-- def __init__(self, features, eps=1e-6):- super(LayerNorm, self).__init__()- self.a_2 = nn.parameter.Parameter(torch.ones(features))- self.b_2 = nn.parameter.Parameter(torch.zeros(features))- self.eps = eps-- def forward(self, x):- mean = x.mean(-1, keepdim=True)- std = x.std(-1, keepdim=True)- return self.a_2 * (x - mean) / (std + self.eps) + self.b_2---class Decoder(nn.Module):- def __init__(self):- super(Decoder, self).__init__()-- self.mask_multihead = MultiHeadedAttention(- h=16, d_model=1024, dropout=0.1)- self.mul_layernorm1 = LayerNorm(1024)-- self.multihead = MultiHeadedAttention(h=16, d_model=1024, dropout=0.1)- self.mul_layernorm2 = LayerNorm(1024)-- self.pff = PositionwiseFeedForward(1024, 2048)- self.mul_layernorm3 = LayerNorm(1024)-- def forward(self, text, conv_feature, attention_map=None):- text_max_length = text.shape[1]- mask = subsequent_mask(text_max_length)- result = text- result = self.mul_layernorm1(result + self.mask_multihead(- text, text, text, mask=mask)[0])- b, c, h, w = conv_feature.shape- conv_feature = conv_feature.view(b, c, h * w).permute(0, 2, 1).contiguous()- word_image_align, attention_map = self.multihead(- result,- conv_feature,- conv_feature,- mask=None,- attention_map=attention_map)- result = self.mul_layernorm2(result + word_image_align)- result = self.mul_layernorm3(result + self.pff(result))-- return result, attention_map---class BasicBlock(nn.Module):- def __init__(self, inplanes, planes, downsample):- super(BasicBlock, self).__init__()- self.conv1 = nn.Conv2d(- inplanes, planes, kernel_size=3, stride=1, padding=1)- self.bn1 = nn.BatchNorm2d(planes)- self.relu = nn.ReLU()- self.conv2 = nn.Conv2d(- planes, planes, kernel_size=3, stride=1, padding=1)- self.bn2 = nn.BatchNorm2d(planes)- self.downsample = downsample-- 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 != None:- residual = self.downsample(residual)-- out += residual- out = self.relu(out)-- return out---class Encoder(nn.Module):- def __init__(self):- super(Encoder, self).__init__()- self.cnn = ResNet(num_in=1, block=BasicBlock, layers=[1, 2, 5, 3])-- def forward(self, input):- conv_result = self.cnn(input)- return conv_result---class Transformer(nn.Module):- def __init__(self, in_channels=1, alphabet='0123456789'):- super(Transformer, self).__init__()- self.alphabet = alphabet- word_n_class = self.get_alphabet_len()- self.embedding_word_with_upperword = Embeddings(512, word_n_class)- self.pe = PositionalEncoding(dim=512, dropout=0.1, max_len=5000)-- self.encoder = Encoder()- self.decoder = Decoder()- self.generator_word_with_upperword = Generator(1024, word_n_class)-- for p in self.parameters():- if p.dim() > 1:- nn.init.xavier_uniform_(p)-- def get_alphabet_len(self):- return len(self.alphabet)-- def forward(self, image, text_length, text_input, attention_map=None):- if image.shape[1] == 3:- R = image[:, 0:1, :, :]- G = image[:, 1:2, :, :]- B = image[:, 2:3, :, :]- image = 0.299 * R + 0.587 * G + 0.114 * B-- conv_feature = self.encoder(image) # batch, 1024, 8, 32- max_length = max(text_length)- text_input = text_input[:, :max_length]-- text_embedding = self.embedding_word_with_upperword(- text_input) # batch, text_max_length, 512- if torch.cuda.is_available():- postion_embedding = self.pe(- torch.zeros(text_embedding.shape).cuda()).cuda()- else:- postion_embedding = self.pe(- torch.zeros(text_embedding.shape)) # batch, text_max_length, 512- text_input_with_pe = torch.cat([text_embedding, postion_embedding], 2) # batch, text_max_length, 1024- batch, seq_len, _ = text_input_with_pe.shape-- text_input_with_pe, word_attention_map = self.decoder(- text_input_with_pe, conv_feature)-- word_decoder_result = self.generator_word_with_upperword(- text_input_with_pe)-- if self.training:- total_length = torch.sum(text_length).data- probs_res = torch.zeros([total_length, self.get_alphabet_len()]).type_as(word_decoder_result.data)- start = 0-- for index, length in enumerate(text_length):- length = int(length.numpy())- probs_res[start:start + length, :] = word_decoder_result[- index, 0:0 + length, :]-- start = start + length-- return probs_res, word_attention_map, None- else:- return word_decoder_resultdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/table_att_head.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/table_att_head.pydeleted file mode 100755index a2a97ee4..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/table_att_head.py+++ /dev/null@@ -1,207 +0,0 @@-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import torch-import torch.nn as nn-import torch.nn.functional as F-import numpy as np---class TableAttentionHead(nn.Module):- def __init__(self, in_channels, hidden_size, loc_type, in_max_len=488, **kwargs):- super(TableAttentionHead, self).__init__()- self.input_size = in_channels[-1]- self.hidden_size = hidden_size- self.elem_num = 30- self.max_text_length = 100- self.max_elem_length = kwargs.get('max_elem_length', 500)- self.max_cell_num = 500-- self.structure_attention_cell = AttentionGRUCell(- self.input_size, hidden_size, self.elem_num, use_gru=False)- self.structure_generator = nn.Linear(hidden_size, self.elem_num)- self.loc_type = loc_type- self.in_max_len = in_max_len-- if self.loc_type == 1:- self.loc_generator = nn.Linear(hidden_size, 4)- else:- if self.in_max_len == 640:- self.loc_fea_trans = nn.Linear(400, self.max_elem_length + 1)- elif self.in_max_len == 800:- self.loc_fea_trans = nn.Linear(625, self.max_elem_length + 1)- else:- self.loc_fea_trans = nn.Linear(256, self.max_elem_length + 1)- self.loc_generator = nn.Linear(self.input_size + hidden_size, 4)-- def _char_to_onehot(self, input_char, onehot_dim):- input_ont_hot = F.one_hot(input_char.type(torch.int64), onehot_dim)- return input_ont_hot-- def forward(self, inputs, targets=None):- # if and else branch are both needed when you want to assign a variable- # if you modify the var in just one branch, then the modification will not work.- fea = inputs[-1]- if len(fea.shape) == 3:- pass- else:- last_shape = int(np.prod(fea.shape[2:])) # gry added- fea = torch.reshape(fea, [fea.shape[0], fea.shape[1], last_shape])- # fea = fea.transpose([0, 2, 1]) # (NTC)(batch, width, channels)- fea = fea.permute(0, 2, 1)- batch_size = fea.shape[0]-- hidden = torch.zeros((batch_size, self.hidden_size))- output_hiddens = []- if self.training and targets is not None:- raise NotImplementedError- else:- temp_elem = torch.zeros([batch_size], dtype=torch.int32)- structure_probs = None- loc_preds = None- elem_onehots = None- outputs = None- alpha = None- max_elem_length = torch.as_tensor(self.max_elem_length)- i = 0- while i < max_elem_length + 1:- elem_onehots = self._char_to_onehot(- temp_elem, onehot_dim=self.elem_num)- (outputs, hidden), alpha = self.structure_attention_cell(- hidden, fea, elem_onehots)- output_hiddens.append(torch.unsqueeze(outputs, dim=1))- structure_probs_step = self.structure_generator(outputs)- temp_elem = structure_probs_step.argmax(dim=1, keepdim=False)- i += 1-- output = torch.cat(output_hiddens, dim=1)- structure_probs = self.structure_generator(output)- structure_probs = F.softmax(structure_probs, dim=-1)- if self.loc_type == 1:- loc_preds = self.loc_generator(output)- loc_preds = F.sigmoid(loc_preds)- else:- loc_fea = fea.permute(0, 2, 1)- loc_fea = self.loc_fea_trans(loc_fea)- loc_fea = loc_fea.permute(0, 2, 1)- loc_concat = torch.cat([output, loc_fea], dim=2)- loc_preds = self.loc_generator(loc_concat)- loc_preds = F.sigmoid(loc_preds)- return {'structure_probs': structure_probs, 'loc_preds': loc_preds}---class AttentionGRUCell(nn.Module):- def __init__(self, input_size, hidden_size, num_embeddings, use_gru=False):- super(AttentionGRUCell, self).__init__()- self.i2h = nn.Linear(input_size, hidden_size, bias=False)- self.h2h = nn.Linear(hidden_size, hidden_size)- self.score = nn.Linear(hidden_size, 1, bias=False)- self.rnn = nn.GRUCell(- input_size=input_size + num_embeddings, hidden_size=hidden_size)- self.hidden_size = hidden_size-- def forward(self, prev_hidden, batch_H, char_onehots):- batch_H_proj = self.i2h(batch_H)- prev_hidden_proj = torch.unsqueeze(self.h2h(prev_hidden), dim=1)- res = torch.add(batch_H_proj, prev_hidden_proj)- res = torch.tanh(res)- e = self.score(res)- alpha = F.softmax(e, dim=1)- alpha = alpha.permute(0, 2, 1)- context = torch.squeeze(torch.matmul(alpha, batch_H), dim=1)- concat_context = torch.cat([context, char_onehots.float()], 1)- cur_hidden = self.rnn(concat_context, prev_hidden)- return (cur_hidden, cur_hidden), alpha---class AttentionLSTM(nn.Module):- def __init__(self, in_channels, out_channels, hidden_size, **kwargs):- super(AttentionLSTM, self).__init__()- self.input_size = in_channels- self.hidden_size = hidden_size- self.num_classes = out_channels-- self.attention_cell = AttentionLSTMCell(- in_channels, hidden_size, out_channels, use_gru=False)- self.generator = nn.Linear(hidden_size, out_channels)-- def _char_to_onehot(self, input_char, onehot_dim):- input_ont_hot = F.one_hot(input_char, onehot_dim)- return input_ont_hot-- def forward(self, inputs, targets=None, batch_max_length=25):- batch_size = inputs.shape[0]- num_steps = batch_max_length-- hidden = (torch.zeros((batch_size, self.hidden_size)), torch.zeros(- (batch_size, self.hidden_size)))- output_hiddens = []-- if targets is not None:- for i in range(num_steps):- # one-hot vectors for a i-th char- char_onehots = self._char_to_onehot(- targets[:, i], onehot_dim=self.num_classes)- hidden, alpha = self.attention_cell(hidden, inputs,- char_onehots)-- hidden = (hidden[1][0], hidden[1][1])- output_hiddens.append(torch.unsqueeze(hidden[0], dim=1))- output = torch.cat(output_hiddens, dim=1)- probs = self.generator(output)-- else:- targets = torch.zeros([batch_size], dtype=torch.int32)- probs = None-- for i in range(num_steps):- char_onehots = self._char_to_onehot(- targets, onehot_dim=self.num_classes)- hidden, alpha = self.attention_cell(hidden, inputs,- char_onehots)- probs_step = self.generator(hidden[0])- hidden = (hidden[1][0], hidden[1][1])- if probs is None:- probs = torch.unsqueeze(probs_step, dim=1)- else:- probs = torch.cat(- [probs, torch.unsqueeze(- probs_step, dim=1)], dim=1)-- next_input = probs_step.argmax(dim=1)-- targets = next_input-- return probs---class AttentionLSTMCell(nn.Module):- def __init__(self, input_size, hidden_size, num_embeddings, use_gru=False):- super(AttentionLSTMCell, self).__init__()- self.i2h = nn.Linear(input_size, hidden_size, bias=False)- self.h2h = nn.Linear(hidden_size, hidden_size)- self.score = nn.Linear(hidden_size, 1, bias=False)- if not use_gru:- self.rnn = nn.LSTMCell(- input_size=input_size + num_embeddings, hidden_size=hidden_size)- else:- self.rnn = nn.GRUCell(- input_size=input_size + num_embeddings, hidden_size=hidden_size)-- self.hidden_size = hidden_size-- def forward(self, prev_hidden, batch_H, char_onehots):- batch_H_proj = self.i2h(batch_H)- prev_hidden_proj = torch.unsqueeze(self.h2h(prev_hidden[0]), dim=1)- res = torch.add(batch_H_proj, prev_hidden_proj)- res = torch.tanh(res)- e = self.score(res)-- alpha = F.softmax(e, dim=1)- alpha = alpha.permute(0, 2, 1)- context = torch.squeeze(torch.matmul(alpha, batch_H), dim=1)- concat_context = torch.cat([context, char_onehots.float()], 1)- cur_hidden = self.rnn(concat_context, prev_hidden)-- return (cur_hidden, cur_hidden), alpha\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/__init__.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/__init__.pyold mode 100755new mode 100644index e5258101..bbe85bc6--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/__init__.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/__init__.py@@ -12,22 +12,18 @@# See the License for the specific language governing permissions and# limitations under the License.-__all__ = ['build_neck']+__all__ = ["build_neck"]+def build_neck(config):- from .db_fpn import DBFPN, RSEFPN, LKPAN- from .east_fpn import EASTFPN- from .sast_fpn import SASTFPN+ from .db_fpn import DBFPN, LKPAN, RSEFPNfrom .rnn import SequenceEncoder- from .pg_fpn import PGFPN- from .fpn import FPN- from .fce_fpn import FCEFPN- from .table_fpn import TableFPN- support_dict = ['FPN', 'DBFPN', 'EASTFPN', 'SASTFPN', 'SequenceEncoder', 'PGFPN', 'TableFPN',- 'RSEFPN', 'LKPAN', 'FCEFPN']- module_name = config.pop('name')- assert module_name in support_dict, Exception('neck only support {}'.format(- support_dict))+ support_dict = ["DBFPN", "SequenceEncoder", "RSEFPN", "LKPAN"]++ module_name = config.pop("name")+ assert module_name in support_dict, Exception(+ "neck only support {}".format(support_dict)+ )module_class = eval(module_name)(**config)- return module_class\ No newline at end of file+ return module_classdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/db_fpn.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/db_fpn.pyold mode 100755new mode 100644index 34ef9582..9c8460a2--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/db_fpn.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/db_fpn.py@@ -1,24 +1,28 @@-import os, sysimport torch-import torch.nn as nnimport torch.nn.functional as F-from pytorchocr.modeling.backbones.det_mobilenet_v3 import SEModule-from pytorchocr.modeling.necks.intracl import IntraCLBlock+from torch import nn++from ..backbones.det_mobilenet_v3 import SEModule+from ..necks.intracl import IntraCLBlock+def hard_swish(x, inplace=True):- return x * F.relu6(x + 3., inplace=inplace) / 6.+ return x * F.relu6(x + 3.0, inplace=inplace) / 6.0+class DSConv(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- padding,- stride=1,- groups=None,- if_act=True,- act="relu",- **kwargs):+ def __init__(+ self,+ in_channels,+ out_channels,+ kernel_size,+ padding,+ stride=1,+ groups=None,+ if_act=True,+ act="relu",+ **kwargs+ ):super(DSConv, self).__init__()if groups == None:groups = in_channels@@ -31,7 +35,8 @@ class DSConv(nn.Module):stride=stride,padding=padding,groups=groups,- bias=False)+ bias=False,+ )self.bn1 = nn.BatchNorm2d(in_channels)@@ -40,7 +45,8 @@ class DSConv(nn.Module):out_channels=int(in_channels * 4),kernel_size=1,stride=1,- bias=False)+ bias=False,+ )self.bn2 = nn.BatchNorm2d(int(in_channels * 4))@@ -49,7 +55,8 @@ class DSConv(nn.Module):out_channels=out_channels,kernel_size=1,stride=1,- bias=False)+ bias=False,+ )self._c = [in_channels, out_channels]if in_channels != out_channels:self.conv_end = nn.Conv2d(@@ -57,10 +64,10 @@ class DSConv(nn.Module):out_channels=out_channels,kernel_size=1,stride=1,- bias=False)+ bias=False,+ )def forward(self, inputs):-x = self.conv1(inputs)x = self.bn1(x)@@ -72,8 +79,11 @@ class DSConv(nn.Module):elif self.act == "hardswish":x = hard_swish(x)else:- print("The activation function({}) is selected incorrectly.".- format(self.act))+ print(+ "The activation function({}) is selected incorrectly.".format(+ self.act+ )+ )exit()x = self.conv3(x)@@ -92,46 +102,54 @@ class DBFPN(nn.Module):in_channels=in_channels[0],out_channels=self.out_channels,kernel_size=1,- bias=False)+ bias=False,+ )self.in3_conv = nn.Conv2d(in_channels=in_channels[1],out_channels=self.out_channels,kernel_size=1,- bias=False)+ bias=False,+ )self.in4_conv = nn.Conv2d(in_channels=in_channels[2],out_channels=self.out_channels,kernel_size=1,- bias=False)+ bias=False,+ )self.in5_conv = nn.Conv2d(in_channels=in_channels[3],out_channels=self.out_channels,kernel_size=1,- bias=False)+ bias=False,+ )self.p5_conv = nn.Conv2d(in_channels=self.out_channels,out_channels=self.out_channels // 4,kernel_size=3,padding=1,- bias=False)+ bias=False,+ )self.p4_conv = nn.Conv2d(in_channels=self.out_channels,out_channels=self.out_channels // 4,kernel_size=3,padding=1,- bias=False)+ bias=False,+ )self.p3_conv = nn.Conv2d(in_channels=self.out_channels,out_channels=self.out_channels // 4,kernel_size=3,padding=1,- bias=False)+ bias=False,+ )self.p2_conv = nn.Conv2d(in_channels=self.out_channels,out_channels=self.out_channels // 4,kernel_size=3,padding=1,- bias=False)+ bias=False,+ )if self.use_asf is True:self.asf = ASFBlock(self.out_channels, self.out_channels // 4)@@ -145,19 +163,40 @@ class DBFPN(nn.Module):in2 = self.in2_conv(c2)out4 = in4 + F.interpolate(- in5, scale_factor=2, mode="nearest", )#align_mode=1) # 1/16+ in5,+ scale_factor=2,+ mode="nearest",+ ) # align_mode=1) # 1/16out3 = in3 + F.interpolate(- out4, scale_factor=2, mode="nearest", )#align_mode=1) # 1/8+ out4,+ scale_factor=2,+ mode="nearest",+ ) # align_mode=1) # 1/8out2 = in2 + F.interpolate(- out3, scale_factor=2, mode="nearest", )#align_mode=1) # 1/4+ out3,+ scale_factor=2,+ mode="nearest",+ ) # align_mode=1) # 1/4p5 = self.p5_conv(in5)p4 = self.p4_conv(out4)p3 = self.p3_conv(out3)p2 = self.p2_conv(out2)- p5 = F.interpolate(p5, scale_factor=8, mode="nearest", )#align_mode=1)- p4 = F.interpolate(p4, scale_factor=4, mode="nearest", )#align_mode=1)- p3 = F.interpolate(p3, scale_factor=2, mode="nearest", )#align_mode=1)+ p5 = F.interpolate(+ p5,+ scale_factor=8,+ mode="nearest",+ ) # align_mode=1)+ p4 = F.interpolate(+ p4,+ scale_factor=4,+ mode="nearest",+ ) # align_mode=1)+ p3 = F.interpolate(+ p3,+ scale_factor=2,+ mode="nearest",+ ) # align_mode=1)fuse = torch.cat([p5, p4, p3, p2], dim=1)@@ -176,7 +215,8 @@ class RSELayer(nn.Module):out_channels=self.out_channels,kernel_size=kernel_size,padding=int(kernel_size // 2),- bias=False)+ bias=False,+ )self.se_block = SEModule(self.out_channels)self.shortcut = shortcut@@ -196,8 +236,8 @@ class RSEFPN(nn.Module):self.ins_conv = nn.ModuleList()self.inp_conv = nn.ModuleList()self.intracl = False- if 'intracl' in kwargs.keys() and kwargs['intracl'] is True:- self.intracl = kwargs['intracl']+ if "intracl" in kwargs.keys() and kwargs["intracl"] is True:+ self.intracl = kwargs["intracl"]self.incl1 = IntraCLBlock(self.out_channels // 4, reduce_factor=2)self.incl2 = IntraCLBlock(self.out_channels // 4, reduce_factor=2)self.incl3 = IntraCLBlock(self.out_channels // 4, reduce_factor=2)@@ -205,17 +245,13 @@ class RSEFPN(nn.Module):for i in range(len(in_channels)):self.ins_conv.append(- RSELayer(- in_channels[i],- out_channels,- kernel_size=1,- shortcut=shortcut))+ RSELayer(in_channels[i], out_channels, kernel_size=1, shortcut=shortcut)+ )self.inp_conv.append(RSELayer(- out_channels,- out_channels // 4,- kernel_size=3,- shortcut=shortcut))+ out_channels, out_channels // 4, kernel_size=3, shortcut=shortcut+ )+ )def forward(self, x):c2, c3, c4, c5 = x@@ -225,12 +261,9 @@ class RSEFPN(nn.Module):in3 = self.ins_conv[1](c3)in2 = self.ins_conv[0](c2)- out4 = in4 + F.interpolate(- in5, scale_factor=2, mode="nearest") # 1/16- out3 = in3 + F.interpolate(- out4, scale_factor=2, mode="nearest") # 1/8- out2 = in2 + F.interpolate(- out3, scale_factor=2, mode="nearest") # 1/4+ out4 = in4 + F.interpolate(in5, scale_factor=2, mode="nearest") # 1/16+ out3 = in3 + F.interpolate(out4, scale_factor=2, mode="nearest") # 1/8+ out2 = in2 + F.interpolate(out3, scale_factor=2, mode="nearest") # 1/4p5 = self.inp_conv[3](in5)p4 = self.inp_conv[2](out4)@@ -252,7 +285,7 @@ class RSEFPN(nn.Module):class LKPAN(nn.Module):- def __init__(self, in_channels, out_channels, mode='large', **kwargs):+ def __init__(self, in_channels, out_channels, mode="large", **kwargs):super(LKPAN, self).__init__()self.out_channels = out_channels@@ -262,14 +295,16 @@ class LKPAN(nn.Module):self.pan_head_conv = nn.ModuleList()self.pan_lat_conv = nn.ModuleList()- if mode.lower() == 'lite':+ if mode.lower() == "lite":p_layer = DSConv- elif mode.lower() == 'large':+ elif mode.lower() == "large":p_layer = nn.Conv2delse:raise ValueError(- "mode can only be one of ['lite', 'large'], but received {}".- format(mode))+ "mode can only be one of ['lite', 'large'], but received {}".format(+ mode+ )+ )for i in range(len(in_channels)):self.ins_conv.append(@@ -277,7 +312,9 @@ class LKPAN(nn.Module):in_channels=in_channels[i],out_channels=self.out_channels,kernel_size=1,- bias=False))+ bias=False,+ )+ )self.inp_conv.append(p_layer(@@ -285,7 +322,9 @@ class LKPAN(nn.Module):out_channels=self.out_channels // 4,kernel_size=9,padding=4,- bias=False))+ bias=False,+ )+ )if i > 0:self.pan_head_conv.append(@@ -295,17 +334,21 @@ class LKPAN(nn.Module):kernel_size=3,padding=1,stride=2,- bias=False))+ bias=False,+ )+ )self.pan_lat_conv.append(p_layer(in_channels=self.out_channels // 4,out_channels=self.out_channels // 4,kernel_size=9,padding=4,- bias=False))+ bias=False,+ )+ )self.intracl = False- if 'intracl' in kwargs.keys() and kwargs['intracl'] is True:- self.intracl = kwargs['intracl']+ if "intracl" in kwargs.keys() and kwargs["intracl"] is True:+ self.intracl = kwargs["intracl"]self.incl1 = IntraCLBlock(self.out_channels // 4, reduce_factor=2)self.incl2 = IntraCLBlock(self.out_channels // 4, reduce_factor=2)self.incl3 = IntraCLBlock(self.out_channels // 4, reduce_factor=2)@@ -319,12 +362,9 @@ class LKPAN(nn.Module):in3 = self.ins_conv[1](c3)in2 = self.ins_conv[0](c2)- out4 = in4 + F.interpolate(- in5, scale_factor=2, mode="nearest") # 1/16- out3 = in3 + F.interpolate(- out4, scale_factor=2, mode="nearest") # 1/8- out2 = in2 + F.interpolate(- out3, scale_factor=2, mode="nearest") # 1/4+ out4 = in4 + F.interpolate(in5, scale_factor=2, mode="nearest") # 1/16+ out3 = in3 + F.interpolate(out4, scale_factor=2, mode="nearest") # 1/8+ out2 = in2 + F.interpolate(out3, scale_factor=2, mode="nearest") # 1/4f5 = self.inp_conv[3](in5)f4 = self.inp_conv[2](out4)@@ -375,22 +415,23 @@ class ASFBlock(nn.Module):self.conv = nn.Conv2d(in_channels, inter_channels, 3, padding=1)self.spatial_scale = nn.Sequential(- #Nx1xHxW+ # Nx1xHxWnn.Conv2d(in_channels=1,out_channels=1,kernel_size=3,bias=False,padding=1,- ),+ ),nn.ReLU(),nn.Conv2d(in_channels=1,out_channels=1,kernel_size=1,bias=False,- ),- nn.Sigmoid())+ ),+ nn.Sigmoid(),+ )self.channel_scale = nn.Sequential(nn.Conv2d(@@ -398,8 +439,9 @@ class ASFBlock(nn.Module):out_channels=out_features_num,kernel_size=1,bias=False,- ),- nn.Sigmoid())+ ),+ nn.Sigmoid(),+ )def forward(self, fuse_features, features_list):fuse_features = self.conv(fuse_features)@@ -410,5 +452,5 @@ class ASFBlock(nn.Module):out_list = []for i in range(self.out_features_num):- out_list.append(attention_scores[:, i:i + 1] * features_list[i])+ out_list.append(attention_scores[:, i : i + 1] * features_list[i])return torch.cat(out_list, dim=1)diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/east_fpn.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/east_fpn.pydeleted file mode 100755index e5fdac4e..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/east_fpn.py+++ /dev/null@@ -1,184 +0,0 @@-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import os, sys-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation-# import paddle-# from paddle import nn-# import paddle.nn.functional as F-# from paddle import ParamAttr---class ConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride,- padding,- groups=1,- if_act=True,- act=None,- name=None):- super(ConvBNLayer, self).__init__()- self.if_act = if_act- self.act = act-- self.conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=padding,- groups=groups,- bias=False)-- self.bn = nn.BatchNorm2d(- out_channels,)- self.act = act- if act is not None:- self._act = Activation(act)-- def forward(self, x):- x = self.conv(x)- x = self.bn(x)- if self.act is not None:- x = self._act(x)- return x---class DeConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride,- padding,- groups=1,- if_act=True,- act=None,- name=None):- super(DeConvBNLayer, self).__init__()- self.if_act = if_act- self.act = act-- self.deconv = nn.ConvTranspose2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=padding,- groups=groups,- bias=False)- self.bn = nn.BatchNorm2d(- out_channels,- )- self.act = act- if act is not None:- self._act = Activation(act)--- def forward(self, x):- x = self.deconv(x)- x = self.bn(x)- if self.act is not None:- x = self._act(x)- return x---class EASTFPN(nn.Module):- def __init__(self, in_channels, model_name, **kwargs):- super(EASTFPN, self).__init__()- self.model_name = model_name- if self.model_name == "large":- self.out_channels = 128- else:- self.out_channels = 64- self.in_channels = in_channels[::-1]- self.h1_conv = ConvBNLayer(- in_channels=self.out_channels+self.in_channels[1],- out_channels=self.out_channels,- kernel_size=3,- stride=1,- padding=1,- if_act=True,- act='relu',- name="unet_h_1")- self.h2_conv = ConvBNLayer(- in_channels=self.out_channels+self.in_channels[2],- out_channels=self.out_channels,- kernel_size=3,- stride=1,- padding=1,- if_act=True,- act='relu',- name="unet_h_2")- self.h3_conv = ConvBNLayer(- in_channels=self.out_channels+self.in_channels[3],- out_channels=self.out_channels,- kernel_size=3,- stride=1,- padding=1,- if_act=True,- act='relu',- name="unet_h_3")- self.g0_deconv = DeConvBNLayer(- in_channels=self.in_channels[0],- out_channels=self.out_channels,- kernel_size=4,- stride=2,- padding=1,- if_act=True,- act='relu',- name="unet_g_0")- self.g1_deconv = DeConvBNLayer(- in_channels=self.out_channels,- out_channels=self.out_channels,- kernel_size=4,- stride=2,- padding=1,- if_act=True,- act='relu',- name="unet_g_1")- self.g2_deconv = DeConvBNLayer(- in_channels=self.out_channels,- out_channels=self.out_channels,- kernel_size=4,- stride=2,- padding=1,- if_act=True,- act='relu',- name="unet_g_2")- self.g3_conv = ConvBNLayer(- in_channels=self.out_channels,- out_channels=self.out_channels,- kernel_size=3,- stride=1,- padding=1,- if_act=True,- act='relu',- name="unet_g_3")-- def forward(self, x):- f = x[::-1]-- h = f[0]- g = self.g0_deconv(h)- # h = paddle.concat([g, f[1]], axis=1)- h = torch.cat([g, f[1]], dim=1)- h = self.h1_conv(h)- g = self.g1_deconv(h)- # h = paddle.concat([g, f[2]], axis=1)- h = torch.cat([g, f[2]], dim=1)- h = self.h2_conv(h)- g = self.g2_deconv(h)- # h = paddle.concat([g, f[3]], axis=1)- h = torch.cat([g, f[3]], dim=1)- h = self.h3_conv(h)- g = self.g3_conv(h)-- return g\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/fce_fpn.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/fce_fpn.pydeleted file mode 100755index 8111c9b0..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/fce_fpn.py+++ /dev/null@@ -1,323 +0,0 @@-"""-This code is refer from:-https://github.com/PaddlePaddle/PaddleDetection/blob/release/2.3/ppdet/modeling/necks/fpn.py-"""--import torch-import torch.nn as nn-import torch.nn.functional as F-from torch.nn.init import xavier_normal_-from torch.nn.init import xavier_uniform_-# import paddle.nn as nn-# import paddle.nn.functional as F-# from paddle import ParamAttr-# from paddle.nn.initializer import XavierUniform-# from paddle.nn.initializer import Normal-# from paddle.regularizer import L2Decay--__all__ = ['FCEFPN']---class ConvNormLayer(nn.Module):- def __init__(self,- ch_in,- ch_out,- filter_size,- stride,- groups=1,- norm_type='bn',- norm_decay=0.,- norm_groups=32,- lr_scale=1.,- freeze_norm=False,- initializer=None):- super(ConvNormLayer, self).__init__()- assert norm_type in ['bn', 'sync_bn', 'gn']-- bias_attr = False-- self.conv = nn.Conv2d(- in_channels=ch_in,- out_channels=ch_out,- kernel_size=filter_size,- stride=stride,- padding=(filter_size - 1) // 2,- groups=groups,- bias=bias_attr)-- norm_lr = 0. if freeze_norm else 1.- # param_attr = ParamAttr(- # learning_rate=norm_lr,- # regularizer=L2Decay(norm_decay) if norm_decay is not None else None)- # bias_attr = ParamAttr(- # learning_rate=norm_lr,- # regularizer=L2Decay(norm_decay) if norm_decay is not None else None)- if norm_type == 'bn':- self.norm = nn.BatchNorm2d(- ch_out,- )- elif norm_type == 'sync_bn':- self.norm = nn.SyncBatchNorm(- ch_out,- )- elif norm_type == 'gn':- self.norm = nn.GroupNorm(- num_groups=norm_groups,- num_channels=ch_out,- affine=bias_attr)-- def forward(self, inputs):- out = self.conv(inputs)- out = self.norm(out)- return out---class FCEFPN(nn.Module):- """- Feature Pyramid Network, see https://arxiv.org/abs/1612.03144- Args:- in_channels (list[int]): input channels of each level which can be- derived from the output shape of backbone by from_config- out_channels (list[int]): output channel of each level- spatial_scales (list[float]): the spatial scales between input feature- maps and original input image which can be derived from the output- shape of backbone by from_config- has_extra_convs (bool): whether to add extra conv to the last level.- default False- extra_stage (int): the number of extra stages added to the last level.- default 1- use_c5 (bool): Whether to use c5 as the input of extra stage,- otherwise p5 is used. default True- norm_type (string|None): The normalization type in FPN module. If- norm_type is None, norm will not be used after conv and if- norm_type is string, bn, gn, sync_bn are available. default None- norm_decay (float): weight decay for normalization layer weights.- default 0.- freeze_norm (bool): whether to freeze normalization layer.- default False- relu_before_extra_convs (bool): whether to add relu before extra convs.- default False-- """-- def __init__(self,- in_channels,- out_channels,- spatial_scales=[0.25, 0.125, 0.0625, 0.03125],- has_extra_convs=False,- extra_stage=1,- use_c5=True,- norm_type=None,- norm_decay=0.,- freeze_norm=False,- relu_before_extra_convs=True):- super(FCEFPN, self).__init__()- self.out_channels = out_channels- for s in range(extra_stage):- spatial_scales = spatial_scales + [spatial_scales[-1] / 2.]- self.spatial_scales = spatial_scales- self.has_extra_convs = has_extra_convs- self.extra_stage = extra_stage- self.use_c5 = use_c5- self.relu_before_extra_convs = relu_before_extra_convs- self.norm_type = norm_type- self.norm_decay = norm_decay- self.freeze_norm = freeze_norm-- self.lateral_convs = []#nn.ModuleList()- self.lateral_convs_module = nn.ModuleList()- self.fpn_convs = []#nn.ModuleList()- self.fpn_convs_module = nn.ModuleList()- fan = out_channels * 3 * 3-- # stage index 0,1,2,3 stands for res2,res3,res4,res5 on ResNet Backbone- # 0 <= st_stage < ed_stage <= 3- st_stage = 4 - len(in_channels)- ed_stage = st_stage + len(in_channels) - 1- for i in range(st_stage, ed_stage + 1):- if i == 3:- lateral_name = 'fpn_inner_res5_sum'- else:- lateral_name = 'fpn_inner_res{}_sum_lateral'.format(i + 2)- in_c = in_channels[i - st_stage]- if self.norm_type is not None:- # self.lateral_convs_module.add_module(- # lateral_name,- # ConvNormLayer(- # ch_in=in_c,- # ch_out=out_channels,- # filter_size=1,- # stride=1,- # norm_type=self.norm_type,- # norm_decay=self.norm_decay,- # freeze_norm=self.freeze_norm,- # initializer=None))- lateral = ConvNormLayer(- ch_in=in_c,- ch_out=out_channels,- filter_size=1,- stride=1,- norm_type=self.norm_type,- norm_decay=self.norm_decay,- freeze_norm=self.freeze_norm,- initializer=None)- else:- # self.lateral_convs_module.add_module(- # lateral_name,- # nn.Conv2d(- # in_channels=in_c,- # out_channels=out_channels,- # kernel_size=1,- # )- # )- lateral = nn.Conv2d(- in_channels=in_c,- out_channels=out_channels,- kernel_size=1,- )- self.lateral_convs_module.add_module(lateral_name, lateral)- self.lateral_convs.append(lateral)-- for i in range(st_stage, ed_stage + 1):- fpn_name = 'fpn_res{}_sum'.format(i + 2)- fpn_conv_module = nn.Sequential()- if self.norm_type is not None:- # fpn_conv_module.add_module(- # fpn_name,- # ConvNormLayer(- # ch_in=out_channels,- # ch_out=out_channels,- # filter_size=3,- # stride=1,- # norm_type=self.norm_type,- # norm_decay=self.norm_decay,- # freeze_norm=self.freeze_norm,- # initializer=None))- fpn_conv = ConvNormLayer(- ch_in=out_channels,- ch_out=out_channels,- filter_size=3,- stride=1,- norm_type=self.norm_type,- norm_decay=self.norm_decay,- freeze_norm=self.freeze_norm,- initializer=None)- else:- # fpn_conv_module.add_module(- # fpn_name,- # nn.Conv2d(- # in_channels=out_channels,- # out_channels=out_channels,- # kernel_size=3,- # padding=1,- # )- # )- fpn_conv = nn.Conv2d(- in_channels=out_channels,- out_channels=out_channels,- kernel_size=3,- padding=1,- )- self.fpn_convs_module.add_module(fpn_name, fpn_conv)- self.fpn_convs.append(fpn_conv)-- # add extra conv levels for RetinaNet(use_c5)/FCOS(use_p5)- if self.has_extra_convs:- for i in range(self.extra_stage):- lvl = ed_stage + 1 + i- if i == 0 and self.use_c5:- in_c = in_channels[-1]- else:- in_c = out_channels- extra_fpn_name = 'fpn_{}'.format(lvl + 2)- extra_fpn_conv_module = nn.Sequential()- if self.norm_type is not None:- # extra_fpn_conv_module.add_module(- # extra_fpn_name,- # ConvNormLayer(- # ch_in=in_c,- # ch_out=out_channels,- # filter_size=3,- # stride=2,- # norm_type=self.norm_type,- # norm_decay=self.norm_decay,- # freeze_norm=self.freeze_norm,- # initializer=None))- extra_fpn_conv = ConvNormLayer(- ch_in=in_c,- ch_out=out_channels,- filter_size=3,- stride=2,- norm_type=self.norm_type,- norm_decay=self.norm_decay,- freeze_norm=self.freeze_norm,- initializer=None)- else:- # extra_fpn_conv_module.add_module(- # extra_fpn_name,- # nn.Conv2d(- # in_channels=in_c,- # out_channels=out_channels,- # kernel_size=3,- # stride=2,- # padding=1,- # )- # )- extra_fpn_conv = nn.Conv2d(- in_channels=in_c,- out_channels=out_channels,- kernel_size=3,- stride=2,- padding=1,- )-- self.fpn_convs_module.add_module(extra_fpn_name, extra_fpn_conv)- self.fpn_convs.append(extra_fpn_conv)-- @classmethod- def from_config(cls, cfg, input_shape):- return {- 'in_channels': [i.channels for i in input_shape],- 'spatial_scales': [1.0 / i.stride for i in input_shape],- }-- def forward(self, body_feats):- laterals = []- num_levels = len(body_feats)-- for i in range(num_levels):- laterals.append(self.lateral_convs[i](body_feats[i]))-- for i in range(1, num_levels):- lvl = num_levels - i- upsample = F.interpolate(- laterals[lvl],- scale_factor=2.,- mode='nearest', )- laterals[lvl - 1] += upsample-- fpn_output = []- for lvl in range(num_levels):- fpn_output.append(self.fpn_convs[lvl](laterals[lvl]))-- if self.extra_stage > 0:- # use max pool to get more levels on top of outputs (Faster R-CNN, Mask R-CNN)- if not self.has_extra_convs:- assert self.extra_stage == 1, 'extra_stage should be 1 if FPN has not extra convs'- fpn_output.append(torch.max_pool2d(fpn_output[-1], 1, stride=2))- # add extra conv levels for RetinaNet(use_c5)/FCOS(use_p5)- else:- if self.use_c5:- extra_source = body_feats[-1]- else:- extra_source = fpn_output[-1]- fpn_output.append(self.fpn_convs[num_levels](extra_source))-- for i in range(1, self.extra_stage):- if self.relu_before_extra_convs:- fpn_output.append(self.fpn_convs[num_levels + i](F.relu(- fpn_output[-1])))- else:- fpn_output.append(self.fpn_convs[num_levels + i](- fpn_output[-1]))- return fpn_outputdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/fpn.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/fpn.pydeleted file mode 100755index a2399dfb..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/fpn.py+++ /dev/null@@ -1,109 +0,0 @@-"""-This code is refer from:-https://github.com/whai362/PSENet/blob/python3/models/neck/fpn.py-"""--import math-import torch-import torch.nn as nn-import torch.nn.functional as F----class Conv_BN_ReLU(nn.Module):- def __init__(self,- in_planes,- out_planes,- kernel_size=1,- stride=1,- padding=0):- super(Conv_BN_ReLU, self).__init__()- self.conv = nn.Conv2d(- in_planes,- out_planes,- kernel_size=kernel_size,- stride=stride,- padding=padding,- bias=False)- self.bn = nn.BatchNorm2d(out_planes, momentum=0.1)- self.relu = nn.ReLU()-- for m in self.modules():- if isinstance(m, nn.Conv2d):- nn.init.kaiming_normal_(m.weight, mode='fan_out')- if m.bias is not None:- nn.init.zeros_(m.bias)- elif isinstance(m, nn.BatchNorm2d):- nn.init.ones_(m.weight)- nn.init.zeros_(m.bias)--- def forward(self, x):- return self.relu(self.bn(self.conv(x)))---class FPN(nn.Module):- def __init__(self, in_channels, out_channels):- super(FPN, self).__init__()-- # Top layer- self.toplayer_ = Conv_BN_ReLU(- in_channels[3], out_channels, kernel_size=1, stride=1, padding=0)- # Lateral layers- self.latlayer1_ = Conv_BN_ReLU(- in_channels[2], out_channels, kernel_size=1, stride=1, padding=0)-- self.latlayer2_ = Conv_BN_ReLU(- in_channels[1], out_channels, kernel_size=1, stride=1, padding=0)-- self.latlayer3_ = Conv_BN_ReLU(- in_channels[0], out_channels, kernel_size=1, stride=1, padding=0)-- # Smooth layers- self.smooth1_ = Conv_BN_ReLU(- out_channels, out_channels, kernel_size=3, stride=1, padding=1)-- self.smooth2_ = Conv_BN_ReLU(- out_channels, out_channels, kernel_size=3, stride=1, padding=1)-- self.smooth3_ = Conv_BN_ReLU(- out_channels, out_channels, kernel_size=3, stride=1, padding=1)-- self.out_channels = out_channels * 4- for m in self.modules():- if isinstance(m, nn.Conv2d):- nn.init.kaiming_normal_(m.weight, mode='fan_out')- if m.bias is not None:- nn.init.zeros_(m.bias)- elif isinstance(m, nn.BatchNorm2d):- nn.init.ones_(m.weight)- nn.init.zeros_(m.bias)-- def _upsample(self, x, scale=1):- return F.interpolate(x, scale_factor=scale, mode='bilinear')-- def _upsample_add(self, x, y, scale=1):- return F.interpolate(x, scale_factor=scale, mode='bilinear') + y-- def forward(self, x):- f2, f3, f4, f5 = x- p5 = self.toplayer_(f5)-- f4 = self.latlayer1_(f4)- p4 = self._upsample_add(p5, f4, 2)- p4 = self.smooth1_(p4)-- f3 = self.latlayer2_(f3)- p3 = self._upsample_add(p4, f3, 2)- p3 = self.smooth2_(p3)-- f2 = self.latlayer3_(f2)- p2 = self._upsample_add(p3, f2, 2)- p2 = self.smooth3_(p2)-- p3 = self._upsample(p3, 2)- p4 = self._upsample(p4, 4)- p5 = self._upsample(p5, 8)-- fuse = torch.cat([p2, p3, p4, p5], dim=1)- return fusediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/intracl.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/intracl.pyold mode 100755new mode 100644index 414b7238..0ba85fa8--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/intracl.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/intracl.py@@ -7,55 +7,55 @@ class IntraCLBlock(nn.Module):self.channels = in_channelsself.rf = reduce_factorself.conv1x1_reduce_channel = nn.Conv2d(- self.channels,- self.channels // self.rf,- kernel_size=1,- stride=1,- padding=0)+ self.channels, self.channels // self.rf, kernel_size=1, stride=1, padding=0+ )self.conv1x1_return_channel = nn.Conv2d(- self.channels // self.rf,- self.channels,- kernel_size=1,- stride=1,- padding=0)+ self.channels // self.rf, self.channels, kernel_size=1, stride=1, padding=0+ )self.v_layer_7x1 = nn.Conv2d(self.channels // self.rf,self.channels // self.rf,kernel_size=(7, 1),stride=(1, 1),- padding=(3, 0))+ padding=(3, 0),+ )self.v_layer_5x1 = nn.Conv2d(self.channels // self.rf,self.channels // self.rf,kernel_size=(5, 1),stride=(1, 1),- padding=(2, 0))+ padding=(2, 0),+ )self.v_layer_3x1 = nn.Conv2d(self.channels // self.rf,self.channels // self.rf,kernel_size=(3, 1),stride=(1, 1),- padding=(1, 0))+ padding=(1, 0),+ )self.q_layer_1x7 = nn.Conv2d(self.channels // self.rf,self.channels // self.rf,kernel_size=(1, 7),stride=(1, 1),- padding=(0, 3))+ padding=(0, 3),+ )self.q_layer_1x5 = nn.Conv2d(self.channels // self.rf,self.channels // self.rf,kernel_size=(1, 5),stride=(1, 1),- padding=(0, 2))+ padding=(0, 2),+ )self.q_layer_1x3 = nn.Conv2d(self.channels // self.rf,self.channels // self.rf,kernel_size=(1, 3),stride=(1, 1),- padding=(0, 1))+ padding=(0, 1),+ )# baseself.c_layer_7x7 = nn.Conv2d(@@ -63,19 +63,22 @@ class IntraCLBlock(nn.Module):self.channels // self.rf,kernel_size=(7, 7),stride=(1, 1),- padding=(3, 3))+ padding=(3, 3),+ )self.c_layer_5x5 = nn.Conv2d(self.channels // self.rf,self.channels // self.rf,kernel_size=(5, 5),stride=(1, 1),- padding=(2, 2))+ padding=(2, 2),+ )self.c_layer_3x3 = nn.Conv2d(self.channels // self.rf,self.channels // self.rf,kernel_size=(3, 3),stride=(1, 1),- padding=(1, 1))+ padding=(1, 1),+ )self.bn = nn.BatchNorm2d(self.channels)self.relu = nn.ReLU()@@ -111,4 +114,4 @@ def build_intraclblock_list(num_block):for i in range(num_block):IntraCLBlock_list.append(IntraCLBlock())- return IntraCLBlock_list\ No newline at end of file+ return IntraCLBlock_listdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/pg_fpn.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/pg_fpn.pydeleted file mode 100755index ec48d3cc..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/pg_fpn.py+++ /dev/null@@ -1,297 +0,0 @@---from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation---class ConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride=1,- groups=1,- is_vd_mode=False,- act=None,- name=None):- super(ConvBNLayer, self).__init__()-- self.is_vd_mode = is_vd_mode- self._pool2d_avg = nn.AvgPool2d(- kernel_size=2, stride=2, padding=0, ceil_mode=True)- self._conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=(kernel_size - 1) // 2,- groups=groups,- bias=False)- if name == "conv1":- bn_name = "bn_" + name- else:- bn_name = "bn" + name[3:]- self._batch_norm = nn.BatchNorm2d(out_channels)- self.act = act- if self.act is not None:- self._act = Activation(act_type=self.act, inplace=True)--- def forward(self, inputs):- y = self._conv(inputs)- y = self._batch_norm(y)- if self.act is not None:- y = self._act(y)- return y---class DeConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size=4,- stride=2,- padding=1,- groups=1,- if_act=True,- act=None,- name=None):- super(DeConvBNLayer, self).__init__()-- self.if_act = if_act- self.act = act- self.deconv = nn.ConvTranspose2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=padding,- groups=groups,- bias=False)- self.bn = nn.BatchNorm2d(out_channels)- self.act = act- if self.act is not None:- self._act = Activation(act_type=self.act, inplace=True)-- def forward(self, x):- x = self.deconv(x)- x = self.bn(x)- if self.act is not None:- x = self._act(x)- return x---class PGFPN(nn.Module):- def __init__(self, in_channels, **kwargs):- super(PGFPN, self).__init__()- num_inputs = [2048, 2048, 1024, 512, 256]- num_outputs = [256, 256, 192, 192, 128]- self.out_channels = 128- self.conv_bn_layer_1 = ConvBNLayer(- in_channels=3,- out_channels=32,- kernel_size=3,- stride=1,- act=None,- name='FPN_d1')- self.conv_bn_layer_2 = ConvBNLayer(- in_channels=64,- out_channels=64,- kernel_size=3,- stride=1,- act=None,- name='FPN_d2')- self.conv_bn_layer_3 = ConvBNLayer(- in_channels=256,- out_channels=128,- kernel_size=3,- stride=1,- act=None,- name='FPN_d3')- self.conv_bn_layer_4 = ConvBNLayer(- in_channels=32,- out_channels=64,- kernel_size=3,- stride=2,- act=None,- name='FPN_d4')- self.conv_bn_layer_5 = ConvBNLayer(- in_channels=64,- out_channels=64,- kernel_size=3,- stride=1,- act='relu',- name='FPN_d5')- self.conv_bn_layer_6 = ConvBNLayer(- in_channels=64,- out_channels=128,- kernel_size=3,- stride=2,- act=None,- name='FPN_d6')- self.conv_bn_layer_7 = ConvBNLayer(- in_channels=128,- out_channels=128,- kernel_size=3,- stride=1,- act='relu',- name='FPN_d7')- self.conv_bn_layer_8 = ConvBNLayer(- in_channels=128,- out_channels=128,- kernel_size=1,- stride=1,- act=None,- name='FPN_d8')-- self.conv_h0 = ConvBNLayer(- in_channels=num_inputs[0],- out_channels=num_outputs[0],- kernel_size=1,- stride=1,- act=None,- name="conv_h{}".format(0))- self.conv_h1 = ConvBNLayer(- in_channels=num_inputs[1],- out_channels=num_outputs[1],- kernel_size=1,- stride=1,- act=None,- name="conv_h{}".format(1))- self.conv_h2 = ConvBNLayer(- in_channels=num_inputs[2],- out_channels=num_outputs[2],- kernel_size=1,- stride=1,- act=None,- name="conv_h{}".format(2))- self.conv_h3 = ConvBNLayer(- in_channels=num_inputs[3],- out_channels=num_outputs[3],- kernel_size=1,- stride=1,- act=None,- name="conv_h{}".format(3))- self.conv_h4 = ConvBNLayer(- in_channels=num_inputs[4],- out_channels=num_outputs[4],- kernel_size=1,- stride=1,- act=None,- name="conv_h{}".format(4))-- self.dconv0 = DeConvBNLayer(- in_channels=num_outputs[0],- out_channels=num_outputs[0 + 1],- name="dconv_{}".format(0))- self.dconv1 = DeConvBNLayer(- in_channels=num_outputs[1],- out_channels=num_outputs[1 + 1],- act=None,- name="dconv_{}".format(1))- self.dconv2 = DeConvBNLayer(- in_channels=num_outputs[2],- out_channels=num_outputs[2 + 1],- act=None,- name="dconv_{}".format(2))- self.dconv3 = DeConvBNLayer(- in_channels=num_outputs[3],- out_channels=num_outputs[3 + 1],- act=None,- name="dconv_{}".format(3))- self.conv_g1 = ConvBNLayer(- in_channels=num_outputs[1],- out_channels=num_outputs[1],- kernel_size=3,- stride=1,- act='relu',- name="conv_g{}".format(1))- self.conv_g2 = ConvBNLayer(- in_channels=num_outputs[2],- out_channels=num_outputs[2],- kernel_size=3,- stride=1,- act='relu',- name="conv_g{}".format(2))- self.conv_g3 = ConvBNLayer(- in_channels=num_outputs[3],- out_channels=num_outputs[3],- kernel_size=3,- stride=1,- act='relu',- name="conv_g{}".format(3))- self.conv_g4 = ConvBNLayer(- in_channels=num_outputs[4],- out_channels=num_outputs[4],- kernel_size=3,- stride=1,- act='relu',- name="conv_g{}".format(4))- self.convf = ConvBNLayer(- in_channels=num_outputs[4],- out_channels=num_outputs[4],- kernel_size=1,- stride=1,- act=None,- name="conv_f{}".format(4))-- def forward(self, x):- c0, c1, c2, c3, c4, c5, c6 = x- # FPN_Down_Fusion- f = [c0, c1, c2]- g = [None, None, None]- h = [None, None, None]- h[0] = self.conv_bn_layer_1(f[0])- h[1] = self.conv_bn_layer_2(f[1])- h[2] = self.conv_bn_layer_3(f[2])-- g[0] = self.conv_bn_layer_4(h[0])- g[1] = torch.add(g[0], h[1])- g[1] = F.relu(g[1])- g[1] = self.conv_bn_layer_5(g[1])- g[1] = self.conv_bn_layer_6(g[1])-- g[2] = torch.add(g[1], h[2])- g[2] = F.relu(g[2])- g[2] = self.conv_bn_layer_7(g[2])- f_down = self.conv_bn_layer_8(g[2])-- # FPN UP Fusion- f1 = [c6, c5, c4, c3, c2]- g = [None, None, None, None, None]- h = [None, None, None, None, None]- h[0] = self.conv_h0(f1[0])- h[1] = self.conv_h1(f1[1])- h[2] = self.conv_h2(f1[2])- h[3] = self.conv_h3(f1[3])- h[4] = self.conv_h4(f1[4])-- g[0] = self.dconv0(h[0])- g[1] = torch.add(g[0], h[1])- g[1] = F.relu(g[1])- g[1] = self.conv_g1(g[1])- g[1] = self.dconv1(g[1])-- g[2] = torch.add(g[1], h[2])- g[2] = F.relu(g[2])- g[2] = self.conv_g2(g[2])- g[2] = self.dconv2(g[2])-- g[3] = torch.add(g[2], h[3])- g[3] = F.relu(g[3])- g[3] = self.conv_g3(g[3])- g[3] = self.dconv3(g[3])-- g[4] = torch.add(g[3], h[4])- g[4] = F.relu(g[4])- g[4] = self.conv_g4(g[4])- f_up = self.convf(g[4])- f_common = torch.add(f_down, f_up)- f_common = F.relu(f_common)- return f_commondiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/rnn.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/rnn.pyold mode 100755new mode 100644index 5a353cb7..244ea443--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/rnn.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/rnn.py@@ -1,7 +1,8 @@-import os, sysimport torch-import torch.nn as nn-from pytorchocr.modeling.backbones.rec_svtrnet import Block, ConvBNLayer+from torch import nn++from ..backbones.rec_svtrnet import Block, ConvBNLayer+class Im2Seq(nn.Module):def __init__(self, in_channels, **kwargs):@@ -13,7 +14,7 @@ class Im2Seq(nn.Module):# assert H == 1x = x.squeeze(dim=2)# x = x.transpose([0, 2, 1]) # paddle (NTC)(batch, width, channels)- x = x.permute(0,2,1)+ x = x.permute(0, 2, 1)return x@@ -21,8 +22,20 @@ class EncoderWithRNN_(nn.Module):def __init__(self, in_channels, hidden_size):super(EncoderWithRNN_, self).__init__()self.out_channels = hidden_size * 2- self.rnn1 = nn.LSTM(in_channels, hidden_size, bidirectional=False, batch_first=True, num_layers=2)- self.rnn2 = nn.LSTM(in_channels, hidden_size, bidirectional=False, batch_first=True, num_layers=2)+ self.rnn1 = nn.LSTM(+ in_channels,+ hidden_size,+ bidirectional=False,+ batch_first=True,+ num_layers=2,+ )+ self.rnn2 = nn.LSTM(+ in_channels,+ hidden_size,+ bidirectional=False,+ batch_first=True,+ num_layers=2,+ )def forward(self, x):self.rnn1.flatten_parameters()@@ -37,7 +50,8 @@ class EncoderWithRNN(nn.Module):super(EncoderWithRNN, self).__init__()self.out_channels = hidden_size * 2self.lstm = nn.LSTM(- in_channels, hidden_size, num_layers=2, batch_first=True, bidirectional=True) # batch_first:=True+ in_channels, hidden_size, num_layers=2, batch_first=True, bidirectional=True+ ) # batch_first:=Truedef forward(self, x):x, _ = self.lstm(x)@@ -52,7 +66,7 @@ class EncoderWithFC(nn.Module):in_channels,hidden_size,bias=True,- )+ )def forward(self, x):x = self.fc(x)@@ -61,20 +75,21 @@ class EncoderWithFC(nn.Module):class EncoderWithSVTR(nn.Module):def __init__(- self,- in_channels,- dims=64, # XS- depth=2,- hidden_dims=120,- use_guide=False,- num_heads=8,- qkv_bias=True,- mlp_ratio=2.0,- drop_rate=0.1,- kernel_size=[3,3],- attn_drop_rate=0.1,- drop_path=0.,- qk_scale=None):+ self,+ in_channels,+ dims=64, # XS+ depth=2,+ hidden_dims=120,+ use_guide=False,+ num_heads=8,+ qkv_bias=True,+ mlp_ratio=2.0,+ drop_rate=0.1,+ kernel_size=[3, 3],+ attn_drop_rate=0.1,+ drop_path=0.0,+ qk_scale=None,+ ):super(EncoderWithSVTR, self).__init__()self.depth = depthself.use_guide = use_guide@@ -83,43 +98,48 @@ class EncoderWithSVTR(nn.Module):in_channels // 8,kernel_size=kernel_size,padding=[kernel_size[0] // 2, kernel_size[1] // 2],- act='swish')+ act="swish",+ )self.conv2 = ConvBNLayer(- in_channels // 8, hidden_dims, kernel_size=1, act='swish')-- self.svtr_block = nn.ModuleList([- Block(- dim=hidden_dims,- num_heads=num_heads,- mixer='Global',- HW=None,- mlp_ratio=mlp_ratio,- qkv_bias=qkv_bias,- qk_scale=qk_scale,- drop=drop_rate,- act_layer='swish',- attn_drop=attn_drop_rate,- drop_path=drop_path,- norm_layer='nn.LayerNorm',- epsilon=1e-05,- prenorm=False) for i in range(depth)- ])+ in_channels // 8, hidden_dims, kernel_size=1, act="swish"+ )++ self.svtr_block = nn.ModuleList(+ [+ Block(+ dim=hidden_dims,+ num_heads=num_heads,+ mixer="Global",+ HW=None,+ mlp_ratio=mlp_ratio,+ qkv_bias=qkv_bias,+ qk_scale=qk_scale,+ drop=drop_rate,+ act_layer="swish",+ attn_drop=attn_drop_rate,+ drop_path=drop_path,+ norm_layer="nn.LayerNorm",+ epsilon=1e-05,+ prenorm=False,+ )+ for i in range(depth)+ ]+ )self.norm = nn.LayerNorm(hidden_dims, eps=1e-6)- self.conv3 = ConvBNLayer(- hidden_dims, in_channels, kernel_size=1, act='swish')+ self.conv3 = ConvBNLayer(hidden_dims, in_channels, kernel_size=1, act="swish")# last conv-nxn, the input is concat of input tensor and conv3 output tensorself.conv4 = ConvBNLayer(- 2 * in_channels, in_channels // 8, padding=1, act='swish')+ 2 * in_channels, in_channels // 8, padding=1, act="swish"+ )- self.conv1x1 = ConvBNLayer(- in_channels // 8, dims, kernel_size=1, act='swish')+ self.conv1x1 = ConvBNLayer(in_channels // 8, dims, kernel_size=1, act="swish")self.out_channels = dimsself.apply(self._init_weights)def _init_weights(self, m):# weight initializationif isinstance(m, nn.Conv2d):- nn.init.kaiming_normal_(m.weight, mode='fan_out')+ nn.init.kaiming_normal_(m.weight, mode="fan_out")if m.bias is not None:nn.init.zeros_(m.bias)elif isinstance(m, nn.BatchNorm2d):@@ -130,7 +150,7 @@ class EncoderWithSVTR(nn.Module):if m.bias is not None:nn.init.zeros_(m.bias)elif isinstance(m, nn.ConvTranspose2d):- nn.init.kaiming_normal_(m.weight, mode='fan_out')+ nn.init.kaiming_normal_(m.weight, mode="fan_out")if m.bias is not None:nn.init.zeros_(m.bias)elif isinstance(m, nn.LayerNorm):@@ -172,29 +192,32 @@ class SequenceEncoder(nn.Module):self.encoder_reshape = Im2Seq(in_channels)self.out_channels = self.encoder_reshape.out_channelsself.encoder_type = encoder_type- if encoder_type == 'reshape':+ if encoder_type == "reshape":self.only_reshape = Trueelse:support_encoder_dict = {- 'reshape': Im2Seq,- 'fc': EncoderWithFC,- 'rnn': EncoderWithRNN,- 'svtr': EncoderWithSVTR,+ "reshape": Im2Seq,+ "fc": EncoderWithFC,+ "rnn": EncoderWithRNN,+ "svtr": EncoderWithSVTR,}- assert encoder_type in support_encoder_dict, '{} must in {}'.format(- encoder_type, support_encoder_dict.keys())+ assert encoder_type in support_encoder_dict, "{} must in {}".format(+ encoder_type, support_encoder_dict.keys()+ )if encoder_type == "svtr":self.encoder = support_encoder_dict[encoder_type](- self.encoder_reshape.out_channels, **kwargs)+ self.encoder_reshape.out_channels, **kwargs+ )else:self.encoder = support_encoder_dict[encoder_type](- self.encoder_reshape.out_channels, hidden_size)+ self.encoder_reshape.out_channels, hidden_size+ )self.out_channels = self.encoder.out_channelsself.only_reshape = Falsedef forward(self, x):- if self.encoder_type != 'svtr':+ if self.encoder_type != "svtr":x = self.encoder_reshape(x)if not self.only_reshape:x = self.encoder(x)@@ -202,4 +225,4 @@ class SequenceEncoder(nn.Module):else:x = self.encoder(x)x = self.encoder_reshape(x)- return x\ No newline at end of file+ return xdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/sast_fpn.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/sast_fpn.pydeleted file mode 100755index 118467fc..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/sast_fpn.py+++ /dev/null@@ -1,305 +0,0 @@-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import os, sys-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation-# import paddle-# from paddle import nn-# import paddle.nn.functional as F-# from paddle import ParamAttr---class ConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride,- groups=1,- if_act=True,- act=None,- name=None):- super(ConvBNLayer, self).__init__()- self.if_act = if_act- self.act = act- # self.conv = nn.Conv2D(- # in_channels=in_channels,- # out_channels=out_channels,- # kernel_size=kernel_size,- # stride=stride,- # padding=(kernel_size - 1) // 2,- # groups=groups,- # weight_attr=ParamAttr(name=name + '_weights'),- # bias_attr=False)- self.conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=(kernel_size - 1) // 2,- groups=groups,- bias=False)-- self.bn = nn.BatchNorm2d(- out_channels,)- self.act = act- if act is not None:- self._act = Activation(act)-- def forward(self, x):- x = self.conv(x)- x = self.bn(x)- if self.act is not None:- x = self._act(x)- return x---class DeConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride,- groups=1,- if_act=True,- act=None,- name=None):- super(DeConvBNLayer, self).__init__()- self.if_act = if_act- self.act = act-- self.deconv = nn.ConvTranspose2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=(kernel_size - 1) // 2,- groups=groups,- bias=False)- self.bn = nn.BatchNorm2d(- out_channels,- )- self.act = act- if act is not None:- self._act = Activation(act)-- def forward(self, x):- x = self.deconv(x)- x = self.bn(x)- if self.act is not None:- x = self._act(x)- return x---class FPN_Up_Fusion(nn.Module):- def __init__(self, in_channels):- super(FPN_Up_Fusion, self).__init__()- in_channels = in_channels[::-1]- out_channels = [256, 256, 192, 192, 128]-- self.h0_conv = ConvBNLayer(in_channels[0], out_channels[0], 1, 1, act=None, name='fpn_up_h0')- self.h1_conv = ConvBNLayer(in_channels[1], out_channels[1], 1, 1, act=None, name='fpn_up_h1')- self.h2_conv = ConvBNLayer(in_channels[2], out_channels[2], 1, 1, act=None, name='fpn_up_h2')- self.h3_conv = ConvBNLayer(in_channels[3], out_channels[3], 1, 1, act=None, name='fpn_up_h3')- self.h4_conv = ConvBNLayer(in_channels[4], out_channels[4], 1, 1, act=None, name='fpn_up_h4')-- self.g0_conv = DeConvBNLayer(out_channels[0], out_channels[1], 4, 2, act=None, name='fpn_up_g0')-- self.g1_conv = nn.Sequential(- ConvBNLayer(out_channels[1], out_channels[1], 3, 1, act='relu', name='fpn_up_g1_1'),- DeConvBNLayer(out_channels[1], out_channels[2], 4, 2, act=None, name='fpn_up_g1_2')- )- self.g2_conv = nn.Sequential(- ConvBNLayer(out_channels[2], out_channels[2], 3, 1, act='relu', name='fpn_up_g2_1'),- DeConvBNLayer(out_channels[2], out_channels[3], 4, 2, act=None, name='fpn_up_g2_2')- )- self.g3_conv = nn.Sequential(- ConvBNLayer(out_channels[3], out_channels[3], 3, 1, act='relu', name='fpn_up_g3_1'),- DeConvBNLayer(out_channels[3], out_channels[4], 4, 2, act=None, name='fpn_up_g3_2')- )-- self.g4_conv = nn.Sequential(- ConvBNLayer(out_channels[4], out_channels[4], 3, 1, act='relu', name='fpn_up_fusion_1'),- ConvBNLayer(out_channels[4], out_channels[4], 1, 1, act=None, name='fpn_up_fusion_2')- )-- def _add_relu(self, x1, x2):- # x = paddle.add(x=x1, y=x2)- x = torch.add(x1, x2)- x = F.relu(x)- return x-- def forward(self, x):- f = x[2:][::-1]- h0 = self.h0_conv(f[0])- h1 = self.h1_conv(f[1])- h2 = self.h2_conv(f[2])- h3 = self.h3_conv(f[3])- h4 = self.h4_conv(f[4])-- g0 = self.g0_conv(h0)- g1 = self._add_relu(g0, h1)- g1 = self.g1_conv(g1)- g2 = self.g2_conv(self._add_relu(g1, h2))- g3 = self.g3_conv(self._add_relu(g2, h3))- g4 = self.g4_conv(self._add_relu(g3, h4))-- return g4---class FPN_Down_Fusion(nn.Module):- def __init__(self, in_channels):- super(FPN_Down_Fusion, self).__init__()- out_channels = [32, 64, 128]-- self.h0_conv = ConvBNLayer(in_channels[0], out_channels[0], 3, 1, act=None, name='fpn_down_h0')- self.h1_conv = ConvBNLayer(in_channels[1], out_channels[1], 3, 1, act=None, name='fpn_down_h1')- self.h2_conv = ConvBNLayer(in_channels[2], out_channels[2], 3, 1, act=None, name='fpn_down_h2')-- self.g0_conv = ConvBNLayer(out_channels[0], out_channels[1], 3, 2, act=None, name='fpn_down_g0')-- self.g1_conv = nn.Sequential(- ConvBNLayer(out_channels[1], out_channels[1], 3, 1, act='relu', name='fpn_down_g1_1'),- ConvBNLayer(out_channels[1], out_channels[2], 3, 2, act=None, name='fpn_down_g1_2')- )-- self.g2_conv = nn.Sequential(- ConvBNLayer(out_channels[2], out_channels[2], 3, 1, act='relu', name='fpn_down_fusion_1'),- ConvBNLayer(out_channels[2], out_channels[2], 1, 1, act=None, name='fpn_down_fusion_2')- )-- def forward(self, x):- f = x[:3]- h0 = self.h0_conv(f[0])- h1 = self.h1_conv(f[1])- h2 = self.h2_conv(f[2])- g0 = self.g0_conv(h0)- # g1 = paddle.add(x=g0, y=h1)- g1 = torch.add(g0, h1)- g1 = F.relu(g1)- g1 = self.g1_conv(g1)- # g2 = paddle.add(x=g1, y=h2)- g2 = torch.add(g1, h2)- g2 = F.relu(g2)- g2 = self.g2_conv(g2)- return g2---class Cross_Attention(nn.Module):- def __init__(self, in_channels):- super(Cross_Attention, self).__init__()- self.theta_conv = ConvBNLayer(in_channels, in_channels, 1, 1, act='relu', name='f_theta')- self.phi_conv = ConvBNLayer(in_channels, in_channels, 1, 1, act='relu', name='f_phi')- self.g_conv = ConvBNLayer(in_channels, in_channels, 1, 1, act='relu', name='f_g')-- self.fh_weight_conv = ConvBNLayer(in_channels, in_channels, 1, 1, act=None, name='fh_weight')- self.fh_sc_conv = ConvBNLayer(in_channels, in_channels, 1, 1, act=None, name='fh_sc')-- self.fv_weight_conv = ConvBNLayer(in_channels, in_channels, 1, 1, act=None, name='fv_weight')- self.fv_sc_conv = ConvBNLayer(in_channels, in_channels, 1, 1, act=None, name='fv_sc')-- self.f_attn_conv = ConvBNLayer(in_channels * 2, in_channels, 1, 1, act='relu', name='f_attn')-- def _cal_fweight(self, f, shape):- f_theta, f_phi, f_g = f- # flatten- # f_theta = paddle.transpose(f_theta, [0, 2, 3, 1])- f_theta = f_theta.permute(0, 2, 3, 1)- # f_theta = paddle.reshape(f_theta, [shape[0] * shape[1], shape[2], 128])- f_theta = torch.reshape(f_theta, [shape[0] * shape[1], shape[2], 128])- # f_phi = paddle.transpose(f_phi, [0, 2, 3, 1])- f_phi = f_phi.permute(0, 2, 3, 1)- # f_phi = paddle.reshape(f_phi, [shape[0] * shape[1], shape[2], 128])- f_phi = torch.reshape(f_phi, [shape[0] * shape[1], shape[2], 128])- # f_g = paddle.transpose(f_g, [0, 2, 3, 1])- f_g = f_g.permute(0, 2, 3, 1)- # f_g = paddle.reshape(f_g, [shape[0] * shape[1], shape[2], 128])- f_g = torch.reshape(f_g, [shape[0] * shape[1], shape[2], 128])- # correlation- # f_attn = paddle.matmul(f_theta, paddle.transpose(f_phi, [0, 2, 1]))- f_attn = torch.matmul(f_theta, f_phi.permute(0, 2, 1))- # scale- f_attn = f_attn / (128 ** 0.5)- f_attn = F.softmax(f_attn, dim=-1)- # weighted sum- # f_weight = paddle.matmul(f_attn, f_g)- f_weight = torch.matmul(f_attn, f_g)- # f_weight = paddle.reshape(- # f_weight, [shape[0], shape[1], shape[2], 128])- f_weight = torch.reshape(- f_weight, [shape[0], shape[1], shape[2], 128])- return f_weight-- def forward(self, f_common):- # f_shape = paddle.shape(f_common)- f_shape = f_common.size()- # print('f_shape: ', f_shape)-- f_theta = self.theta_conv(f_common)- f_phi = self.phi_conv(f_common)- f_g = self.g_conv(f_common)-- ######## horizon ########- fh_weight = self._cal_fweight([f_theta, f_phi, f_g],- [f_shape[0], f_shape[2], f_shape[3]])- # fh_weight = paddle.transpose(fh_weight, [0, 3, 1, 2])- fh_weight = fh_weight.permute(0, 3, 1, 2)- fh_weight = self.fh_weight_conv(fh_weight)- # short cut- fh_sc = self.fh_sc_conv(f_common)- f_h = F.relu(fh_weight + fh_sc)-- ######## vertical ########- # fv_theta = paddle.transpose(f_theta, [0, 1, 3, 2])- fv_theta = f_theta.permute(0, 1, 3, 2)- # fv_phi = paddle.transpose(f_phi, [0, 1, 3, 2])- fv_phi = f_phi.permute(0, 1, 3, 2)- # fv_g = paddle.transpose(f_g, [0, 1, 3, 2])- fv_g = f_g.permute(0, 1, 3, 2)- fv_weight = self._cal_fweight([fv_theta, fv_phi, fv_g],- [f_shape[0], f_shape[3], f_shape[2]])- # fv_weight = paddle.transpose(fv_weight, [0, 3, 2, 1])- fv_weight = fv_weight.permute(0, 3, 2, 1)- fv_weight = self.fv_weight_conv(fv_weight)- # short cut- fv_sc = self.fv_sc_conv(f_common)- f_v = F.relu(fv_weight + fv_sc)-- ######## merge ########- # f_attn = paddle.concat([f_h, f_v], axis=1)- f_attn = torch.cat([f_h, f_v], dim=1)- f_attn = self.f_attn_conv(f_attn)- return f_attn---class SASTFPN(nn.Module):- def __init__(self, in_channels, with_cab=False, **kwargs):- super(SASTFPN, self).__init__()- self.in_channels = in_channels- self.with_cab = with_cab- self.FPN_Down_Fusion = FPN_Down_Fusion(self.in_channels)- self.FPN_Up_Fusion = FPN_Up_Fusion(self.in_channels)- self.out_channels = 128- self.cross_attention = Cross_Attention(self.out_channels)-- def forward(self, x):- # down fpn- f_down = self.FPN_Down_Fusion(x)-- # up fpn- f_up = self.FPN_Up_Fusion(x)-- # fusion- # f_common = paddle.add(x=f_down, y=f_up)- f_common = torch.add(f_down, f_up)- f_common = F.relu(f_common)-- if self.with_cab:- # print('enhence f_common with CAB.')- f_common = self.cross_attention(f_common)-- return f_common\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/table_fpn.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/table_fpn.pydeleted file mode 100755index 1d0ee690..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/table_fpn.py+++ /dev/null@@ -1,88 +0,0 @@-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation---class TableFPN(nn.Module):- def __init__(self, in_channels, out_channels, **kwargs):- super(TableFPN, self).__init__()- self.out_channels = 512-- self.in2_conv = nn.Conv2d(- in_channels=in_channels[0],- out_channels=self.out_channels,- kernel_size=1,- bias=False)- self.in3_conv = nn.Conv2d(- in_channels=in_channels[1],- out_channels=self.out_channels,- kernel_size=1,- stride = 1,- bias=False)- self.in4_conv = nn.Conv2d(- in_channels=in_channels[2],- out_channels=self.out_channels,- kernel_size=1,- bias=False)- self.in5_conv = nn.Conv2d(- in_channels=in_channels[3],- out_channels=self.out_channels,- kernel_size=1,- bias=False)- self.p5_conv = nn.Conv2d(- in_channels=self.out_channels,- out_channels=self.out_channels // 4,- kernel_size=3,- padding=1,- bias=False)- self.p4_conv = nn.Conv2d(- in_channels=self.out_channels,- out_channels=self.out_channels // 4,- kernel_size=3,- padding=1,- bias=False)- self.p3_conv = nn.Conv2d(- in_channels=self.out_channels,- out_channels=self.out_channels // 4,- kernel_size=3,- padding=1,- bias=False)- self.p2_conv = nn.Conv2d(- in_channels=self.out_channels,- out_channels=self.out_channels // 4,- kernel_size=3,- padding=1,- bias=False)- self.fuse_conv = nn.Conv2d(- in_channels=self.out_channels * 4,- out_channels=512,- kernel_size=3,- padding=1,- bias=False)-- def forward(self, x):- c2, c3, c4, c5 = x-- in5 = self.in5_conv(c5)- in4 = self.in4_conv(c4)- in3 = self.in3_conv(c3)- in2 = self.in2_conv(c2)-- out4 = in4 + F.interpolate(- in5, size=in4.shape[2:4], mode="nearest", )#align_mode=1) # 1/16- out3 = in3 + F.interpolate(- out4, size=in3.shape[2:4], mode="nearest", )#align_mode=1) # 1/8- out2 = in2 + F.interpolate(- out3, size=in2.shape[2:4], mode="nearest", )#align_mode=1) # 1/4-- p4 = F.interpolate(out4, size=in5.shape[2:4], mode="nearest", )#align_mode=1)- p3 = F.interpolate(out3, size=in5.shape[2:4], mode="nearest", )#align_mode=1)- p2 = F.interpolate(out2, size=in5.shape[2:4], mode="nearest", )#align_mode=1)- fuse = torch.cat([in5, p4, p3, p2], dim=1)- fuse_conv = self.fuse_conv(fuse) * 0.005- return [c5 + fuse_conv]\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/__init__.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/__init__.pydeleted file mode 100755index f0383993..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/__init__.py+++ /dev/null@@ -1,30 +0,0 @@-# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.--__all__ = ['build_transform']---def build_transform(config):- from .tps import TPS- from .stn import STN_ON- from .tsrn import TSRN- from .tbsrn import TBSRN-- support_dict = ['TPS', 'STN_ON', 'TSRN', 'TBSRN']-- module_name = config.pop('name')- assert module_name in support_dict, Exception(- 'transform only support {}'.format(support_dict))- module_class = eval(module_name)(**config)- return module_class\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/stn.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/stn.pydeleted file mode 100755index dbed2d1c..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/stn.py+++ /dev/null@@ -1,121 +0,0 @@-"""-This code is refer from:-https://github.com/ayumiymk/aster.pytorch/blob/master/lib/models/stn_head.py-"""-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import math-import torch-from torch import nn-from torch.nn import functional as F-import numpy as np--from .tps_spatial_transformer import TPSSpatialTransformer---def conv3x3_block(in_channels, out_channels, stride=1):- n = 3 * 3 * out_channels- w = math.sqrt(2. / n)- conv_layer = nn.Conv2d(- in_channels,- out_channels,- kernel_size=3,- stride=stride,- padding=1,- bias=True)- block = nn.Sequential(conv_layer, nn.BatchNorm2d(out_channels), nn.ReLU())- return block---class STN(nn.Module):- def __init__(self, in_channels, num_ctrlpoints, activation='none'):- super(STN, self).__init__()- self.in_channels = in_channels- self.num_ctrlpoints = num_ctrlpoints- self.activation = activation- self.stn_convnet = nn.Sequential(- conv3x3_block(in_channels, 32), #32x64- nn.MaxPool2d(- kernel_size=2, stride=2),- conv3x3_block(32, 64), #16x32- nn.MaxPool2d(- kernel_size=2, stride=2),- conv3x3_block(64, 128), # 8*16- nn.MaxPool2d(- kernel_size=2, stride=2),- conv3x3_block(128, 256), # 4*8- nn.MaxPool2d(- kernel_size=2, stride=2),- conv3x3_block(256, 256), # 2*4,- nn.MaxPool2d(- kernel_size=2, stride=2),- conv3x3_block(256, 256)) # 1*2- self.stn_fc1 = nn.Sequential(- nn.Linear(- 2 * 256,- 512,- bias=True),- nn.BatchNorm1d(512),- nn.ReLU(inplace=True))- fc2_bias = self.init_stn()- self.stn_fc2 = nn.Linear(- 512,- num_ctrlpoints * 2,- bias=True)-- def init_stn(self):- margin = 0.01- sampling_num_per_side = int(self.num_ctrlpoints / 2)- ctrl_pts_x = np.linspace(margin, 1. - margin, sampling_num_per_side)- ctrl_pts_y_top = np.ones(sampling_num_per_side) * margin- ctrl_pts_y_bottom = np.ones(sampling_num_per_side) * (1 - margin)- ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)- ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)- ctrl_points = np.concatenate(- [ctrl_pts_top, ctrl_pts_bottom], axis=0).astype(np.float32)- if self.activation == 'none':- pass- elif self.activation == 'sigmoid':- ctrl_points = -np.log(1. / ctrl_points - 1.)- ctrl_points = torch.Tensor(ctrl_points)- # fc2_bias = ctrl_points.view(-1)- fc2_bias = torch.reshape(- ctrl_points, shape=[ctrl_points.shape[0] * ctrl_points.shape[1]])- return fc2_bias-- def forward(self, x):- x = self.stn_convnet(x)- batch_size, _, h, w = x.shape- # x = x.view(batch_size, -1)- x = torch.reshape(x, shape=(batch_size, -1))- img_feat = self.stn_fc1(x)- x = self.stn_fc2(0.1 * img_feat)- if self.activation == 'sigmoid':- x = F.sigmoid(x)- # x = x.view(-1, self.num_ctrlpoints, 2)- x = torch.reshape(x, shape=[-1, self.num_ctrlpoints, 2])- return img_feat, x---class STN_ON(nn.Module):- def __init__(self, in_channels, tps_inputsize, tps_outputsize,- num_control_points, tps_margins, stn_activation):- super(STN_ON, self).__init__()- self.tps = TPSSpatialTransformer(- output_image_size=tuple(tps_outputsize),- num_control_points=num_control_points,- margins=tuple(tps_margins))- self.stn_head = STN(in_channels=in_channels,- num_ctrlpoints=num_control_points,- activation=stn_activation)- self.tps_inputsize = tps_inputsize- self.out_channels = in_channels-- def forward(self, image):- stn_input = torch.nn.functional.interpolate(- image, self.tps_inputsize, mode="bilinear", align_corners=True)- stn_img_feat, ctrl_points = self.stn_head(stn_input)- x, _ = self.tps(image, ctrl_points)- return xdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/tbsrn.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/tbsrn.pydeleted file mode 100755index 8cbaa69f..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/tbsrn.py+++ /dev/null@@ -1,267 +0,0 @@-# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.-"""-This code is refer from:-https://github.com/FudanVI/FudanOCR/blob/main/scene-text-telescope/model/tbsrn.py-"""--import math-import warnings-import numpy as np-import torch-from torch import nn-import string--warnings.filterwarnings("ignore")--from .tps_spatial_transformer import TPSSpatialTransformer-from .stn import STN as STNHead-from .tsrn import GruBlock, mish, UpsampleBLock-from pytorchocr.modeling.heads.sr_rensnet_transformer import Transformer, LayerNorm, \- PositionwiseFeedForward, MultiHeadedAttention---def positionalencoding2d(d_model, height, width):- """- :param d_model: dimension of the model- :param height: height of the positions- :param width: width of the positions- :return: d_model*height*width position matrix- """- if d_model % 4 != 0:- raise ValueError("Cannot use sin/cos positional encoding with "- "odd dimension (got dim={:d})".format(d_model))- pe = torch.zeros([d_model, height, width])- # Each dimension use half of d_model- d_model = int(d_model / 2)- div_term = torch.exp(torch.arange(0., d_model, 2) *- -(math.log(10000.0) / d_model))- pos_w = torch.arange(0., width, dtype=torch.float32).unsqueeze(1)- pos_h = torch.arange(0., height, dtype=torch.float32).unsqueeze(1)-- pe[0:d_model:2, :, :] = torch.sin(pos_w * div_term).transpose(0, 1).unsqueeze(1).repeat(1, height, 1)- pe[1:d_model:2, :, :] = torch.cos(pos_w * div_term).transpose(0, 1).unsqueeze(1).repeat(1, height, 1)- pe[d_model::2, :, :] = torch.sin(pos_h * div_term).transpose(0, 1).unsqueeze(2).repeat(1, 1, width)- pe[d_model + 1::2, :, :] = torch.cos(pos_h * div_term).transpose(0, 1).unsqueeze(2).repeat(1, 1, width)-- return pe---class FeatureEnhancer(nn.Module):-- def __init__(self):- super(FeatureEnhancer, self).__init__()-- self.multihead = MultiHeadedAttention(h=4, d_model=128, dropout=0.1)- self.mul_layernorm1 = LayerNorm(features=128)-- self.pff = PositionwiseFeedForward(128, 128)- self.mul_layernorm3 = LayerNorm(features=128)-- self.linear = nn.Linear(128, 64)-- def forward(self, conv_feature):- '''- text : (batch, seq_len, embedding_size)- global_info: (batch, embedding_size, 1, 1)- conv_feature: (batch, channel, H, W)- '''- batch = conv_feature.shape[0]- if torch.cuda.is_available():- position2d = positionalencoding2d(64, 16, 64).float().cuda().unsqueeze(0).reshape([1, 64, 1024])- else:- position2d = positionalencoding2d(64, 16, 64).float().unsqueeze(0).reshape([1, 64, 1024])- position2d = position2d.repeat(batch, 1, 1)- conv_feature = torch.cat([conv_feature, position2d], 1) # batch, 128(64+64), 32, 128- result = conv_feature.permute(0, 2, 1).contiguous()- origin_result = result- result = self.mul_layernorm1(origin_result + self.multihead(result, result, result, mask=None)[0])- origin_result = result- result = self.mul_layernorm3(origin_result + self.pff(result))- result = self.linear(result)- return result.permute(0, 2, 1).contiguous()---def str_filt(str_, voc_type):- alpha_dict = {- 'digit': string.digits,- 'lower': string.digits + string.ascii_lowercase,- 'upper': string.digits + string.ascii_letters,- 'all': string.digits + string.ascii_letters + string.punctuation- }- if voc_type == 'lower':- str_ = str_.lower()- for char in str_:- if char not in alpha_dict[voc_type]:- str_ = str_.replace(char, '')- str_ = str_.lower()- return str_---class TBSRN(nn.Module):- def __init__(self,- in_channels=3,- scale_factor=2,- width=128,- height=32,- STN=True,- srb_nums=5,- mask=False,- hidden_units=32,- infer_mode=False):- super(TBSRN, self).__init__()- in_planes = 3- if mask:- in_planes = 4- assert math.log(scale_factor, 2) % 1 == 0- upsample_block_num = int(math.log(scale_factor, 2))- self.block1 = nn.Sequential(- nn.Conv2d(in_planes, 2 * hidden_units, kernel_size=9, padding=4),- nn.PReLU()- # nn.ReLU()- )- self.srb_nums = srb_nums- for i in range(srb_nums):- setattr(self, 'block%d' % (i + 2), RecurrentResidualBlock(2 * hidden_units))-- setattr(self, 'block%d' % (srb_nums + 2),- nn.Sequential(- nn.Conv2d(2 * hidden_units, 2 * hidden_units, kernel_size=3, padding=1),- nn.BatchNorm2d(2 * hidden_units)- ))-- # self.non_local = NonLocalBlock2D(64, 64)- block_ = [UpsampleBLock(2 * hidden_units, 2) for _ in range(upsample_block_num)]- block_.append(nn.Conv2d(2 * hidden_units, in_planes, kernel_size=9, padding=4))- setattr(self, 'block%d' % (srb_nums + 3), nn.Sequential(*block_))- self.tps_inputsize = [height // scale_factor, width // scale_factor]- tps_outputsize = [height // scale_factor, width // scale_factor]- num_control_points = 20- tps_margins = [0.05, 0.05]- self.stn = STN- self.out_channels = in_channels- if self.stn:- self.tps = TPSSpatialTransformer(- output_image_size=tuple(tps_outputsize),- num_control_points=num_control_points,- margins=tuple(tps_margins))-- self.stn_head = STNHead(- in_channels=in_planes,- num_ctrlpoints=num_control_points,- activation='none')- self.infer_mode = infer_mode-- self.english_alphabet = '-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'- self.english_dict = {}- for index in range(len(self.english_alphabet)):- self.english_dict[self.english_alphabet[index]] = index- transformer = Transformer(alphabet='-0123456789abcdefghijklmnopqrstuvwxyz')- self.transformer = transformer- for param in self.transformer.parameters():- param.trainable = False-- def label_encoder(self, label):- batch = len(label)-- length = [len(i) for i in label]- length_tensor = torch.Tensor(length).type(torch.int64)-- max_length = max(length)- input_tensor = np.zeros((batch, max_length))- for i in range(batch):- for j in range(length[i] - 1):- input_tensor[i][j + 1] = self.english_dict[label[i][j]]-- text_gt = []- for i in label:- for j in i:- text_gt.append(self.english_dict[j])- text_gt = torch.Tensor(text_gt).type(torch.int64)-- input_tensor = torch.Tensor(input_tensor).type(torch.int64)- return length_tensor, input_tensor, text_gt-- def forward(self, x):- output = {}- if self.infer_mode:- output["lr_img"] = x- y = x- else:- output["lr_img"] = x[0]- output["hr_img"] = x[1]- y = x[0]- if self.stn and self.training:- _, ctrl_points_x = self.stn_head(y)- y, _ = self.tps(y, ctrl_points_x)- block = {'1': self.block1(y)}- for i in range(self.srb_nums + 1):- block[str(i + 2)] = getattr(self,- 'block%d' % (i + 2))(block[str(i + 1)])-- block[str(self.srb_nums + 3)] = getattr(self, 'block%d' % (self.srb_nums + 3)) \- ((block['1'] + block[str(self.srb_nums + 2)]))-- sr_img = torch.tanh(block[str(self.srb_nums + 3)])- output["sr_img"] = sr_img-- if self.training:- hr_img = x[1]-- # add transformer- label = [str_filt(i, 'lower') + '-' for i in x[2]]- length_tensor, input_tensor, text_gt = self.label_encoder(label)- hr_pred, word_attention_map_gt, hr_correct_list = self.transformer(hr_img, length_tensor,- input_tensor)- sr_pred, word_attention_map_pred, sr_correct_list = self.transformer(sr_img, length_tensor,- input_tensor)- output["hr_img"] = hr_img- output["hr_pred"] = hr_pred- output["text_gt"] = text_gt- output["word_attention_map_gt"] = word_attention_map_gt- output["sr_pred"] = sr_pred- output["word_attention_map_pred"] = word_attention_map_pred-- return output---class RecurrentResidualBlock(nn.Module):- def __init__(self, channels):- super(RecurrentResidualBlock, self).__init__()- self.conv1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)- self.bn1 = nn.BatchNorm2d(channels)- self.gru1 = GruBlock(channels, channels)- # self.prelu = nn.ReLU()- self.prelu = mish()- self.conv2 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)- self.bn2 = nn.BatchNorm2d(channels)- self.gru2 = GruBlock(channels, channels)- self.feature_enhancer = FeatureEnhancer()-- for p in self.parameters():- if p.dim() > 1:- nn.init.xavier_uniform_(p)-- def forward(self, x):- residual = self.conv1(x)- residual = self.bn1(residual)- residual = self.prelu(residual)- residual = self.conv2(residual)- residual = self.bn2(residual)-- size = residual.shape- residual = residual.reshape([size[0], size[1], -1])- residual = self.feature_enhancer(residual)- residual = residual.reshape([size[0], size[1], size[2], size[3]])- return x + residual\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/tps.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/tps.pydeleted file mode 100755index 1fc0cc6b..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/tps.py+++ /dev/null@@ -1,301 +0,0 @@-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import math-import os, sys-import torch-import torch.nn as nn-import torch.nn.functional as F-from pytorchocr.modeling.common import Activation-# import paddle-# from paddle import nn, ParamAttr-# from paddle.nn import functional as F-import numpy as np---class ConvBNLayer(nn.Module):- def __init__(self,- in_channels,- out_channels,- kernel_size,- stride=1,- groups=1,- act=None,- name=None):- super(ConvBNLayer, self).__init__()- self.conv = nn.Conv2d(- in_channels=in_channels,- out_channels=out_channels,- kernel_size=kernel_size,- stride=stride,- padding=(kernel_size - 1) // 2,- groups=groups,- bias=False,- )- bn_name = "bn_" + name- self.bn = nn.BatchNorm2d(- out_channels, )- self.act = act- if act is not None:- self._act = Activation(act)-- def forward(self, x):- x = self.conv(x)- x = self.bn(x)- if self.act is not None:- x = self._act(x)- return x---class LocalizationNetwork(nn.Module):- def __init__(self, in_channels, num_fiducial, loc_lr, model_name):- super(LocalizationNetwork, self).__init__()- self.F = num_fiducial- F = num_fiducial- if model_name == "large":- num_filters_list = [64, 128, 256, 512]- fc_dim = 256- else:- num_filters_list = [16, 32, 64, 128]- fc_dim = 64-- # self.block_list = []- self.block_list = nn.Sequential()- for fno in range(0, len(num_filters_list)):- num_filters = num_filters_list[fno]- name = "loc_conv%d" % fno- # conv = self.add_sublayer(- # name,- # ConvBNLayer(- # in_channels=in_channels,- # out_channels=num_filters,- # kernel_size=3,- # act='relu',- # name=name))- conv = ConvBNLayer(- in_channels=in_channels,- out_channels=num_filters,- kernel_size=3,- act='relu',- name=name)- # self.block_list.append(conv)- self.block_list.add_module(name, conv)- if fno == len(num_filters_list) - 1:- pool = nn.AdaptiveAvgPool2d(1)- else:- # pool = nn.MaxPool2D(kernel_size=2, stride=2, padding=0)- pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)- in_channels = num_filters- # self.block_list.append(pool)- self.block_list.add_module('{}_pool'.format(name), pool)- name = "loc_fc1"- stdv = 1.0 / math.sqrt(num_filters_list[-1] * 1.0)- self.fc1 = nn.Linear(- in_channels,- fc_dim,- bias=True,- )--- # Init fc2 in LocalizationNetwork- initial_bias = self.get_initial_fiducials()- initial_bias = initial_bias.reshape(-1)- name = "loc_fc2"- self.fc2 = nn.Linear(- fc_dim,- F * 2,- bias=True- )- self.out_channels = F * 2-- def forward(self, x):- """- Estimating parameters of geometric transformation- Args:- image: input- Return:- batch_C_prime: the matrix of the geometric transformation- """- B = x.shape[0]- i = 0- for block in self.block_list:- x = block(x)- x = x.squeeze(dim=2).squeeze(dim=2)- x = self.fc1(x)-- x = F.relu(x)- x = self.fc2(x)- x = x.reshape(shape=[-1, self.F, 2])- return x-- def get_initial_fiducials(self):- """ see RARE paper Fig. 6 (a) """- F = self.F- ctrl_pts_x = np.linspace(-1.0, 1.0, int(F / 2))- ctrl_pts_y_top = np.linspace(0.0, -1.0, num=int(F / 2))- ctrl_pts_y_bottom = np.linspace(1.0, 0.0, num=int(F / 2))- ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)- ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)- initial_bias = np.concatenate([ctrl_pts_top, ctrl_pts_bottom], axis=0)- return initial_bias---class GridGenerator(nn.Module):- def __init__(self, in_channels, num_fiducial):- super(GridGenerator, self).__init__()- self.eps = 1e-6- self.F = num_fiducial-- name = "ex_fc"- self.fc = nn.Linear(- in_channels,- 6,- bias=True- )-- def forward(self, batch_C_prime, I_r_size):- """- Generate the grid for the grid_sampler.- Args:- batch_C_prime: the matrix of the geometric transformation- I_r_size: the shape of the input image- Return:- batch_P_prime: the grid for the grid_sampler- """- C = self.build_C_paddle()- P = self.build_P_paddle(I_r_size)-- inv_delta_C_tensor = self.build_inv_delta_C_paddle(C).type(torch.float32)- P_hat_tensor = self.build_P_hat_paddle(- C, torch.as_tensor(P)).type(torch.float32)-- inv_delta_C_tensor.stop_gradient = True- P_hat_tensor.stop_gradient = True-- batch_C_ex_part_tensor = self.get_expand_tensor(batch_C_prime)-- batch_C_ex_part_tensor.stop_gradient = True-- batch_C_prime_with_zeros = torch.cat(- [batch_C_prime, batch_C_ex_part_tensor], dim=1)- inv_delta_C_tensor = inv_delta_C_tensor.to(batch_C_prime_with_zeros.device)- batch_T = torch.matmul(inv_delta_C_tensor, batch_C_prime_with_zeros)- P_hat_tensor = P_hat_tensor.to(batch_T.device)- batch_P_prime = torch.matmul(P_hat_tensor, batch_T)- return batch_P_prime-- def build_C_paddle(self):- """ Return coordinates of fiducial points in I_r; C """- F = self.F- ctrl_pts_x = torch.linspace(-1.0, 1.0, int(F / 2), dtype=torch.float64)- ctrl_pts_y_top = -1 * torch.ones([int(F / 2)], dtype=torch.float64)- ctrl_pts_y_bottom = torch.ones([int(F / 2)], dtype=torch.float64)- ctrl_pts_top = torch.stack([ctrl_pts_x, ctrl_pts_y_top], dim=1)- ctrl_pts_bottom = torch.stack([ctrl_pts_x, ctrl_pts_y_bottom], dim=1)- C = torch.cat([ctrl_pts_top, ctrl_pts_bottom], dim=0)- return C # F x 2-- def build_P_paddle(self, I_r_size):- I_r_height, I_r_width = I_r_size- I_r_grid_x = (torch.arange(- -I_r_width, I_r_width, 2, dtype=torch.float64) + 1.0- ) / torch.as_tensor(np.array([I_r_width]).astype(np.float64))-- I_r_grid_y = (torch.arange(- -I_r_height, I_r_height, 2, dtype=torch.float64) + 1.0- ) / torch.as_tensor(np.array([I_r_height]).astype(np.float64))-- # P: self.I_r_width x self.I_r_height x 2- P = torch.stack(torch.meshgrid([I_r_grid_x, I_r_grid_y]), dim=2)- # P = paddle.transpose(P, perm=[1, 0, 2])- P = P.permute(1, 0, 2)- # n (= self.I_r_width x self.I_r_height) x 2- return P.reshape([-1, 2])-- def build_inv_delta_C_paddle(self, C):- """ Return inv_delta_C which is needed to calculate T """- F = self.F- hat_C = torch.zeros((F, F), dtype=torch.float64) # F x F- for i in range(0, F):- for j in range(i, F):- if i == j:- hat_C[i, j] = 1- else:- r = torch.norm(C[i] - C[j])- hat_C[i, j] = r- hat_C[j, i] = r- hat_C = (hat_C**2) * torch.log(hat_C)- delta_C = torch.cat( # F+3 x F+3- [- torch.cat(- [torch.ones(- (F, 1), dtype=torch.float64), C, hat_C], dim=1), # F x F+3- torch.cat(- [- torch.zeros(- (2, 3), dtype=torch.float64), C.permute(1,0)- ],- dim=1), # 2 x F+3- torch.cat(- [- torch.zeros(- (1, 3), dtype=torch.float64), torch.ones(- (1, F), dtype=torch.float64)- ],- dim=1) # 1 x F+3- ],- dim=0)- inv_delta_C = torch.inverse(delta_C)- return inv_delta_C # F+3 x F+3-- def build_P_hat_paddle(self, C, P):- F = self.F- eps = self.eps- n = P.shape[0] # n (= self.I_r_width x self.I_r_height)- # P_tile: n x 2 -> n x 1 x 2 -> n x F x 2- # P_tile = paddle.tile(paddle.unsqueeze(P, axis=1), (1, F, 1))- P_tile = torch.unsqueeze(P, dim=1).repeat(1, F, 1)- C_tile = torch.unsqueeze(C, dim=0) # 1 x F x 2- P_diff = P_tile - C_tile # n x F x 2- # rbf_norm: n x F- rbf_norm = torch.norm(P_diff, p=2, dim=2, keepdim=False)-- # rbf: n x F- # rbf = torch.mul(- # torch.square(rbf_norm), torch.log(rbf_norm + eps))- rbf = torch.mul(- rbf_norm**2, torch.log(rbf_norm + eps))- P_hat = torch.cat(- [torch.ones(- (n, 1), dtype=torch.float64), P, rbf], dim=1)- return P_hat # n x F+3-- def get_expand_tensor(self, batch_C_prime):- B, H, C = batch_C_prime.shape- batch_C_prime = batch_C_prime.reshape([B, H * C])- batch_C_ex_part_tensor = self.fc(batch_C_prime)- batch_C_ex_part_tensor = batch_C_ex_part_tensor.reshape([-1, 3, 2])- return batch_C_ex_part_tensor---class TPS(nn.Module):- def __init__(self, in_channels, num_fiducial, loc_lr, model_name):- super(TPS, self).__init__()- self.loc_net = LocalizationNetwork(in_channels, num_fiducial, loc_lr,- model_name)- self.grid_generator = GridGenerator(self.loc_net.out_channels,- num_fiducial)- self.out_channels = in_channels-- def forward(self, image):- image.stop_gradient = False- batch_C_prime = self.loc_net(image)- batch_P_prime = self.grid_generator(batch_C_prime, image.shape[2:])- batch_P_prime = batch_P_prime.reshape(- [-1, image.shape[2], image.shape[3], 2])- if torch.__version__ < '1.3.0':- batch_I_r = F.grid_sample(image, grid=batch_P_prime)- else:- batch_I_r = F.grid_sample(image, grid=batch_P_prime, align_corners=True)- return batch_I_rdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/tps_spatial_transformer.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/tps_spatial_transformer.pydeleted file mode 100755index 2241307d..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/tps_spatial_transformer.py+++ /dev/null@@ -1,136 +0,0 @@-"""-This code is refer from:-https://github.com/ayumiymk/aster.pytorch/blob/master/lib/models/tps_spatial_transformer.py-"""-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import math-import torch-from torch import nn-from torch.nn import functional as F-import numpy as np-import itertools---def grid_sample(input, grid, canvas=None):- input.stop_gradient = False- output = F.grid_sample(input, grid, align_corners=True) if torch.__version__ >= '1.3.0' else F.grid_sample(input, grid)- if canvas is None:- return output- else:- # input_mask = paddle.ones(shape=input.shape)- input_mask = input.data.new(input.size()).fill_(1)- output_mask = F.grid_sample(input_mask, grid)- padded_output = output * output_mask + canvas * (1 - output_mask)- return padded_output---# phi(x1, x2) = r^2 * log(r), where r = ||x1 - x2||_2-def compute_partial_repr(input_points, control_points):- N = input_points.shape[0]- M = control_points.shape[0]- # pairwise_diff = input_points.view(N, 1, 2) - control_points.view(1, M, 2)- pairwise_diff = torch.reshape(- input_points, shape=[N, 1, 2]) - torch.reshape(- control_points, shape=[1, M, 2])- # original implementation, very slow- # pairwise_dist = torch.sum(pairwise_diff ** 2, dim = 2) # square of distance- pairwise_diff_square = pairwise_diff * pairwise_diff- pairwise_dist = pairwise_diff_square[:, :, 0] + pairwise_diff_square[:, :, 1]- repr_matrix = 0.5 * pairwise_dist * torch.log(pairwise_dist)- # fix numerical error for 0 * log(0), substitute all nan with 0- # mask = np.array(repr_matrix != repr_matrix)- # repr_matrix[mask] = 0- mask = repr_matrix != repr_matrix- repr_matrix.masked_fill_(mask, 0)- return repr_matrix---# output_ctrl_pts are specified, according to our task.-def build_output_control_points(num_control_points, margins):- margin_x, margin_y = margins- num_ctrl_pts_per_side = num_control_points // 2- ctrl_pts_x = np.linspace(margin_x, 1.0 - margin_x, num_ctrl_pts_per_side)- ctrl_pts_y_top = np.ones(num_ctrl_pts_per_side) * margin_y- ctrl_pts_y_bottom = np.ones(num_ctrl_pts_per_side) * (1.0 - margin_y)- ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)- ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)- output_ctrl_pts_arr = np.concatenate(- [ctrl_pts_top, ctrl_pts_bottom], axis=0)- output_ctrl_pts = torch.Tensor(output_ctrl_pts_arr)- return output_ctrl_pts---class TPSSpatialTransformer(nn.Module):- def __init__(self,- output_image_size=None,- num_control_points=None,- margins=None):- super(TPSSpatialTransformer, self).__init__()- self.output_image_size = output_image_size- self.num_control_points = num_control_points- self.margins = margins-- self.target_height, self.target_width = output_image_size- target_control_points = build_output_control_points(num_control_points,- margins)- N = num_control_points-- # create padded kernel matrix- forward_kernel = torch.zeros(N + 3, N + 3)- target_control_partial_repr = compute_partial_repr(target_control_points, target_control_points)- forward_kernel[:N, :N].copy_(target_control_partial_repr)- forward_kernel[:N, -3].fill_(1)- forward_kernel[-3, :N].fill_(1)- forward_kernel[:N, -2:].copy_(target_control_points)- forward_kernel[-2:, :N].copy_(target_control_points.transpose(0, 1))- # compute inverse matrix- inverse_kernel = torch.inverse(forward_kernel)-- # create target cordinate matrix- HW = self.target_height * self.target_width- target_coordinate = list(- itertools.product(- range(self.target_height), range(self.target_width)))- target_coordinate = torch.Tensor(target_coordinate) # HW x 2- Y, X = target_coordinate.split(1, dim = 1)- Y = Y / (self.target_height - 1)- X = X / (self.target_width - 1)- target_coordinate = torch.cat([X, Y], dim = 1) # convert from (y, x) to (x, y)- target_coordinate_partial_repr = compute_partial_repr(- target_coordinate, target_control_points)- target_coordinate_repr = torch.cat(- [- target_coordinate_partial_repr,- torch.ones(HW, 1),- target_coordinate- ],- dim=1)-- # register precomputed matrices- self.inverse_kernel = inverse_kernel- self.padding_matrix = torch.zeros(3, 2)- self.target_coordinate_repr = target_coordinate_repr- self.target_control_points = target_control_points-- def forward(self, input, source_control_points):- assert source_control_points.ndimension() == 3- assert source_control_points.shape[1] == self.num_control_points- assert source_control_points.shape[2] == 2- batch_size = source_control_points.size(0)-- Y = torch.cat([source_control_points, self.padding_matrix.expand(batch_size, 3, 2)], 1)- mapping_matrix = torch.matmul(self.inverse_kernel, Y)- source_coordinate = torch.matmul(self.target_coordinate_repr, mapping_matrix)-- # grid = source_coordinate.view(-1, self.target_height, self.target_width, 2)- grid = torch.reshape(- source_coordinate,- shape=[-1, self.target_height, self.target_width, 2])- grid = torch.clamp(grid, 0, 1) # the source_control_points may be out of [0, 1].- # the input to grid_sample is normalized [-1, 1], but what we get is [0, 1]- grid = 2.0 * grid - 1.0- output_maps = grid_sample(input, grid, canvas=None)- return output_maps, source_coordinatediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/tsrn.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/tsrn.pydeleted file mode 100755index f7ee9c31..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/transforms/tsrn.py+++ /dev/null@@ -1,220 +0,0 @@-# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.-"""-This code is refer from:-https://github.com/FudanVI/FudanOCR/blob/main/text-gestalt/model/tsrn.py-"""--import math-import torch-import torch.nn.functional as F-from torch import nn-from collections import OrderedDict-import sys-import numpy as np-import warnings-import math, copy-import cv2--warnings.filterwarnings("ignore")--from .tps_spatial_transformer import TPSSpatialTransformer-from .stn import STN as STN_model-from pytorchocr.modeling.heads.sr_rensnet_transformer import Transformer---class TSRN(nn.Module):- def __init__(self,- in_channels,- scale_factor=2,- width=128,- height=32,- STN=False,- srb_nums=5,- mask=False,- hidden_units=32,- infer_mode=False,- **kwargs):- super(TSRN, self).__init__()- in_planes = 3- if mask:- in_planes = 4- assert math.log(scale_factor, 2) % 1 == 0- upsample_block_num = int(math.log(scale_factor, 2))- self.block1 = nn.Sequential(- nn.Conv2d(- in_planes, 2 * hidden_units, kernel_size=9, padding=4),- nn.PReLU())- self.srb_nums = srb_nums- for i in range(srb_nums):- setattr(self, 'block%d' % (i + 2),- RecurrentResidualBlock(2 * hidden_units))-- setattr(- self,- 'block%d' % (srb_nums + 2),- nn.Sequential(- nn.Conv2d(- 2 * hidden_units,- 2 * hidden_units,- kernel_size=3,- padding=1),- nn.BatchNorm2d(2 * hidden_units)))-- block_ = [- UpsampleBLock(2 * hidden_units, 2)- for _ in range(upsample_block_num)- ]- block_.append(- nn.Conv2d(2 * hidden_units, in_planes, kernel_size=9, padding=4)- )- setattr(self, 'block%d' % (srb_nums + 3), nn.Sequential(*block_))- self.tps_inputsize = [height // scale_factor, width // scale_factor]- tps_outputsize = [height // scale_factor, width // scale_factor]- num_control_points = 20- tps_margins = [0.05, 0.05]- self.stn = STN- if self.stn:- self.tps = TPSSpatialTransformer(- output_image_size=tuple(tps_outputsize),- num_control_points=num_control_points,- margins=tuple(tps_margins))-- self.stn_head = STN_model(- in_channels=in_planes,- num_ctrlpoints=num_control_points,- activation='none')- self.out_channels = in_channels-- self.r34_transformer = Transformer()- for param in self.r34_transformer.parameters():- param.trainable = False- self.infer_mode = infer_mode-- def forward(self, x):- output = {}- if self.infer_mode:- output["lr_img"] = x- y = x- else:- output["lr_img"] = x[0]- output["hr_img"] = x[1]- y = x[0]- if self.stn and self.training:- _, ctrl_points_x = self.stn_head(y)- y, _ = self.tps(y, ctrl_points_x)- block = {'1': self.block1(y)}- for i in range(self.srb_nums + 1):- block[str(i + 2)] = getattr(self,- 'block%d' % (i + 2))(block[str(i + 1)])-- block[str(self.srb_nums + 3)] = getattr(self, 'block%d' % (self.srb_nums + 3)) \- ((block['1'] + block[str(self.srb_nums + 2)]))-- sr_img = torch.tanh(block[str(self.srb_nums + 3)])-- output["sr_img"] = sr_img-- if self.training:- hr_img = x[1]- length = x[2]- input_tensor = x[3]-- # add transformer- sr_pred, word_attention_map_pred, _ = self.r34_transformer(- sr_img, length, input_tensor)-- hr_pred, word_attention_map_gt, _ = self.r34_transformer(- hr_img, length, input_tensor)-- output["hr_img"] = hr_img- output["hr_pred"] = hr_pred- output["word_attention_map_gt"] = word_attention_map_gt- output["sr_pred"] = sr_pred- output["word_attention_map_pred"] = word_attention_map_pred-- return output---class RecurrentResidualBlock(nn.Module):- def __init__(self, channels):- super(RecurrentResidualBlock, self).__init__()- self.conv1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)- self.bn1 = nn.BatchNorm2d(channels)- self.gru1 = GruBlock(channels, channels)- self.prelu = mish()- self.conv2 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)- self.bn2 = nn.BatchNorm2d(channels)- self.gru2 = GruBlock(channels, channels)-- def forward(self, x):- residual = self.conv1(x)- residual = self.bn1(residual)- residual = self.prelu(residual)- residual = self.conv2(residual)- residual = self.bn2(residual)- residual = self.gru1(residual.permute(0, 1, 3, 2).contiguous()).permute(0, 1, 3, 2).contiguous()-- return self.gru2(x + residual).contiguous()---class UpsampleBLock(nn.Module):- def __init__(self, in_channels, up_scale):- super(UpsampleBLock, self).__init__()- self.conv = nn.Conv2d(- in_channels, in_channels * up_scale**2, kernel_size=3, padding=1)-- self.pixel_shuffle = nn.PixelShuffle(up_scale)- self.prelu = mish()-- def forward(self, x):- x = self.conv(x)- x = self.pixel_shuffle(x)- x = self.prelu(x)- return x---class mish(nn.Module):- def __init__(self, ):- super(mish, self).__init__()- self.activated = True-- def forward(self, x):- if self.activated:- x = x * (torch.tanh(F.softplus(x)))- return x---class GruBlock(nn.Module):- def __init__(self, in_channels, out_channels):- super(GruBlock, self).__init__()- assert out_channels % 2 == 0- self.conv1 = nn.Conv2d(- in_channels, out_channels, kernel_size=1, padding=0)- self.gru = nn.GRU(out_channels,- out_channels // 2,- bidirectional=True,- batch_first=True,- )-- def forward(self, x):- # x: b, c, w, h- x = self.conv1(x)- x = x.permute(0, 2, 3, 1).contiguous() # b, w, h, c- batch_size, w, h, c = x.size()- x = x.view(batch_size * w, h, c) # b*w, h, c- x, _ = self.gru(x)- x = x.view(batch_size, w, h, c)- x = x.permute(0, 3, 1, 2).contiguous()- return xdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/__init__.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/__init__.pyindex fc20314b..40603ade 100755--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/__init__.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/__init__.py@@ -11,26 +11,18 @@ __all__ = ['build_post_process']def build_post_process(config, global_config=None):from .db_postprocess import DBPostProcess- from .east_postprocess import EASTPostProcess- from .sast_postprocess import SASTPostProcess- from .fce_postprocess import FCEPostProcessfrom .rec_postprocess import CTCLabelDecode, AttnLabelDecode, SRNLabelDecode, TableLabelDecode, \NRTRLabelDecode, SARLabelDecode, ViTSTRLabelDecode, RFLLabelDecodefrom .cls_postprocess import ClsPostProcess- from .pg_postprocess import PGPostProcessfrom .rec_postprocess import CANLabelDecodesupport_dict = [- 'DBPostProcess', 'EASTPostProcess', 'SASTPostProcess', 'CTCLabelDecode',- 'AttnLabelDecode', 'ClsPostProcess', 'SRNLabelDecode', 'PGPostProcess',- 'TableLabelDecode', 'NRTRLabelDecode', 'SARLabelDecode', 'FCEPostProcess',+ 'DBPostProcess', 'CTCLabelDecode',+ 'AttnLabelDecode', 'ClsPostProcess', 'SRNLabelDecode',+ 'TableLabelDecode', 'NRTRLabelDecode', 'SARLabelDecode','ViTSTRLabelDecode','CANLabelDecode', 'RFLLabelDecode']- if config['name'] == 'PSEPostProcess':- from .pse_postprocess import PSEPostProcess- support_dict.append('PSEPostProcess')-config = copy.deepcopy(config)module_name = config.pop('name')if global_config is not None:diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/east_postprocess.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/east_postprocess.pydeleted file mode 100755index 10bb9164..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/east_postprocess.py+++ /dev/null@@ -1,144 +0,0 @@-# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.--from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import numpy as np-from .locality_aware_nms import nms_locality-import cv2-# import paddle-import torch--import os-import sys---class EASTPostProcess(object):- """- The post process for EAST.- """-- def __init__(self,- score_thresh=0.8,- cover_thresh=0.1,- nms_thresh=0.2,- **kwargs):-- self.score_thresh = score_thresh- self.cover_thresh = cover_thresh- self.nms_thresh = nms_thresh-- # c++ la-nms is faster, but only support python 3.5- self.is_python35 = False- if sys.version_info.major == 3 and sys.version_info.minor == 5:- self.is_python35 = True-- def restore_rectangle_quad(self, origin, geometry):- """- Restore rectangle from quadrangle.- """- # quad- origin_concat = np.concatenate(- (origin, origin, origin, origin), axis=1) # (n, 8)- pred_quads = origin_concat - geometry- pred_quads = pred_quads.reshape((-1, 4, 2)) # (n, 4, 2)- return pred_quads-- def detect(self,- score_map,- geo_map,- score_thresh=0.8,- cover_thresh=0.1,- nms_thresh=0.2):- """- restore text boxes from score map and geo map- """- score_map = score_map[0]- geo_map = np.swapaxes(geo_map, 1, 0)- geo_map = np.swapaxes(geo_map, 1, 2)- # filter the score map- xy_text = np.argwhere(score_map > score_thresh)- if len(xy_text) == 0:- return []- # sort the text boxes via the y axis- xy_text = xy_text[np.argsort(xy_text[:, 0])]- # restore quad proposals- text_box_restored = self.restore_rectangle_quad(- xy_text[:, ::-1] * 4, geo_map[xy_text[:, 0], xy_text[:, 1], :])- boxes = np.zeros((text_box_restored.shape[0], 9), dtype=np.float32)- boxes[:, :8] = text_box_restored.reshape((-1, 8))- boxes[:, 8] = score_map[xy_text[:, 0], xy_text[:, 1]]- if self.is_python35:- import lanms- boxes = lanms.merge_quadrangle_n9(boxes, nms_thresh)- else:- boxes = nms_locality(boxes.astype(np.float64), nms_thresh)- if boxes.shape[0] == 0:- return []- # Here we filter some low score boxes by the average score map,- # this is different from the orginal paper.- for i, box in enumerate(boxes):- mask = np.zeros_like(score_map, dtype=np.uint8)- cv2.fillPoly(mask, box[:8].reshape(- (-1, 4, 2)).astype(np.int32) // 4, 1)- boxes[i, 8] = cv2.mean(score_map, mask)[0]- boxes = boxes[boxes[:, 8] > cover_thresh]- return boxes-- def sort_poly(self, p):- """- Sort polygons.- """- min_axis = np.argmin(np.sum(p, axis=1))- p = p[[min_axis, (min_axis + 1) % 4, \- (min_axis + 2) % 4, (min_axis + 3) % 4]]- if abs(p[0, 0] - p[1, 0]) > abs(p[0, 1] - p[1, 1]):- return p- else:- return p[[0, 3, 2, 1]]-- def __call__(self, outs_dict, shape_list):- score_list = outs_dict['f_score']- geo_list = outs_dict['f_geo']- if isinstance(score_list, torch.Tensor):- score_list = score_list.cpu().numpy()- geo_list = geo_list.cpu().numpy()- img_num = len(shape_list)- dt_boxes_list = []- for ino in range(img_num):- score = score_list[ino]- geo = geo_list[ino]- boxes = self.detect(- score_map=score,- geo_map=geo,- score_thresh=self.score_thresh,- cover_thresh=self.cover_thresh,- nms_thresh=self.nms_thresh)- boxes_norm = []- if len(boxes) > 0:- h, w = score.shape[1:]- src_h, src_w, ratio_h, ratio_w = shape_list[ino]- boxes = boxes[:, :8].reshape((-1, 4, 2))- boxes[:, :, 0] /= ratio_w- boxes[:, :, 1] /= ratio_h- for i_box, box in enumerate(boxes):- box = self.sort_poly(box.astype(np.int32))- if np.linalg.norm(box[0] - box[1]) < 5 \- or np.linalg.norm(box[3] - box[0]) < 5:- continue- boxes_norm.append(box)- dt_boxes_list.append({'points': np.array(boxes_norm)})- return dt_boxes_list\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/fce_postprocess.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/fce_postprocess.pydeleted file mode 100755index ae4633fb..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/fce_postprocess.py+++ /dev/null@@ -1,228 +0,0 @@-"""-This code is refer from:-https://github.com/open-mmlab/mmocr/blob/v0.3.0/mmocr/models/textdet/postprocess/wrapper.py-"""--import cv2-import torch-import numpy as np-from numpy.fft import ifft-from pytorchocr.utils.poly_nms import poly_nms, valid_boundary---def fill_hole(input_mask):- h, w = input_mask.shape- canvas = np.zeros((h + 2, w + 2), np.uint8)- canvas[1:h + 1, 1:w + 1] = input_mask.copy()-- mask = np.zeros((h + 4, w + 4), np.uint8)-- cv2.floodFill(canvas, mask, (0, 0), 1)- canvas = canvas[1:h + 1, 1:w + 1].astype(np.bool)-- return ~canvas | input_mask---def fourier2poly(fourier_coeff, num_reconstr_points=50):- """ Inverse Fourier transform- Args:- fourier_coeff (ndarray): Fourier coefficients shaped (n, 2k+1),- with n and k being candidates number and Fourier degree- respectively.- num_reconstr_points (int): Number of reconstructed polygon points.- Returns:- Polygons (ndarray): The reconstructed polygons shaped (n, n')- """-- a = np.zeros((len(fourier_coeff), num_reconstr_points), dtype='complex')- k = (len(fourier_coeff[0]) - 1) // 2-- a[:, 0:k + 1] = fourier_coeff[:, k:]- a[:, -k:] = fourier_coeff[:, :k]-- poly_complex = ifft(a) * num_reconstr_points- polygon = np.zeros((len(fourier_coeff), num_reconstr_points, 2))- polygon[:, :, 0] = poly_complex.real- polygon[:, :, 1] = poly_complex.imag- return polygon.astype('int32').reshape((len(fourier_coeff), -1))---class FCEPostProcess(object):- """- The post process for FCENet.- """-- def __init__(self,- scales,- fourier_degree=5,- num_reconstr_points=50,- decoding_type='fcenet',- score_thr=0.3,- nms_thr=0.1,- alpha=1.0,- beta=1.0,- box_type='poly',- **kwargs):-- self.scales = scales- self.fourier_degree = fourier_degree- self.num_reconstr_points = num_reconstr_points- self.decoding_type = decoding_type- self.score_thr = score_thr- self.nms_thr = nms_thr- self.alpha = alpha- self.beta = beta- self.box_type = box_type-- def __call__(self, preds, shape_list):- score_maps = []- for key, value in preds.items():- if isinstance(value, torch.Tensor):- value = value.numpy()- cls_res = value[:, :4, :, :]- reg_res = value[:, 4:, :, :]- score_maps.append([cls_res, reg_res])-- return self.get_boundary(score_maps, shape_list)-- def resize_boundary(self, boundaries, scale_factor):- """Rescale boundaries via scale_factor.-- Args:- boundaries (list[list[float]]): The boundary list. Each boundary- with size 2k+1 with k>=4.- scale_factor(ndarray): The scale factor of size (4,).-- Returns:- boundaries (list[list[float]]): The scaled boundaries.- """- boxes = []- scores = []- for b in boundaries:- sz = len(b)- valid_boundary(b, True)- scores.append(b[-1])- b = (np.array(b[:sz - 1]) *- (np.tile(scale_factor[:2], int(- (sz - 1) / 2)).reshape(1, sz - 1))).flatten().tolist()- boxes.append(np.array(b).reshape([-1, 2]))-- return np.array(boxes, dtype=np.float32), scores-- def get_boundary(self, score_maps, shape_list):- assert len(score_maps) == len(self.scales)- boundaries = []- for idx, score_map in enumerate(score_maps):- scale = self.scales[idx]- boundaries = boundaries + self._get_boundary_single(score_map,- scale)-- # nms- boundaries = poly_nms(boundaries, self.nms_thr)- boundaries, scores = self.resize_boundary(- boundaries, (1 / shape_list[0, 2:]).tolist()[::-1])-- boxes_batch = [dict(points=boundaries, scores=scores)]- return boxes_batch-- def _get_boundary_single(self, score_map, scale):- assert len(score_map) == 2- assert score_map[1].shape[1] == 4 * self.fourier_degree + 2-- return self.fcenet_decode(- preds=score_map,- fourier_degree=self.fourier_degree,- num_reconstr_points=self.num_reconstr_points,- scale=scale,- alpha=self.alpha,- beta=self.beta,- box_type=self.box_type,- score_thr=self.score_thr,- nms_thr=self.nms_thr)-- def fcenet_decode(self,- preds,- fourier_degree,- num_reconstr_points,- scale,- alpha=1.0,- beta=2.0,- box_type='poly',- score_thr=0.3,- nms_thr=0.1):- """Decoding predictions of FCENet to instances.-- Args:- preds (list(Tensor)): The head output tensors.- fourier_degree (int): The maximum Fourier transform degree k.- num_reconstr_points (int): The points number of the polygon- reconstructed from predicted Fourier coefficients.- scale (int): The down-sample scale of the prediction.- alpha (float) : The parameter to calculate final scores. Score_{final}- = (Score_{text region} ^ alpha)- * (Score_{text center region}^ beta)- beta (float) : The parameter to calculate final score.- box_type (str): Boundary encoding type 'poly' or 'quad'.- score_thr (float) : The threshold used to filter out the final- candidates.- nms_thr (float) : The threshold of nms.-- Returns:- boundaries (list[list[float]]): The instance boundary and confidence- list.- """- assert isinstance(preds, list)- assert len(preds) == 2- assert box_type in ['poly', 'quad']-- cls_pred = preds[0][0]- tr_pred = cls_pred[0:2]- tcl_pred = cls_pred[2:]-- reg_pred = preds[1][0].transpose([1, 2, 0])- x_pred = reg_pred[:, :, :2 * fourier_degree + 1]- y_pred = reg_pred[:, :, 2 * fourier_degree + 1:]-- score_pred = (tr_pred[1]**alpha) * (tcl_pred[1]**beta)- tr_pred_mask = (score_pred) > score_thr- tr_mask = fill_hole(tr_pred_mask)-- tr_contours, _ = cv2.findContours(- tr_mask.astype(np.uint8), cv2.RETR_TREE,- cv2.CHAIN_APPROX_SIMPLE) # opencv4-- mask = np.zeros_like(tr_mask)- boundaries = []- for cont in tr_contours:- deal_map = mask.copy().astype(np.int8)- cv2.drawContours(deal_map, [cont], -1, 1, -1)-- score_map = score_pred * deal_map- score_mask = score_map > 0- xy_text = np.argwhere(score_mask)- dxy = xy_text[:, 1] + xy_text[:, 0] * 1j-- x, y = x_pred[score_mask], y_pred[score_mask]- c = x + y * 1j- c[:, fourier_degree] = c[:, fourier_degree] + dxy- c *= scale-- polygons = fourier2poly(c, num_reconstr_points)- score = score_map[score_mask].reshape(-1, 1)- polygons = poly_nms(np.hstack((polygons, score)).tolist(), nms_thr)-- boundaries = boundaries + polygons-- boundaries = poly_nms(boundaries, nms_thr)-- if box_type == 'quad':- new_boundaries = []- for boundary in boundaries:- poly = np.array(boundary[:-1]).reshape(-1, 2).astype(np.float32)- score = boundary[-1]- points = cv2.boxPoints(cv2.minAreaRect(poly))- points = np.int0(points)- new_boundaries.append(points.reshape(-1).tolist() + [score])- boundaries = new_boundaries-- return boundariesdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/locality_aware_nms.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/locality_aware_nms.pydeleted file mode 100755index 53280cc1..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/locality_aware_nms.py+++ /dev/null@@ -1,199 +0,0 @@-"""-Locality aware nms.-"""--import numpy as np-from shapely.geometry import Polygon---def intersection(g, p):- """- Intersection.- """- g = Polygon(g[:8].reshape((4, 2)))- p = Polygon(p[:8].reshape((4, 2)))- g = g.buffer(0)- p = p.buffer(0)- if not g.is_valid or not p.is_valid:- return 0- inter = Polygon(g).intersection(Polygon(p)).area- union = g.area + p.area - inter- if union == 0:- return 0- else:- return inter / union---def intersection_iog(g, p):- """- Intersection_iog.- """- g = Polygon(g[:8].reshape((4, 2)))- p = Polygon(p[:8].reshape((4, 2)))- if not g.is_valid or not p.is_valid:- return 0- inter = Polygon(g).intersection(Polygon(p)).area- #union = g.area + p.area - inter- union = p.area- if union == 0:- print("p_area is very small")- return 0- else:- return inter / union---def weighted_merge(g, p):- """- Weighted merge.- """- g[:8] = (g[8] * g[:8] + p[8] * p[:8]) / (g[8] + p[8])- g[8] = (g[8] + p[8])- return g---def standard_nms(S, thres):- """- Standard nms.- """- order = np.argsort(S[:, 8])[::-1]- keep = []- while order.size > 0:- i = order[0]- keep.append(i)- ovr = np.array([intersection(S[i], S[t]) for t in order[1:]])-- inds = np.where(ovr <= thres)[0]- order = order[inds + 1]-- return S[keep]---def standard_nms_inds(S, thres):- """- Standard nms, retun inds.- """- order = np.argsort(S[:, 8])[::-1]- keep = []- while order.size > 0:- i = order[0]- keep.append(i)- ovr = np.array([intersection(S[i], S[t]) for t in order[1:]])-- inds = np.where(ovr <= thres)[0]- order = order[inds + 1]-- return keep---def nms(S, thres):- """- nms.- """- order = np.argsort(S[:, 8])[::-1]- keep = []- while order.size > 0:- i = order[0]- keep.append(i)- ovr = np.array([intersection(S[i], S[t]) for t in order[1:]])-- inds = np.where(ovr <= thres)[0]- order = order[inds + 1]-- return keep---def soft_nms(boxes_in, Nt_thres=0.3, threshold=0.8, sigma=0.5, method=2):- """- soft_nms- :para boxes_in, N x 9 (coords + score)- :para threshould, eliminate cases min score(0.001)- :para Nt_thres, iou_threshi- :para sigma, gaussian weght- :method, linear or gaussian- """- boxes = boxes_in.copy()- N = boxes.shape[0]- if N is None or N < 1:- return np.array([])- pos, maxpos = 0, 0- weight = 0.0- inds = np.arange(N)- tbox, sbox = boxes[0].copy(), boxes[0].copy()- for i in range(N):- maxscore = boxes[i, 8]- maxpos = i- tbox = boxes[i].copy()- ti = inds[i]- pos = i + 1- #get max box- while pos < N:- if maxscore < boxes[pos, 8]:- maxscore = boxes[pos, 8]- maxpos = pos- pos = pos + 1- #add max box as a detection- boxes[i, :] = boxes[maxpos, :]- inds[i] = inds[maxpos]- #swap- boxes[maxpos, :] = tbox- inds[maxpos] = ti- tbox = boxes[i].copy()- pos = i + 1- #NMS iteration- while pos < N:- sbox = boxes[pos].copy()- ts_iou_val = intersection(tbox, sbox)- if ts_iou_val > 0:- if method == 1:- if ts_iou_val > Nt_thres:- weight = 1 - ts_iou_val- else:- weight = 1- elif method == 2:- weight = np.exp(-1.0 * ts_iou_val**2 / sigma)- else:- if ts_iou_val > Nt_thres:- weight = 0- else:- weight = 1- boxes[pos, 8] = weight * boxes[pos, 8]- #if box score falls below thresold, discard the box by- #swaping last box update N- if boxes[pos, 8] < threshold:- boxes[pos, :] = boxes[N - 1, :]- inds[pos] = inds[N - 1]- N = N - 1- pos = pos - 1- pos = pos + 1-- return boxes[:N]---def nms_locality(polys, thres=0.3):- """- locality aware nms of EAST- :param polys: a N*9 numpy array. first 8 coordinates, then prob- :return: boxes after nms- """- S = []- p = None- for g in polys:- if p is not None and intersection(g, p) > thres:- p = weighted_merge(g, p)- else:- if p is not None:- S.append(p)- p = g- if p is not None:- S.append(p)-- if len(S) == 0:- return np.array([])- return standard_nms(np.array(S), thres)---if __name__ == '__main__':- # 343,350,448,135,474,143,369,359- print(- Polygon(np.array([[343, 350], [448, 135], [474, 143], [369, 359]]))- .area)\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pg_postprocess.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pg_postprocess.pydeleted file mode 100755index 81a8e08c..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pg_postprocess.py+++ /dev/null@@ -1,52 +0,0 @@-# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.--from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import os-import sys--__dir__ = os.path.dirname(__file__)-sys.path.append(__dir__)-sys.path.append(os.path.join(__dir__, '..'))-from pytorchocr.utils.e2e_utils.pgnet_pp_utils import PGNet_PostProcess---class PGPostProcess(object):- """- The post process for PGNet.- """-- def __init__(self, character_dict_path, valid_set, score_thresh, mode,- **kwargs):- self.character_dict_path = character_dict_path- self.valid_set = valid_set- self.score_thresh = score_thresh- self.mode = mode-- # c++ la-nms is faster, but only support python 3.5- self.is_python35 = False- if sys.version_info.major == 3 and sys.version_info.minor == 5:- self.is_python35 = True-- def __call__(self, outs_dict, shape_list):- post = PGNet_PostProcess(self.character_dict_path, self.valid_set,- self.score_thresh, outs_dict, shape_list)- if self.mode == 'fast':- data = post.pg_postprocess_fast()- else:- data = post.pg_postprocess_slow()- return datadiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/__init__.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/__init__.pydeleted file mode 100755index 680473bf..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/__init__.py+++ /dev/null@@ -1,15 +0,0 @@-# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.--from .pse_postprocess import PSEPostProcess\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse/README.md b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse/README.mddeleted file mode 100755index 6a19d5d1..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse/README.md+++ /dev/null@@ -1,6 +0,0 @@-## 编译-This code is refer from:-https://github.com/whai362/PSENet/blob/python3/models/post_processing/pse-```python-python3 setup.py build_ext --inplace-```diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse/__init__.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse/__init__.pydeleted file mode 100755index ce0142f5..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse/__init__.py+++ /dev/null@@ -1,29 +0,0 @@-# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.-import sys-import os-import subprocess--python_path = sys.executable--ori_path = os.getcwd()-os.chdir('pytorchocr/postprocess/pse_postprocess/pse')-if subprocess.call(- '{} setup.py build_ext --inplace'.format(python_path), shell=True) != 0:- raise RuntimeError(- 'Cannot compile pse: {}, if your system is windows, you need to install all the default components of `desktop development using C++` in visual studio 2019+'.- format(os.path.dirname(os.path.realpath(__file__))))-os.chdir(ori_path)--from .pse import psediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse/pse.pyx b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse/pse.pyxdeleted file mode 100755index b2be49e9..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse/pse.pyx+++ /dev/null@@ -1,70 +0,0 @@--import numpy as np-import cv2-cimport numpy as np-cimport cython-cimport libcpp-cimport libcpp.pair-cimport libcpp.queue-from libcpp.pair cimport *-from libcpp.queue cimport *-[email protected](False)[email protected](False)-cdef np.ndarray[np.int32_t, ndim=2] _pse(np.ndarray[np.uint8_t, ndim=3] kernels,- np.ndarray[np.int32_t, ndim=2] label,- int kernel_num,- int label_num,- float min_area=0):- cdef np.ndarray[np.int32_t, ndim=2] pred- pred = np.zeros((label.shape[0], label.shape[1]), dtype=np.int32)-- for label_idx in range(1, label_num):- if np.sum(label == label_idx) < min_area:- label[label == label_idx] = 0-- cdef libcpp.queue.queue[libcpp.pair.pair[np.int16_t,np.int16_t]] que = \- queue[libcpp.pair.pair[np.int16_t,np.int16_t]]()- cdef libcpp.queue.queue[libcpp.pair.pair[np.int16_t,np.int16_t]] nxt_que = \- queue[libcpp.pair.pair[np.int16_t,np.int16_t]]()- cdef np.int16_t* dx = [-1, 1, 0, 0]- cdef np.int16_t* dy = [0, 0, -1, 1]- cdef np.int16_t tmpx, tmpy-- points = np.array(np.where(label > 0)).transpose((1, 0))- for point_idx in range(points.shape[0]):- tmpx, tmpy = points[point_idx, 0], points[point_idx, 1]- que.push(pair[np.int16_t,np.int16_t](tmpx, tmpy))- pred[tmpx, tmpy] = label[tmpx, tmpy]-- cdef libcpp.pair.pair[np.int16_t,np.int16_t] cur- cdef int cur_label- for kernel_idx in range(kernel_num - 1, -1, -1):- while not que.empty():- cur = que.front()- que.pop()- cur_label = pred[cur.first, cur.second]-- is_edge = True- for j in range(4):- tmpx = cur.first + dx[j]- tmpy = cur.second + dy[j]- if tmpx < 0 or tmpx >= label.shape[0] or tmpy < 0 or tmpy >= label.shape[1]:- continue- if kernels[kernel_idx, tmpx, tmpy] == 0 or pred[tmpx, tmpy] > 0:- continue-- que.push(pair[np.int16_t,np.int16_t](tmpx, tmpy))- pred[tmpx, tmpy] = cur_label- is_edge = False- if is_edge:- nxt_que.push(cur)-- que, nxt_que = nxt_que, que-- return pred--def pse(kernels, min_area):- kernel_num = kernels.shape[0]- label_num, label = cv2.connectedComponents(kernels[-1], connectivity=4)- return _pse(kernels[:-1], label, kernel_num, label_num, min_area)\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse/setup.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse/setup.pydeleted file mode 100755index 03746782..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse/setup.py+++ /dev/null@@ -1,14 +0,0 @@-from distutils.core import setup, Extension-from Cython.Build import cythonize-import numpy--setup(ext_modules=cythonize(Extension(- 'pse',- sources=['pse.pyx'],- language='c++',- include_dirs=[numpy.get_include()],- library_dirs=[],- libraries=[],- extra_compile_args=['-O3'],- extra_link_args=[]-)))diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse_postprocess.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse_postprocess.pydeleted file mode 100755index 531bbcfd..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/pse_postprocess/pse_postprocess.py+++ /dev/null@@ -1,105 +0,0 @@-"""-This code is refer from:-https://github.com/whai362/PSENet/blob/python3/models/head/psenet_head.py-"""--from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import numpy as np-import cv2-import torch-from torch.nn import functional as F--from pytorchocr.postprocess.pse_postprocess.pse import pse---class PSEPostProcess(object):- """- The post process for PSE.- """-- def __init__(self,- thresh=0.5,- box_thresh=0.85,- min_area=16,- box_type='box',- scale=4,- **kwargs):- assert box_type in ['box', 'poly'], 'Only box and poly is supported'- self.thresh = thresh- self.box_thresh = box_thresh- self.min_area = min_area- self.box_type = box_type- self.scale = scale-- def __call__(self, outs_dict, shape_list):- pred = outs_dict['maps']- if not isinstance(pred, torch.Tensor):- pred = torch.as_tensor(pred)- pred = F.interpolate(- pred, scale_factor=4 // self.scale, mode='bilinear')-- score = F.sigmoid(pred[:, 0, :, :])-- kernels = (pred > self.thresh).type(torch.float32)- text_mask = kernels[:, 0, :, :]- kernels[:, 0:, :, :] = kernels[:, 0:, :, :] * text_mask-- score = score.numpy()- kernels = kernels.numpy().astype(np.uint8)-- boxes_batch = []- for batch_index in range(pred.shape[0]):- boxes, scores = self.boxes_from_bitmap(score[batch_index],- kernels[batch_index],- shape_list[batch_index])-- boxes_batch.append({'points': boxes, 'scores': scores})- return boxes_batch-- def boxes_from_bitmap(self, score, kernels, shape):- label = pse(kernels, self.min_area)- return self.generate_box(score, label, shape)-- def generate_box(self, score, label, shape):- src_h, src_w, ratio_h, ratio_w = shape- label_num = np.max(label) + 1-- boxes = []- scores = []- for i in range(1, label_num):- ind = label == i- points = np.array(np.where(ind)).transpose((1, 0))[:, ::-1]-- if points.shape[0] < self.min_area:- label[ind] = 0- continue-- score_i = np.mean(score[ind])- if score_i < self.box_thresh:- label[ind] = 0- continue-- if self.box_type == 'box':- rect = cv2.minAreaRect(points)- bbox = cv2.boxPoints(rect)- elif self.box_type == 'poly':- box_height = np.max(points[:, 1]) + 10- box_width = np.max(points[:, 0]) + 10-- mask = np.zeros((box_height, box_width), np.uint8)- mask[points[:, 1], points[:, 0]] = 255-- contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,- cv2.CHAIN_APPROX_SIMPLE)- bbox = np.squeeze(contours[0], 1)- else:- raise NotImplementedError-- bbox[:, 0] = np.clip(np.round(bbox[:, 0] / ratio_w), 0, src_w)- bbox[:, 1] = np.clip(np.round(bbox[:, 1] / ratio_h), 0, src_h)- boxes.append(bbox)- scores.append(score_i)- return boxes, scoresdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/rec_postprocess.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/rec_postprocess.pyindex b163a5a5..c83fe5c3 100755--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/rec_postprocess.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/rec_postprocess.py@@ -12,9 +12,6 @@# See the License for the specific language governing permissions and# limitations under the License.import numpy as np-import string-#import paddle-# from paddle.nn import functional as Fimport torchdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/sast_postprocess.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/sast_postprocess.pydeleted file mode 100755index 26a03c80..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/sast_postprocess.py+++ /dev/null@@ -1,302 +0,0 @@-# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.--from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import os-import sys--__dir__ = os.path.dirname(__file__)-sys.path.append(__dir__)-sys.path.append(os.path.join(__dir__, '..'))--import numpy as np-from .locality_aware_nms import nms_locality-# import paddle-import torch-import cv2-import time---class SASTPostProcess(object):- """- The post process for SAST.- """-- def __init__(self,- score_thresh=0.5,- nms_thresh=0.2,- sample_pts_num=2,- shrink_ratio_of_width=0.3,- expand_scale=1.0,- tcl_map_thresh=0.5,- **kwargs):-- self.score_thresh = score_thresh- self.nms_thresh = nms_thresh- self.sample_pts_num = sample_pts_num- self.shrink_ratio_of_width = shrink_ratio_of_width- self.expand_scale = expand_scale- self.tcl_map_thresh = tcl_map_thresh-- # c++ la-nms is faster, but only support python 3.5- self.is_python35 = False- if sys.version_info.major == 3 and sys.version_info.minor == 5:- self.is_python35 = True-- def point_pair2poly(self, point_pair_list):- """- Transfer vertical point_pairs into poly point in clockwise.- """- # constract poly- point_num = len(point_pair_list) * 2- point_list = [0] * point_num- for idx, point_pair in enumerate(point_pair_list):- point_list[idx] = point_pair[0]- point_list[point_num - 1 - idx] = point_pair[1]- return np.array(point_list).reshape(-1, 2)-- def shrink_quad_along_width(self, quad, begin_width_ratio=0., end_width_ratio=1.):- """- Generate shrink_quad_along_width.- """- ratio_pair = np.array([[begin_width_ratio], [end_width_ratio]], dtype=np.float32)- p0_1 = quad[0] + (quad[1] - quad[0]) * ratio_pair- p3_2 = quad[3] + (quad[2] - quad[3]) * ratio_pair- return np.array([p0_1[0], p0_1[1], p3_2[1], p3_2[0]])-- def expand_poly_along_width(self, poly, shrink_ratio_of_width=0.3):- """- expand poly along width.- """- point_num = poly.shape[0]- left_quad = np.array([poly[0], poly[1], poly[-2], poly[-1]], dtype=np.float32)- left_ratio = -shrink_ratio_of_width * np.linalg.norm(left_quad[0] - left_quad[3]) / \- (np.linalg.norm(left_quad[0] - left_quad[1]) + 1e-6)- left_quad_expand = self.shrink_quad_along_width(left_quad, left_ratio, 1.0)- right_quad = np.array([poly[point_num // 2 - 2], poly[point_num // 2 - 1],- poly[point_num // 2], poly[point_num // 2 + 1]], dtype=np.float32)- right_ratio = 1.0 + \- shrink_ratio_of_width * np.linalg.norm(right_quad[0] - right_quad[3]) / \- (np.linalg.norm(right_quad[0] - right_quad[1]) + 1e-6)- right_quad_expand = self.shrink_quad_along_width(right_quad, 0.0, right_ratio)- poly[0] = left_quad_expand[0]- poly[-1] = left_quad_expand[-1]- poly[point_num // 2 - 1] = right_quad_expand[1]- poly[point_num // 2] = right_quad_expand[2]- return poly-- def restore_quad(self, tcl_map, tcl_map_thresh, tvo_map):- """Restore quad."""- xy_text = np.argwhere(tcl_map[:, :, 0] > tcl_map_thresh)- xy_text = xy_text[:, ::-1] # (n, 2)-- # Sort the text boxes via the y axis- xy_text = xy_text[np.argsort(xy_text[:, 1])]-- scores = tcl_map[xy_text[:, 1], xy_text[:, 0], 0]- scores = scores[:, np.newaxis]-- # Restore- point_num = int(tvo_map.shape[-1] / 2)- assert point_num == 4- tvo_map = tvo_map[xy_text[:, 1], xy_text[:, 0], :]- xy_text_tile = np.tile(xy_text, (1, point_num)) # (n, point_num * 2)- quads = xy_text_tile - tvo_map-- return scores, quads, xy_text-- def quad_area(self, quad):- """- compute area of a quad.- """- edge = [- (quad[1][0] - quad[0][0]) * (quad[1][1] + quad[0][1]),- (quad[2][0] - quad[1][0]) * (quad[2][1] + quad[1][1]),- (quad[3][0] - quad[2][0]) * (quad[3][1] + quad[2][1]),- (quad[0][0] - quad[3][0]) * (quad[0][1] + quad[3][1])- ]- return np.sum(edge) / 2.-- def nms(self, dets):- if self.is_python35:- import lanms- dets = lanms.merge_quadrangle_n9(dets, self.nms_thresh)- else:- dets = nms_locality(dets, self.nms_thresh)- return dets-- def cluster_by_quads_tco(self, tcl_map, tcl_map_thresh, quads, tco_map):- """- Cluster pixels in tcl_map based on quads.- """- instance_count = quads.shape[0] + 1 # contain background- instance_label_map = np.zeros(tcl_map.shape[:2], dtype=np.int32)- if instance_count == 1:- return instance_count, instance_label_map-- # predict text center- xy_text = np.argwhere(tcl_map[:, :, 0] > tcl_map_thresh)- n = xy_text.shape[0]- xy_text = xy_text[:, ::-1] # (n, 2)- tco = tco_map[xy_text[:, 1], xy_text[:, 0], :] # (n, 2)- pred_tc = xy_text - tco-- # get gt text center- m = quads.shape[0]- gt_tc = np.mean(quads, axis=1) # (m, 2)-- pred_tc_tile = np.tile(pred_tc[:, np.newaxis, :], (1, m, 1)) # (n, m, 2)- gt_tc_tile = np.tile(gt_tc[np.newaxis, :, :], (n, 1, 1)) # (n, m, 2)- dist_mat = np.linalg.norm(pred_tc_tile - gt_tc_tile, axis=2) # (n, m)- xy_text_assign = np.argmin(dist_mat, axis=1) + 1 # (n,)-- instance_label_map[xy_text[:, 1], xy_text[:, 0]] = xy_text_assign- return instance_count, instance_label_map-- def estimate_sample_pts_num(self, quad, xy_text):- """- Estimate sample points number.- """- eh = (np.linalg.norm(quad[0] - quad[3]) + np.linalg.norm(quad[1] - quad[2])) / 2.0- ew = (np.linalg.norm(quad[0] - quad[1]) + np.linalg.norm(quad[2] - quad[3])) / 2.0-- dense_sample_pts_num = max(2, int(ew))- dense_xy_center_line = xy_text[np.linspace(0, xy_text.shape[0] - 1, dense_sample_pts_num,- endpoint=True, dtype=np.float32).astype(np.int32)]-- dense_xy_center_line_diff = dense_xy_center_line[1:] - dense_xy_center_line[:-1]- estimate_arc_len = np.sum(np.linalg.norm(dense_xy_center_line_diff, axis=1))-- sample_pts_num = max(2, int(estimate_arc_len / eh))- return sample_pts_num-- def detect_sast(self, tcl_map, tvo_map, tbo_map, tco_map, ratio_w, ratio_h, src_w, src_h,- shrink_ratio_of_width=0.3, tcl_map_thresh=0.5, offset_expand=1.0, out_strid=4.0):- """- first resize the tcl_map, tvo_map and tbo_map to the input_size, then restore the polys- """- # restore quad- scores, quads, xy_text = self.restore_quad(tcl_map, tcl_map_thresh, tvo_map)- dets = np.hstack((quads, scores)).astype(np.float32, copy=False)- dets = self.nms(dets)- if dets.shape[0] == 0:- return []- quads = dets[:, :-1].reshape(-1, 4, 2)-- # Compute quad area- quad_areas = []- for quad in quads:- quad_areas.append(-self.quad_area(quad))-- # instance segmentation- # instance_count, instance_label_map = cv2.connectedComponents(tcl_map.astype(np.uint8), connectivity=8)- instance_count, instance_label_map = self.cluster_by_quads_tco(tcl_map, tcl_map_thresh, quads, tco_map)-- # restore single poly with tcl instance.- poly_list = []- for instance_idx in range(1, instance_count):- xy_text = np.argwhere(instance_label_map == instance_idx)[:, ::-1]- quad = quads[instance_idx - 1]- q_area = quad_areas[instance_idx - 1]- if q_area < 5:- continue-- #- len1 = float(np.linalg.norm(quad[0] - quad[1]))- len2 = float(np.linalg.norm(quad[1] - quad[2]))- min_len = min(len1, len2)- if min_len < 3:- continue-- # filter small CC- if xy_text.shape[0] <= 0:- continue-- # filter low confidence instance- xy_text_scores = tcl_map[xy_text[:, 1], xy_text[:, 0], 0]- if np.sum(xy_text_scores) / quad_areas[instance_idx - 1] < 0.1:- # if np.sum(xy_text_scores) / quad_areas[instance_idx - 1] < 0.05:- continue-- # sort xy_text- left_center_pt = np.array([[(quad[0, 0] + quad[-1, 0]) / 2.0,- (quad[0, 1] + quad[-1, 1]) / 2.0]]) # (1, 2)- right_center_pt = np.array([[(quad[1, 0] + quad[2, 0]) / 2.0,- (quad[1, 1] + quad[2, 1]) / 2.0]]) # (1, 2)- proj_unit_vec = (right_center_pt - left_center_pt) / \- (np.linalg.norm(right_center_pt - left_center_pt) + 1e-6)- proj_value = np.sum(xy_text * proj_unit_vec, axis=1)- xy_text = xy_text[np.argsort(proj_value)]-- # Sample pts in tcl map- if self.sample_pts_num == 0:- sample_pts_num = self.estimate_sample_pts_num(quad, xy_text)- else:- sample_pts_num = self.sample_pts_num- xy_center_line = xy_text[np.linspace(0, xy_text.shape[0] - 1, sample_pts_num,- endpoint=True, dtype=np.float32).astype(np.int32)]-- point_pair_list = []- for x, y in xy_center_line:- # get corresponding offset- offset = tbo_map[y, x, :].reshape(2, 2)- if offset_expand != 1.0:- offset_length = np.linalg.norm(offset, axis=1, keepdims=True)- expand_length = np.clip(offset_length * (offset_expand - 1), a_min=0.5, a_max=3.0)- offset_detal = offset / offset_length * expand_length- offset = offset + offset_detal- # original point- ori_yx = np.array([y, x], dtype=np.float32)- point_pair = (ori_yx + offset)[:, ::-1] * out_strid / np.array([ratio_w, ratio_h]).reshape(-1, 2)- point_pair_list.append(point_pair)-- # ndarry: (x, 2), expand poly along width- detected_poly = self.point_pair2poly(point_pair_list)- detected_poly = self.expand_poly_along_width(detected_poly, shrink_ratio_of_width)- detected_poly[:, 0] = np.clip(detected_poly[:, 0], a_min=0, a_max=src_w)- detected_poly[:, 1] = np.clip(detected_poly[:, 1], a_min=0, a_max=src_h)- poly_list.append(detected_poly)-- return poly_list-- def __call__(self, outs_dict, shape_list):- score_list = outs_dict['f_score']- border_list = outs_dict['f_border']- tvo_list = outs_dict['f_tvo']- tco_list = outs_dict['f_tco']- if isinstance(score_list, torch.Tensor):- score_list = score_list.cpu().numpy()- border_list = border_list.cpu().numpy()- tvo_list = tvo_list.cpu().numpy()- tco_list = tco_list.cpu().numpy()-- img_num = len(shape_list)- poly_lists = []- for ino in range(img_num):- p_score = score_list[ino].transpose((1, 2, 0))- p_border = border_list[ino].transpose((1, 2, 0))- p_tvo = tvo_list[ino].transpose((1, 2, 0))- p_tco = tco_list[ino].transpose((1, 2, 0))- src_h, src_w, ratio_h, ratio_w = shape_list[ino]-- poly_list = self.detect_sast(p_score, p_tvo, p_border, p_tco, ratio_w, ratio_h, src_w, src_h,- shrink_ratio_of_width=self.shrink_ratio_of_width,- tcl_map_thresh=self.tcl_map_thresh, offset_expand=self.expand_scale)- poly_lists.append({'points': np.array(poly_list)})-- return poly_lists-diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/extract_batchsize.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/extract_batchsize.pydeleted file mode 100755index 6c6a8bf8..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/extract_batchsize.py+++ /dev/null@@ -1,88 +0,0 @@-raise ValueError('utils -> e2e_utils -> extract_batchsize')-import paddle-import numpy as np-import copy---def org_tcl_rois(batch_size, pos_lists, pos_masks, label_lists, tcl_bs):- """- """- pos_lists_, pos_masks_, label_lists_ = [], [], []- img_bs = batch_size- ngpu = int(batch_size / img_bs)- img_ids = np.array(pos_lists, dtype=np.int32)[:, 0, 0].copy()- pos_lists_split, pos_masks_split, label_lists_split = [], [], []- for i in range(ngpu):- pos_lists_split.append([])- pos_masks_split.append([])- label_lists_split.append([])-- for i in range(img_ids.shape[0]):- img_id = img_ids[i]- gpu_id = int(img_id / img_bs)- img_id = img_id % img_bs- pos_list = pos_lists[i].copy()- pos_list[:, 0] = img_id- pos_lists_split[gpu_id].append(pos_list)- pos_masks_split[gpu_id].append(pos_masks[i].copy())- label_lists_split[gpu_id].append(copy.deepcopy(label_lists[i]))- # repeat or delete- for i in range(ngpu):- vp_len = len(pos_lists_split[i])- if vp_len <= tcl_bs:- for j in range(0, tcl_bs - vp_len):- pos_list = pos_lists_split[i][j].copy()- pos_lists_split[i].append(pos_list)- pos_mask = pos_masks_split[i][j].copy()- pos_masks_split[i].append(pos_mask)- label_list = copy.deepcopy(label_lists_split[i][j])- label_lists_split[i].append(label_list)- else:- for j in range(0, vp_len - tcl_bs):- c_len = len(pos_lists_split[i])- pop_id = np.random.permutation(c_len)[0]- pos_lists_split[i].pop(pop_id)- pos_masks_split[i].pop(pop_id)- label_lists_split[i].pop(pop_id)- # merge- for i in range(ngpu):- pos_lists_.extend(pos_lists_split[i])- pos_masks_.extend(pos_masks_split[i])- label_lists_.extend(label_lists_split[i])- return pos_lists_, pos_masks_, label_lists_---def pre_process(label_list, pos_list, pos_mask, max_text_length, max_text_nums,- pad_num, tcl_bs):- label_list = label_list.numpy()- batch, _, _, _ = label_list.shape- pos_list = pos_list.numpy()- pos_mask = pos_mask.numpy()- pos_list_t = []- pos_mask_t = []- label_list_t = []- for i in range(batch):- for j in range(max_text_nums):- if pos_mask[i, j].any():- pos_list_t.append(pos_list[i][j])- pos_mask_t.append(pos_mask[i][j])- label_list_t.append(label_list[i][j])- pos_list, pos_mask, label_list = org_tcl_rois(batch, pos_list_t, pos_mask_t,- label_list_t, tcl_bs)- label = []- tt = [l.tolist() for l in label_list]- for i in range(tcl_bs):- k = 0- for j in range(max_text_length):- if tt[i][j][0] != pad_num:- k += 1- else:- break- label.append(k)- label = paddle.to_tensor(label)- label = paddle.cast(label, dtype='int64')- pos_list = paddle.to_tensor(pos_list)- pos_mask = paddle.to_tensor(pos_mask)- label_list = paddle.squeeze(paddle.to_tensor(label_list), axis=2)- label_list = paddle.cast(label_list, dtype='int32')- return pos_list, pos_mask, label_list, labeldiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/extract_textpoint_fast.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/extract_textpoint_fast.pydeleted file mode 100755index 787cd301..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/extract_textpoint_fast.py+++ /dev/null@@ -1,457 +0,0 @@-# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.-"""Contains various CTC decoders."""-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import cv2-import math--import numpy as np-from itertools import groupby-from skimage.morphology._skeletonize import thin---def get_dict(character_dict_path):- character_str = ""- with open(character_dict_path, "rb") as fin:- lines = fin.readlines()- for line in lines:- line = line.decode('utf-8').strip("\n").strip("\r\n")- character_str += line- dict_character = list(character_str)- return dict_character---def softmax(logits):- """- logits: N x d- """- max_value = np.max(logits, axis=1, keepdims=True)- exp = np.exp(logits - max_value)- exp_sum = np.sum(exp, axis=1, keepdims=True)- dist = exp / exp_sum- return dist---def get_keep_pos_idxs(labels, remove_blank=None):- """- Remove duplicate and get pos idxs of keep items.- The value of keep_blank should be [None, 95].- """- duplicate_len_list = []- keep_pos_idx_list = []- keep_char_idx_list = []- for k, v_ in groupby(labels):- current_len = len(list(v_))- if k != remove_blank:- current_idx = int(sum(duplicate_len_list) + current_len // 2)- keep_pos_idx_list.append(current_idx)- keep_char_idx_list.append(k)- duplicate_len_list.append(current_len)- return keep_char_idx_list, keep_pos_idx_list---def remove_blank(labels, blank=0):- new_labels = [x for x in labels if x != blank]- return new_labels---def insert_blank(labels, blank=0):- new_labels = [blank]- for l in labels:- new_labels += [l, blank]- return new_labels---def ctc_greedy_decoder(probs_seq, blank=95, keep_blank_in_idxs=True):- """- CTC greedy (best path) decoder.- """- raw_str = np.argmax(np.array(probs_seq), axis=1)- remove_blank_in_pos = None if keep_blank_in_idxs else blank- dedup_str, keep_idx_list = get_keep_pos_idxs(- raw_str, remove_blank=remove_blank_in_pos)- dst_str = remove_blank(dedup_str, blank=blank)- return dst_str, keep_idx_list---def instance_ctc_greedy_decoder(gather_info, logits_map, pts_num=4):- _, _, C = logits_map.shape- ys, xs = zip(*gather_info)- logits_seq = logits_map[list(ys), list(xs)]- probs_seq = logits_seq- labels = np.argmax(probs_seq, axis=1)- dst_str = [k for k, v_ in groupby(labels) if k != C - 1]- detal = len(gather_info) // (pts_num - 1)- keep_idx_list = [0] + [detal * (i + 1) for i in range(pts_num - 2)] + [-1]- keep_gather_list = [gather_info[idx] for idx in keep_idx_list]- return dst_str, keep_gather_list---def ctc_decoder_for_image(gather_info_list,- logits_map,- Lexicon_Table,- pts_num=6):- """- CTC decoder using multiple processes.- """- decoder_str = []- decoder_xys = []- for gather_info in gather_info_list:- if len(gather_info) < pts_num:- continue- dst_str, xys_list = instance_ctc_greedy_decoder(- gather_info, logits_map, pts_num=pts_num)- dst_str_readable = ''.join([Lexicon_Table[idx] for idx in dst_str])- if len(dst_str_readable) < 2:- continue- decoder_str.append(dst_str_readable)- decoder_xys.append(xys_list)- return decoder_str, decoder_xys---def sort_with_direction(pos_list, f_direction):- """- f_direction: h x w x 2- pos_list: [[y, x], [y, x], [y, x] ...]- """-- def sort_part_with_direction(pos_list, point_direction):- pos_list = np.array(pos_list).reshape(-1, 2)- point_direction = np.array(point_direction).reshape(-1, 2)- average_direction = np.mean(point_direction, axis=0, keepdims=True)- pos_proj_leng = np.sum(pos_list * average_direction, axis=1)- sorted_list = pos_list[np.argsort(pos_proj_leng)].tolist()- sorted_direction = point_direction[np.argsort(pos_proj_leng)].tolist()- return sorted_list, sorted_direction-- pos_list = np.array(pos_list).reshape(-1, 2)- point_direction = f_direction[pos_list[:, 0], pos_list[:, 1]] # x, y- point_direction = point_direction[:, ::-1] # x, y -> y, x- sorted_point, sorted_direction = sort_part_with_direction(pos_list,- point_direction)-- point_num = len(sorted_point)- if point_num >= 16:- middle_num = point_num // 2- first_part_point = sorted_point[:middle_num]- first_point_direction = sorted_direction[:middle_num]- sorted_fist_part_point, sorted_fist_part_direction = sort_part_with_direction(- first_part_point, first_point_direction)-- last_part_point = sorted_point[middle_num:]- last_point_direction = sorted_direction[middle_num:]- sorted_last_part_point, sorted_last_part_direction = sort_part_with_direction(- last_part_point, last_point_direction)- sorted_point = sorted_fist_part_point + sorted_last_part_point- sorted_direction = sorted_fist_part_direction + sorted_last_part_direction-- return sorted_point, np.array(sorted_direction)---def add_id(pos_list, image_id=0):- """- Add id for gather feature, for inference.- """- new_list = []- for item in pos_list:- new_list.append((image_id, item[0], item[1]))- return new_list---def sort_and_expand_with_direction(pos_list, f_direction):- """- f_direction: h x w x 2- pos_list: [[y, x], [y, x], [y, x] ...]- """- h, w, _ = f_direction.shape- sorted_list, point_direction = sort_with_direction(pos_list, f_direction)-- point_num = len(sorted_list)- sub_direction_len = max(point_num // 3, 2)- left_direction = point_direction[:sub_direction_len, :]- right_dirction = point_direction[point_num - sub_direction_len:, :]-- left_average_direction = -np.mean(left_direction, axis=0, keepdims=True)- left_average_len = np.linalg.norm(left_average_direction)- left_start = np.array(sorted_list[0])- left_step = left_average_direction / (left_average_len + 1e-6)-- right_average_direction = np.mean(right_dirction, axis=0, keepdims=True)- right_average_len = np.linalg.norm(right_average_direction)- right_step = right_average_direction / (right_average_len + 1e-6)- right_start = np.array(sorted_list[-1])-- append_num = max(- int((left_average_len + right_average_len) / 2.0 * 0.15), 1)- left_list = []- right_list = []- for i in range(append_num):- ly, lx = np.round(left_start + left_step * (i + 1)).flatten().astype(- 'int32').tolist()- if ly < h and lx < w and (ly, lx) not in left_list:- left_list.append((ly, lx))- ry, rx = np.round(right_start + right_step * (i + 1)).flatten().astype(- 'int32').tolist()- if ry < h and rx < w and (ry, rx) not in right_list:- right_list.append((ry, rx))-- all_list = left_list[::-1] + sorted_list + right_list- return all_list---def sort_and_expand_with_direction_v2(pos_list, f_direction, binary_tcl_map):- """- f_direction: h x w x 2- pos_list: [[y, x], [y, x], [y, x] ...]- binary_tcl_map: h x w- """- h, w, _ = f_direction.shape- sorted_list, point_direction = sort_with_direction(pos_list, f_direction)-- point_num = len(sorted_list)- sub_direction_len = max(point_num // 3, 2)- left_direction = point_direction[:sub_direction_len, :]- right_dirction = point_direction[point_num - sub_direction_len:, :]-- left_average_direction = -np.mean(left_direction, axis=0, keepdims=True)- left_average_len = np.linalg.norm(left_average_direction)- left_start = np.array(sorted_list[0])- left_step = left_average_direction / (left_average_len + 1e-6)-- right_average_direction = np.mean(right_dirction, axis=0, keepdims=True)- right_average_len = np.linalg.norm(right_average_direction)- right_step = right_average_direction / (right_average_len + 1e-6)- right_start = np.array(sorted_list[-1])-- append_num = max(- int((left_average_len + right_average_len) / 2.0 * 0.15), 1)- max_append_num = 2 * append_num-- left_list = []- right_list = []- for i in range(max_append_num):- ly, lx = np.round(left_start + left_step * (i + 1)).flatten().astype(- 'int32').tolist()- if ly < h and lx < w and (ly, lx) not in left_list:- if binary_tcl_map[ly, lx] > 0.5:- left_list.append((ly, lx))- else:- break-- for i in range(max_append_num):- ry, rx = np.round(right_start + right_step * (i + 1)).flatten().astype(- 'int32').tolist()- if ry < h and rx < w and (ry, rx) not in right_list:- if binary_tcl_map[ry, rx] > 0.5:- right_list.append((ry, rx))- else:- break-- all_list = left_list[::-1] + sorted_list + right_list- return all_list---def point_pair2poly(point_pair_list):- """- Transfer vertical point_pairs into poly point in clockwise.- """- point_num = len(point_pair_list) * 2- point_list = [0] * point_num- for idx, point_pair in enumerate(point_pair_list):- point_list[idx] = point_pair[0]- point_list[point_num - 1 - idx] = point_pair[1]- return np.array(point_list).reshape(-1, 2)---def shrink_quad_along_width(quad, begin_width_ratio=0., end_width_ratio=1.):- ratio_pair = np.array(- [[begin_width_ratio], [end_width_ratio]], dtype=np.float32)- p0_1 = quad[0] + (quad[1] - quad[0]) * ratio_pair- p3_2 = quad[3] + (quad[2] - quad[3]) * ratio_pair- return np.array([p0_1[0], p0_1[1], p3_2[1], p3_2[0]])---def expand_poly_along_width(poly, shrink_ratio_of_width=0.3):- """- expand poly along width.- """- point_num = poly.shape[0]- left_quad = np.array(- [poly[0], poly[1], poly[-2], poly[-1]], dtype=np.float32)- left_ratio = -shrink_ratio_of_width * np.linalg.norm(left_quad[0] - left_quad[3]) / \- (np.linalg.norm(left_quad[0] - left_quad[1]) + 1e-6)- left_quad_expand = shrink_quad_along_width(left_quad, left_ratio, 1.0)- right_quad = np.array(- [- poly[point_num // 2 - 2], poly[point_num // 2 - 1],- poly[point_num // 2], poly[point_num // 2 + 1]- ],- dtype=np.float32)- right_ratio = 1.0 + shrink_ratio_of_width * np.linalg.norm(right_quad[0] - right_quad[3]) / \- (np.linalg.norm(right_quad[0] - right_quad[1]) + 1e-6)- right_quad_expand = shrink_quad_along_width(right_quad, 0.0, right_ratio)- poly[0] = left_quad_expand[0]- poly[-1] = left_quad_expand[-1]- poly[point_num // 2 - 1] = right_quad_expand[1]- poly[point_num // 2] = right_quad_expand[2]- return poly---def restore_poly(instance_yxs_list, seq_strs, p_border, ratio_w, ratio_h, src_w,- src_h, valid_set):- poly_list = []- keep_str_list = []- for yx_center_line, keep_str in zip(instance_yxs_list, seq_strs):- if len(keep_str) < 2:- print('--> too short, {}'.format(keep_str))- continue-- offset_expand = 1.0- if valid_set == 'totaltext':- offset_expand = 1.2-- point_pair_list = []- for y, x in yx_center_line:- offset = p_border[:, y, x].reshape(2, 2) * offset_expand- ori_yx = np.array([y, x], dtype=np.float32)- point_pair = (ori_yx + offset)[:, ::-1] * 4.0 / np.array(- [ratio_w, ratio_h]).reshape(-1, 2)- point_pair_list.append(point_pair)-- detected_poly = point_pair2poly(point_pair_list)- detected_poly = expand_poly_along_width(- detected_poly, shrink_ratio_of_width=0.2)- detected_poly[:, 0] = np.clip(detected_poly[:, 0], a_min=0, a_max=src_w)- detected_poly[:, 1] = np.clip(detected_poly[:, 1], a_min=0, a_max=src_h)-- keep_str_list.append(keep_str)- if valid_set == 'partvgg':- middle_point = len(detected_poly) // 2- detected_poly = detected_poly[- [0, middle_point - 1, middle_point, -1], :]- poly_list.append(detected_poly)- elif valid_set == 'totaltext':- poly_list.append(detected_poly)- else:- print('--> Not supported format.')- exit(-1)- return poly_list, keep_str_list---def generate_pivot_list_fast(p_score,- p_char_maps,- f_direction,- Lexicon_Table,- score_thresh=0.5):- """- return center point and end point of TCL instance; filter with the char maps;- """- p_score = p_score[0]- f_direction = f_direction.transpose(1, 2, 0)- p_tcl_map = (p_score > score_thresh) * 1.0- skeleton_map = thin(p_tcl_map.astype(np.uint8))- instance_count, instance_label_map = cv2.connectedComponents(- skeleton_map.astype(np.uint8), connectivity=8)-- # get TCL Instance- all_pos_yxs = []- if instance_count > 0:- for instance_id in range(1, instance_count):- pos_list = []- ys, xs = np.where(instance_label_map == instance_id)- pos_list = list(zip(ys, xs))-- if len(pos_list) < 3:- continue-- pos_list_sorted = sort_and_expand_with_direction_v2(- pos_list, f_direction, p_tcl_map)- all_pos_yxs.append(pos_list_sorted)-- p_char_maps = p_char_maps.transpose([1, 2, 0])- decoded_str, keep_yxs_list = ctc_decoder_for_image(- all_pos_yxs, logits_map=p_char_maps, Lexicon_Table=Lexicon_Table)- return keep_yxs_list, decoded_str---def extract_main_direction(pos_list, f_direction):- """- f_direction: h x w x 2- pos_list: [[y, x], [y, x], [y, x] ...]- """- pos_list = np.array(pos_list)- point_direction = f_direction[pos_list[:, 0], pos_list[:, 1]]- point_direction = point_direction[:, ::-1] # x, y -> y, x- average_direction = np.mean(point_direction, axis=0, keepdims=True)- average_direction = average_direction / (- np.linalg.norm(average_direction) + 1e-6)- return average_direction---def sort_by_direction_with_image_id_deprecated(pos_list, f_direction):- """- f_direction: h x w x 2- pos_list: [[id, y, x], [id, y, x], [id, y, x] ...]- """- pos_list_full = np.array(pos_list).reshape(-1, 3)- pos_list = pos_list_full[:, 1:]- point_direction = f_direction[pos_list[:, 0], pos_list[:, 1]] # x, y- point_direction = point_direction[:, ::-1] # x, y -> y, x- average_direction = np.mean(point_direction, axis=0, keepdims=True)- pos_proj_leng = np.sum(pos_list * average_direction, axis=1)- sorted_list = pos_list_full[np.argsort(pos_proj_leng)].tolist()- return sorted_list---def sort_by_direction_with_image_id(pos_list, f_direction):- """- f_direction: h x w x 2- pos_list: [[y, x], [y, x], [y, x] ...]- """-- def sort_part_with_direction(pos_list_full, point_direction):- pos_list_full = np.array(pos_list_full).reshape(-1, 3)- pos_list = pos_list_full[:, 1:]- point_direction = np.array(point_direction).reshape(-1, 2)- average_direction = np.mean(point_direction, axis=0, keepdims=True)- pos_proj_leng = np.sum(pos_list * average_direction, axis=1)- sorted_list = pos_list_full[np.argsort(pos_proj_leng)].tolist()- sorted_direction = point_direction[np.argsort(pos_proj_leng)].tolist()- return sorted_list, sorted_direction-- pos_list = np.array(pos_list).reshape(-1, 3)- point_direction = f_direction[pos_list[:, 1], pos_list[:, 2]] # x, y- point_direction = point_direction[:, ::-1] # x, y -> y, x- sorted_point, sorted_direction = sort_part_with_direction(pos_list,- point_direction)-- point_num = len(sorted_point)- if point_num >= 16:- middle_num = point_num // 2- first_part_point = sorted_point[:middle_num]- first_point_direction = sorted_direction[:middle_num]- sorted_fist_part_point, sorted_fist_part_direction = sort_part_with_direction(- first_part_point, first_point_direction)-- last_part_point = sorted_point[middle_num:]- last_point_direction = sorted_direction[middle_num:]- sorted_last_part_point, sorted_last_part_direction = sort_part_with_direction(- last_part_point, last_point_direction)- sorted_point = sorted_fist_part_point + sorted_last_part_point- sorted_direction = sorted_fist_part_direction + sorted_last_part_direction-- return sorted_pointdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/extract_textpoint_slow.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/extract_textpoint_slow.pydeleted file mode 100755index ace46fba..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/extract_textpoint_slow.py+++ /dev/null@@ -1,592 +0,0 @@-# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.-"""Contains various CTC decoders."""-from __future__ import absolute_import-from __future__ import division-from __future__ import print_function--import cv2-import math--import numpy as np-from itertools import groupby-from skimage.morphology._skeletonize import thin---def get_dict(character_dict_path):- character_str = ""- with open(character_dict_path, "rb") as fin:- lines = fin.readlines()- for line in lines:- line = line.decode('utf-8').strip("\n").strip("\r\n")- character_str += line- dict_character = list(character_str)- return dict_character---def point_pair2poly(point_pair_list):- """- Transfer vertical point_pairs into poly point in clockwise.- """- pair_length_list = []- for point_pair in point_pair_list:- pair_length = np.linalg.norm(point_pair[0] - point_pair[1])- pair_length_list.append(pair_length)- pair_length_list = np.array(pair_length_list)- pair_info = (pair_length_list.max(), pair_length_list.min(),- pair_length_list.mean())-- point_num = len(point_pair_list) * 2- point_list = [0] * point_num- for idx, point_pair in enumerate(point_pair_list):- point_list[idx] = point_pair[0]- point_list[point_num - 1 - idx] = point_pair[1]- return np.array(point_list).reshape(-1, 2), pair_info---def shrink_quad_along_width(quad, begin_width_ratio=0., end_width_ratio=1.):- """- Generate shrink_quad_along_width.- """- ratio_pair = np.array(- [[begin_width_ratio], [end_width_ratio]], dtype=np.float32)- p0_1 = quad[0] + (quad[1] - quad[0]) * ratio_pair- p3_2 = quad[3] + (quad[2] - quad[3]) * ratio_pair- return np.array([p0_1[0], p0_1[1], p3_2[1], p3_2[0]])---def expand_poly_along_width(poly, shrink_ratio_of_width=0.3):- """- expand poly along width.- """- point_num = poly.shape[0]- left_quad = np.array(- [poly[0], poly[1], poly[-2], poly[-1]], dtype=np.float32)- left_ratio = -shrink_ratio_of_width * np.linalg.norm(left_quad[0] - left_quad[3]) / \- (np.linalg.norm(left_quad[0] - left_quad[1]) + 1e-6)- left_quad_expand = shrink_quad_along_width(left_quad, left_ratio, 1.0)- right_quad = np.array(- [- poly[point_num // 2 - 2], poly[point_num // 2 - 1],- poly[point_num // 2], poly[point_num // 2 + 1]- ],- dtype=np.float32)- right_ratio = 1.0 + \- shrink_ratio_of_width * np.linalg.norm(right_quad[0] - right_quad[3]) / \- (np.linalg.norm(right_quad[0] - right_quad[1]) + 1e-6)- right_quad_expand = shrink_quad_along_width(right_quad, 0.0, right_ratio)- poly[0] = left_quad_expand[0]- poly[-1] = left_quad_expand[-1]- poly[point_num // 2 - 1] = right_quad_expand[1]- poly[point_num // 2] = right_quad_expand[2]- return poly---def softmax(logits):- """- logits: N x d- """- max_value = np.max(logits, axis=1, keepdims=True)- exp = np.exp(logits - max_value)- exp_sum = np.sum(exp, axis=1, keepdims=True)- dist = exp / exp_sum- return dist---def get_keep_pos_idxs(labels, remove_blank=None):- """- Remove duplicate and get pos idxs of keep items.- The value of keep_blank should be [None, 95].- """- duplicate_len_list = []- keep_pos_idx_list = []- keep_char_idx_list = []- for k, v_ in groupby(labels):- current_len = len(list(v_))- if k != remove_blank:- current_idx = int(sum(duplicate_len_list) + current_len // 2)- keep_pos_idx_list.append(current_idx)- keep_char_idx_list.append(k)- duplicate_len_list.append(current_len)- return keep_char_idx_list, keep_pos_idx_list---def remove_blank(labels, blank=0):- new_labels = [x for x in labels if x != blank]- return new_labels---def insert_blank(labels, blank=0):- new_labels = [blank]- for l in labels:- new_labels += [l, blank]- return new_labels---def ctc_greedy_decoder(probs_seq, blank=95, keep_blank_in_idxs=True):- """- CTC greedy (best path) decoder.- """- raw_str = np.argmax(np.array(probs_seq), axis=1)- remove_blank_in_pos = None if keep_blank_in_idxs else blank- dedup_str, keep_idx_list = get_keep_pos_idxs(- raw_str, remove_blank=remove_blank_in_pos)- dst_str = remove_blank(dedup_str, blank=blank)- return dst_str, keep_idx_list---def instance_ctc_greedy_decoder(gather_info,- logits_map,- keep_blank_in_idxs=True):- """- gather_info: [[x, y], [x, y] ...]- logits_map: H x W X (n_chars + 1)- """- _, _, C = logits_map.shape- ys, xs = zip(*gather_info)- logits_seq = logits_map[list(ys), list(xs)] # n x 96- probs_seq = softmax(logits_seq)- dst_str, keep_idx_list = ctc_greedy_decoder(- probs_seq, blank=C - 1, keep_blank_in_idxs=keep_blank_in_idxs)- keep_gather_list = [gather_info[idx] for idx in keep_idx_list]- return dst_str, keep_gather_list---def ctc_decoder_for_image(gather_info_list, logits_map,- keep_blank_in_idxs=True):- """- CTC decoder using multiple processes.- """- decoder_results = []- for gather_info in gather_info_list:- res = instance_ctc_greedy_decoder(- gather_info, logits_map, keep_blank_in_idxs=keep_blank_in_idxs)- decoder_results.append(res)- return decoder_results---def sort_with_direction(pos_list, f_direction):- """- f_direction: h x w x 2- pos_list: [[y, x], [y, x], [y, x] ...]- """-- def sort_part_with_direction(pos_list, point_direction):- pos_list = np.array(pos_list).reshape(-1, 2)- point_direction = np.array(point_direction).reshape(-1, 2)- average_direction = np.mean(point_direction, axis=0, keepdims=True)- pos_proj_leng = np.sum(pos_list * average_direction, axis=1)- sorted_list = pos_list[np.argsort(pos_proj_leng)].tolist()- sorted_direction = point_direction[np.argsort(pos_proj_leng)].tolist()- return sorted_list, sorted_direction-- pos_list = np.array(pos_list).reshape(-1, 2)- point_direction = f_direction[pos_list[:, 0], pos_list[:, 1]] # x, y- point_direction = point_direction[:, ::-1] # x, y -> y, x- sorted_point, sorted_direction = sort_part_with_direction(pos_list,- point_direction)-- point_num = len(sorted_point)- if point_num >= 16:- middle_num = point_num // 2- first_part_point = sorted_point[:middle_num]- first_point_direction = sorted_direction[:middle_num]- sorted_fist_part_point, sorted_fist_part_direction = sort_part_with_direction(- first_part_point, first_point_direction)-- last_part_point = sorted_point[middle_num:]- last_point_direction = sorted_direction[middle_num:]- sorted_last_part_point, sorted_last_part_direction = sort_part_with_direction(- last_part_point, last_point_direction)- sorted_point = sorted_fist_part_point + sorted_last_part_point- sorted_direction = sorted_fist_part_direction + sorted_last_part_direction-- return sorted_point, np.array(sorted_direction)---def add_id(pos_list, image_id=0):- """- Add id for gather feature, for inference.- """- new_list = []- for item in pos_list:- new_list.append((image_id, item[0], item[1]))- return new_list---def sort_and_expand_with_direction(pos_list, f_direction):- """- f_direction: h x w x 2- pos_list: [[y, x], [y, x], [y, x] ...]- """- h, w, _ = f_direction.shape- sorted_list, point_direction = sort_with_direction(pos_list, f_direction)-- # expand along- point_num = len(sorted_list)- sub_direction_len = max(point_num // 3, 2)- left_direction = point_direction[:sub_direction_len, :]- right_dirction = point_direction[point_num - sub_direction_len:, :]-- left_average_direction = -np.mean(left_direction, axis=0, keepdims=True)- left_average_len = np.linalg.norm(left_average_direction)- left_start = np.array(sorted_list[0])- left_step = left_average_direction / (left_average_len + 1e-6)-- right_average_direction = np.mean(right_dirction, axis=0, keepdims=True)- right_average_len = np.linalg.norm(right_average_direction)- right_step = right_average_direction / (right_average_len + 1e-6)- right_start = np.array(sorted_list[-1])-- append_num = max(- int((left_average_len + right_average_len) / 2.0 * 0.15), 1)- left_list = []- right_list = []- for i in range(append_num):- ly, lx = np.round(left_start + left_step * (i + 1)).flatten().astype(- 'int32').tolist()- if ly < h and lx < w and (ly, lx) not in left_list:- left_list.append((ly, lx))- ry, rx = np.round(right_start + right_step * (i + 1)).flatten().astype(- 'int32').tolist()- if ry < h and rx < w and (ry, rx) not in right_list:- right_list.append((ry, rx))-- all_list = left_list[::-1] + sorted_list + right_list- return all_list---def sort_and_expand_with_direction_v2(pos_list, f_direction, binary_tcl_map):- """- f_direction: h x w x 2- pos_list: [[y, x], [y, x], [y, x] ...]- binary_tcl_map: h x w- """- h, w, _ = f_direction.shape- sorted_list, point_direction = sort_with_direction(pos_list, f_direction)-- # expand along- point_num = len(sorted_list)- sub_direction_len = max(point_num // 3, 2)- left_direction = point_direction[:sub_direction_len, :]- right_dirction = point_direction[point_num - sub_direction_len:, :]-- left_average_direction = -np.mean(left_direction, axis=0, keepdims=True)- left_average_len = np.linalg.norm(left_average_direction)- left_start = np.array(sorted_list[0])- left_step = left_average_direction / (left_average_len + 1e-6)-- right_average_direction = np.mean(right_dirction, axis=0, keepdims=True)- right_average_len = np.linalg.norm(right_average_direction)- right_step = right_average_direction / (right_average_len + 1e-6)- right_start = np.array(sorted_list[-1])-- append_num = max(- int((left_average_len + right_average_len) / 2.0 * 0.15), 1)- max_append_num = 2 * append_num-- left_list = []- right_list = []- for i in range(max_append_num):- ly, lx = np.round(left_start + left_step * (i + 1)).flatten().astype(- 'int32').tolist()- if ly < h and lx < w and (ly, lx) not in left_list:- if binary_tcl_map[ly, lx] > 0.5:- left_list.append((ly, lx))- else:- break-- for i in range(max_append_num):- ry, rx = np.round(right_start + right_step * (i + 1)).flatten().astype(- 'int32').tolist()- if ry < h and rx < w and (ry, rx) not in right_list:- if binary_tcl_map[ry, rx] > 0.5:- right_list.append((ry, rx))- else:- break-- all_list = left_list[::-1] + sorted_list + right_list- return all_list---def generate_pivot_list_curved(p_score,- p_char_maps,- f_direction,- score_thresh=0.5,- is_expand=True,- is_backbone=False,- image_id=0):- """- return center point and end point of TCL instance; filter with the char maps;- """- p_score = p_score[0]- f_direction = f_direction.transpose(1, 2, 0)- p_tcl_map = (p_score > score_thresh) * 1.0- skeleton_map = thin(p_tcl_map)- instance_count, instance_label_map = cv2.connectedComponents(- skeleton_map.astype(np.uint8), connectivity=8)-- # get TCL Instance- all_pos_yxs = []- center_pos_yxs = []- end_points_yxs = []- instance_center_pos_yxs = []- pred_strs = []- if instance_count > 0:- for instance_id in range(1, instance_count):- pos_list = []- ys, xs = np.where(instance_label_map == instance_id)- pos_list = list(zip(ys, xs))-- ### FIX-ME, eliminate outlier- if len(pos_list) < 3:- continue-- if is_expand:- pos_list_sorted = sort_and_expand_with_direction_v2(- pos_list, f_direction, p_tcl_map)- else:- pos_list_sorted, _ = sort_with_direction(pos_list, f_direction)- all_pos_yxs.append(pos_list_sorted)-- # use decoder to filter backgroud points.- p_char_maps = p_char_maps.transpose([1, 2, 0])- decode_res = ctc_decoder_for_image(- all_pos_yxs, logits_map=p_char_maps, keep_blank_in_idxs=True)- for decoded_str, keep_yxs_list in decode_res:- if is_backbone:- keep_yxs_list_with_id = add_id(keep_yxs_list, image_id=image_id)- instance_center_pos_yxs.append(keep_yxs_list_with_id)- pred_strs.append(decoded_str)- else:- end_points_yxs.extend((keep_yxs_list[0], keep_yxs_list[-1]))- center_pos_yxs.extend(keep_yxs_list)-- if is_backbone:- return pred_strs, instance_center_pos_yxs- else:- return center_pos_yxs, end_points_yxs---def generate_pivot_list_horizontal(p_score,- p_char_maps,- f_direction,- score_thresh=0.5,- is_backbone=False,- image_id=0):- """- return center point and end point of TCL instance; filter with the char maps;- """- p_score = p_score[0]- f_direction = f_direction.transpose(1, 2, 0)- p_tcl_map_bi = (p_score > score_thresh) * 1.0- instance_count, instance_label_map = cv2.connectedComponents(- p_tcl_map_bi.astype(np.uint8), connectivity=8)-- # get TCL Instance- all_pos_yxs = []- center_pos_yxs = []- end_points_yxs = []- instance_center_pos_yxs = []-- if instance_count > 0:- for instance_id in range(1, instance_count):- pos_list = []- ys, xs = np.where(instance_label_map == instance_id)- pos_list = list(zip(ys, xs))-- ### FIX-ME, eliminate outlier- if len(pos_list) < 5:- continue-- # add rule here- main_direction = extract_main_direction(pos_list,- f_direction) # y x- reference_directin = np.array([0, 1]).reshape([-1, 2]) # y x- is_h_angle = abs(np.sum(- main_direction * reference_directin)) < math.cos(math.pi / 180 *- 70)-- point_yxs = np.array(pos_list)- max_y, max_x = np.max(point_yxs, axis=0)- min_y, min_x = np.min(point_yxs, axis=0)- is_h_len = (max_y - min_y) < 1.5 * (max_x - min_x)-- pos_list_final = []- if is_h_len:- xs = np.unique(xs)- for x in xs:- ys = instance_label_map[:, x].copy().reshape((-1, ))- y = int(np.where(ys == instance_id)[0].mean())- pos_list_final.append((y, x))- else:- ys = np.unique(ys)- for y in ys:- xs = instance_label_map[y, :].copy().reshape((-1, ))- x = int(np.where(xs == instance_id)[0].mean())- pos_list_final.append((y, x))-- pos_list_sorted, _ = sort_with_direction(pos_list_final,- f_direction)- all_pos_yxs.append(pos_list_sorted)-- # use decoder to filter backgroud points.- p_char_maps = p_char_maps.transpose([1, 2, 0])- decode_res = ctc_decoder_for_image(- all_pos_yxs, logits_map=p_char_maps, keep_blank_in_idxs=True)- for decoded_str, keep_yxs_list in decode_res:- if is_backbone:- keep_yxs_list_with_id = add_id(keep_yxs_list, image_id=image_id)- instance_center_pos_yxs.append(keep_yxs_list_with_id)- else:- end_points_yxs.extend((keep_yxs_list[0], keep_yxs_list[-1]))- center_pos_yxs.extend(keep_yxs_list)-- if is_backbone:- return instance_center_pos_yxs- else:- return center_pos_yxs, end_points_yxs---def generate_pivot_list_slow(p_score,- p_char_maps,- f_direction,- score_thresh=0.5,- is_backbone=False,- is_curved=True,- image_id=0):- """- Warp all the function together.- """- if is_curved:- return generate_pivot_list_curved(- p_score,- p_char_maps,- f_direction,- score_thresh=score_thresh,- is_expand=True,- is_backbone=is_backbone,- image_id=image_id)- else:- return generate_pivot_list_horizontal(- p_score,- p_char_maps,- f_direction,- score_thresh=score_thresh,- is_backbone=is_backbone,- image_id=image_id)---# for refine module-def extract_main_direction(pos_list, f_direction):- """- f_direction: h x w x 2- pos_list: [[y, x], [y, x], [y, x] ...]- """- pos_list = np.array(pos_list)- point_direction = f_direction[pos_list[:, 0], pos_list[:, 1]]- point_direction = point_direction[:, ::-1] # x, y -> y, x- average_direction = np.mean(point_direction, axis=0, keepdims=True)- average_direction = average_direction / (- np.linalg.norm(average_direction) + 1e-6)- return average_direction---def sort_by_direction_with_image_id_deprecated(pos_list, f_direction):- """- f_direction: h x w x 2- pos_list: [[id, y, x], [id, y, x], [id, y, x] ...]- """- pos_list_full = np.array(pos_list).reshape(-1, 3)- pos_list = pos_list_full[:, 1:]- point_direction = f_direction[pos_list[:, 0], pos_list[:, 1]] # x, y- point_direction = point_direction[:, ::-1] # x, y -> y, x- average_direction = np.mean(point_direction, axis=0, keepdims=True)- pos_proj_leng = np.sum(pos_list * average_direction, axis=1)- sorted_list = pos_list_full[np.argsort(pos_proj_leng)].tolist()- return sorted_list---def sort_by_direction_with_image_id(pos_list, f_direction):- """- f_direction: h x w x 2- pos_list: [[y, x], [y, x], [y, x] ...]- """-- def sort_part_with_direction(pos_list_full, point_direction):- pos_list_full = np.array(pos_list_full).reshape(-1, 3)- pos_list = pos_list_full[:, 1:]- point_direction = np.array(point_direction).reshape(-1, 2)- average_direction = np.mean(point_direction, axis=0, keepdims=True)- pos_proj_leng = np.sum(pos_list * average_direction, axis=1)- sorted_list = pos_list_full[np.argsort(pos_proj_leng)].tolist()- sorted_direction = point_direction[np.argsort(pos_proj_leng)].tolist()- return sorted_list, sorted_direction-- pos_list = np.array(pos_list).reshape(-1, 3)- point_direction = f_direction[pos_list[:, 1], pos_list[:, 2]] # x, y- point_direction = point_direction[:, ::-1] # x, y -> y, x- sorted_point, sorted_direction = sort_part_with_direction(pos_list,- point_direction)-- point_num = len(sorted_point)- if point_num >= 16:- middle_num = point_num // 2- first_part_point = sorted_point[:middle_num]- first_point_direction = sorted_direction[:middle_num]- sorted_fist_part_point, sorted_fist_part_direction = sort_part_with_direction(- first_part_point, first_point_direction)-- last_part_point = sorted_point[middle_num:]- last_point_direction = sorted_direction[middle_num:]- sorted_last_part_point, sorted_last_part_direction = sort_part_with_direction(- last_part_point, last_point_direction)- sorted_point = sorted_fist_part_point + sorted_last_part_point- sorted_direction = sorted_fist_part_direction + sorted_last_part_direction-- return sorted_point---def generate_pivot_list_tt_inference(p_score,- p_char_maps,- f_direction,- score_thresh=0.5,- is_backbone=False,- is_curved=True,- image_id=0):- """- return center point and end point of TCL instance; filter with the char maps;- """- p_score = p_score[0]- f_direction = f_direction.transpose(1, 2, 0)- p_tcl_map = (p_score > score_thresh) * 1.0- skeleton_map = thin(p_tcl_map)- instance_count, instance_label_map = cv2.connectedComponents(- skeleton_map.astype(np.uint8), connectivity=8)-- # get TCL Instance- all_pos_yxs = []- if instance_count > 0:- for instance_id in range(1, instance_count):- pos_list = []- ys, xs = np.where(instance_label_map == instance_id)- pos_list = list(zip(ys, xs))- ### FIX-ME, eliminate outlier- if len(pos_list) < 3:- continue- pos_list_sorted = sort_and_expand_with_direction_v2(- pos_list, f_direction, p_tcl_map)- pos_list_sorted_with_id = add_id(pos_list_sorted, image_id=image_id)- all_pos_yxs.append(pos_list_sorted_with_id)- return all_pos_yxsdiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/pgnet_pp_utils.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/pgnet_pp_utils.pydeleted file mode 100755index ce35a28d..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/pgnet_pp_utils.py+++ /dev/null@@ -1,150 +0,0 @@---from __future__ import absolute_import-from __future__ import division-from __future__ import print_function-import torch-import os-import sys--__dir__ = os.path.dirname(__file__)-sys.path.append(__dir__)-sys.path.append(os.path.join(__dir__, '..'))-from .extract_textpoint_slow import *-from .extract_textpoint_fast import generate_pivot_list_fast, restore_poly---class PGNet_PostProcess(object):- # two different post-process- def __init__(self, character_dict_path, valid_set, score_thresh, outs_dict,- shape_list):- self.Lexicon_Table = get_dict(character_dict_path)- self.valid_set = valid_set- self.score_thresh = score_thresh- self.outs_dict = outs_dict- self.shape_list = shape_list-- def pg_postprocess_fast(self):- p_score = self.outs_dict['f_score']- p_border = self.outs_dict['f_border']- p_char = self.outs_dict['f_char']- p_direction = self.outs_dict['f_direction']- if isinstance(p_score, torch.Tensor):- p_score = p_score[0].numpy()- p_border = p_border[0].numpy()- p_direction = p_direction[0].numpy()- p_char = p_char[0].numpy()- else:- p_score = p_score[0]- p_border = p_border[0]- p_direction = p_direction[0]- p_char = p_char[0]-- src_h, src_w, ratio_h, ratio_w = self.shape_list[0]- instance_yxs_list, seq_strs = generate_pivot_list_fast(- p_score,- p_char,- p_direction,- self.Lexicon_Table,- score_thresh=self.score_thresh)- poly_list, keep_str_list = restore_poly(instance_yxs_list, seq_strs,- p_border, ratio_w, ratio_h,- src_w, src_h, self.valid_set)- data = {- 'points': poly_list,- 'texts': keep_str_list,- }- return data-- def pg_postprocess_slow(self):- p_score = self.outs_dict['f_score']- p_border = self.outs_dict['f_border']- p_char = self.outs_dict['f_char']- p_direction = self.outs_dict['f_direction']- if isinstance(p_score, torch.Tensor):- p_score = p_score[0].numpy()- p_border = p_border[0].numpy()- p_direction = p_direction[0].numpy()- p_char = p_char[0].numpy()- else:- p_score = p_score[0]- p_border = p_border[0]- p_direction = p_direction[0]- p_char = p_char[0]- src_h, src_w, ratio_h, ratio_w = self.shape_list[0]- is_curved = self.valid_set == "totaltext"- char_seq_idx_set, instance_yxs_list = generate_pivot_list_slow(- p_score,- p_char,- p_direction,- score_thresh=self.score_thresh,- is_backbone=True,- is_curved=is_curved)- seq_strs = []- for char_idx_set in char_seq_idx_set:- pr_str = ''.join([self.Lexicon_Table[pos] for pos in char_idx_set])- seq_strs.append(pr_str)- poly_list = []- keep_str_list = []- all_point_list = []- all_point_pair_list = []- for yx_center_line, keep_str in zip(instance_yxs_list, seq_strs):- if len(yx_center_line) == 1:- yx_center_line.append(yx_center_line[-1])-- offset_expand = 1.0- if self.valid_set == 'totaltext':- offset_expand = 1.2-- point_pair_list = []- for batch_id, y, x in yx_center_line:- offset = p_border[:, y, x].reshape(2, 2)- if offset_expand != 1.0:- offset_length = np.linalg.norm(- offset, axis=1, keepdims=True)- expand_length = np.clip(- offset_length * (offset_expand - 1),- a_min=0.5,- a_max=3.0)- offset_detal = offset / offset_length * expand_length- offset = offset + offset_detal- ori_yx = np.array([y, x], dtype=np.float32)- point_pair = (ori_yx + offset)[:, ::-1] * 4.0 / np.array(- [ratio_w, ratio_h]).reshape(-1, 2)- point_pair_list.append(point_pair)-- all_point_list.append([- int(round(x * 4.0 / ratio_w)),- int(round(y * 4.0 / ratio_h))- ])- all_point_pair_list.append(point_pair.round().astype(np.int32)- .tolist())-- detected_poly, pair_length_info = point_pair2poly(point_pair_list)- detected_poly = expand_poly_along_width(- detected_poly, shrink_ratio_of_width=0.2)- detected_poly[:, 0] = np.clip(- detected_poly[:, 0], a_min=0, a_max=src_w)- detected_poly[:, 1] = np.clip(- detected_poly[:, 1], a_min=0, a_max=src_h)-- if len(keep_str) < 2:- continue-- keep_str_list.append(keep_str)- detected_poly = np.round(detected_poly).astype('int32')- if self.valid_set == 'partvgg':- middle_point = len(detected_poly) // 2- detected_poly = detected_poly[- [0, middle_point - 1, middle_point, -1], :]- poly_list.append(detected_poly)- elif self.valid_set == 'totaltext':- poly_list.append(detected_poly)- else:- print('--> Not supported format.')- exit(-1)- data = {- 'points': poly_list,- 'texts': keep_str_list,- }- return datadiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/visual.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/visual.pydeleted file mode 100755index e6e4fd06..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/e2e_utils/visual.py+++ /dev/null@@ -1,162 +0,0 @@-# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.-import numpy as np-import cv2-import time---def resize_image(im, max_side_len=512):- """- resize image to a size multiple of max_stride which is required by the network- :param im: the resized image- :param max_side_len: limit of max image size to avoid out of memory in gpu- :return: the resized image and the resize ratio- """- h, w, _ = im.shape-- resize_w = w- resize_h = h-- if resize_h > resize_w:- ratio = float(max_side_len) / resize_h- else:- ratio = float(max_side_len) / resize_w-- resize_h = int(resize_h * ratio)- resize_w = int(resize_w * ratio)-- max_stride = 128- resize_h = (resize_h + max_stride - 1) // max_stride * max_stride- resize_w = (resize_w + max_stride - 1) // max_stride * max_stride- im = cv2.resize(im, (int(resize_w), int(resize_h)))- ratio_h = resize_h / float(h)- ratio_w = resize_w / float(w)-- return im, (ratio_h, ratio_w)---def resize_image_min(im, max_side_len=512):- """- """- h, w, _ = im.shape-- resize_w = w- resize_h = h-- if resize_h < resize_w:- ratio = float(max_side_len) / resize_h- else:- ratio = float(max_side_len) / resize_w-- resize_h = int(resize_h * ratio)- resize_w = int(resize_w * ratio)-- max_stride = 128- resize_h = (resize_h + max_stride - 1) // max_stride * max_stride- resize_w = (resize_w + max_stride - 1) // max_stride * max_stride- im = cv2.resize(im, (int(resize_w), int(resize_h)))- ratio_h = resize_h / float(h)- ratio_w = resize_w / float(w)- return im, (ratio_h, ratio_w)---def resize_image_for_totaltext(im, max_side_len=512):- """- """- h, w, _ = im.shape-- resize_w = w- resize_h = h- ratio = 1.25- if h * ratio > max_side_len:- ratio = float(max_side_len) / resize_h-- resize_h = int(resize_h * ratio)- resize_w = int(resize_w * ratio)-- max_stride = 128- resize_h = (resize_h + max_stride - 1) // max_stride * max_stride- resize_w = (resize_w + max_stride - 1) // max_stride * max_stride- im = cv2.resize(im, (int(resize_w), int(resize_h)))- ratio_h = resize_h / float(h)- ratio_w = resize_w / float(w)- return im, (ratio_h, ratio_w)---def point_pair2poly(point_pair_list):- """- Transfer vertical point_pairs into poly point in clockwise.- """- pair_length_list = []- for point_pair in point_pair_list:- pair_length = np.linalg.norm(point_pair[0] - point_pair[1])- pair_length_list.append(pair_length)- pair_length_list = np.array(pair_length_list)- pair_info = (pair_length_list.max(), pair_length_list.min(),- pair_length_list.mean())-- point_num = len(point_pair_list) * 2- point_list = [0] * point_num- for idx, point_pair in enumerate(point_pair_list):- point_list[idx] = point_pair[0]- point_list[point_num - 1 - idx] = point_pair[1]- return np.array(point_list).reshape(-1, 2), pair_info---def shrink_quad_along_width(quad, begin_width_ratio=0., end_width_ratio=1.):- """- Generate shrink_quad_along_width.- """- ratio_pair = np.array(- [[begin_width_ratio], [end_width_ratio]], dtype=np.float32)- p0_1 = quad[0] + (quad[1] - quad[0]) * ratio_pair- p3_2 = quad[3] + (quad[2] - quad[3]) * ratio_pair- return np.array([p0_1[0], p0_1[1], p3_2[1], p3_2[0]])---def expand_poly_along_width(poly, shrink_ratio_of_width=0.3):- """- expand poly along width.- """- point_num = poly.shape[0]- left_quad = np.array(- [poly[0], poly[1], poly[-2], poly[-1]], dtype=np.float32)- left_ratio = -shrink_ratio_of_width * np.linalg.norm(left_quad[0] - left_quad[3]) / \- (np.linalg.norm(left_quad[0] - left_quad[1]) + 1e-6)- left_quad_expand = shrink_quad_along_width(left_quad, left_ratio, 1.0)- right_quad = np.array(- [- poly[point_num // 2 - 2], poly[point_num // 2 - 1],- poly[point_num // 2], poly[point_num // 2 + 1]- ],- dtype=np.float32)- right_ratio = 1.0 + \- shrink_ratio_of_width * np.linalg.norm(right_quad[0] - right_quad[3]) / \- (np.linalg.norm(right_quad[0] - right_quad[1]) + 1e-6)- right_quad_expand = shrink_quad_along_width(right_quad, 0.0, right_ratio)- poly[0] = left_quad_expand[0]- poly[-1] = left_quad_expand[-1]- poly[point_num // 2 - 1] = right_quad_expand[1]- poly[point_num // 2] = right_quad_expand[2]- return poly---def norm2(x, axis=None):- if axis:- return np.sqrt(np.sum(x**2, axis=axis))- return np.sqrt(np.sum(x**2))---def cos(p1, p2):- return (p1 * p2).sum() / (norm2(p1) * norm2(p2))diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/logging.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/logging.pydeleted file mode 100755index 68d0c2ff..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/logging.py+++ /dev/null@@ -1,52 +0,0 @@-import os-import sys-import logging-import functools-import torch.distributed as dist--logger_initialized = {}--[email protected]_cache()-def get_logger(name='root', log_file=None, log_level=logging.DEBUG):- """Initialize and get a logger by name.- If the logger has not been initialized, this method will initialize the- logger by adding one or two handlers, otherwise the initialized logger will- be directly returned. During initialization, a StreamHandler will always be- added. If `log_file` is specified a FileHandler will also be added.- Args:- name (str): Logger name.- log_file (str | None): The log filename. If specified, a FileHandler- will be added to the logger.- log_level (int): The logger level. Note that only the process of- rank 0 is affected, and other processes will set the level to- "Error" thus be silent most of the time.- Returns:- logging.Logger: The expected logger.- """- logger = logging.getLogger(name)- if name in logger_initialized:- return logger- for logger_name in logger_initialized:- if name.startswith(logger_name):- return logger-- formatter = logging.Formatter(- '[%(asctime)s] %(name)s %(levelname)s: %(message)s',- datefmt="%Y/%m/%d %H:%M:%S")-- stream_handler = logging.StreamHandler(stream=sys.stdout)- stream_handler.setFormatter(formatter)- logger.addHandler(stream_handler)- if log_file is not None and dist.get_rank() == 0:- log_file_folder = os.path.split(log_file)[0]- os.makedirs(log_file_folder, exist_ok=True)- file_handler = logging.FileHandler(log_file, 'a')- file_handler.setFormatter(formatter)- logger.addHandler(file_handler)- # if dist.get_rank() == 0:- # logger.setLevel(log_level)- # else:- # logger.setLevel(logging.ERROR)- logger_initialized[name] = True- return logger\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/poly_nms.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/poly_nms.pydeleted file mode 100755index 9dcb3d2c..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/poly_nms.py+++ /dev/null@@ -1,146 +0,0 @@-# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.--import numpy as np-from shapely.geometry import Polygon---def points2polygon(points):- """Convert k points to 1 polygon.-- Args:- points (ndarray or list): A ndarray or a list of shape (2k)- that indicates k points.-- Returns:- polygon (Polygon): A polygon object.- """- if isinstance(points, list):- points = np.array(points)-- assert isinstance(points, np.ndarray)- assert (points.size % 2 == 0) and (points.size >= 8)-- point_mat = points.reshape([-1, 2])- return Polygon(point_mat)---def poly_intersection(poly_det, poly_gt, buffer=0.0001):- """Calculate the intersection area between two polygon.-- Args:- poly_det (Polygon): A polygon predicted by detector.- poly_gt (Polygon): A gt polygon.-- Returns:- intersection_area (float): The intersection area between two polygons.- """- assert isinstance(poly_det, Polygon)- assert isinstance(poly_gt, Polygon)-- if buffer == 0:- poly_inter = poly_det & poly_gt- else:- poly_inter = poly_det.buffer(buffer) & poly_gt.buffer(buffer)- return poly_inter.area, poly_inter---def poly_union(poly_det, poly_gt):- """Calculate the union area between two polygon.-- Args:- poly_det (Polygon): A polygon predicted by detector.- poly_gt (Polygon): A gt polygon.-- Returns:- union_area (float): The union area between two polygons.- """- assert isinstance(poly_det, Polygon)- assert isinstance(poly_gt, Polygon)-- area_det = poly_det.area- area_gt = poly_gt.area- area_inters, _ = poly_intersection(poly_det, poly_gt)- return area_det + area_gt - area_inters---def valid_boundary(x, with_score=True):- num = len(x)- if num < 8:- return False- if num % 2 == 0 and (not with_score):- return True- if num % 2 == 1 and with_score:- return True-- return False---def boundary_iou(src, target):- """Calculate the IOU between two boundaries.-- Args:- src (list): Source boundary.- target (list): Target boundary.-- Returns:- iou (float): The iou between two boundaries.- """- assert valid_boundary(src, False)- assert valid_boundary(target, False)- src_poly = points2polygon(src)- target_poly = points2polygon(target)-- return poly_iou(src_poly, target_poly)---def poly_iou(poly_det, poly_gt):- """Calculate the IOU between two polygons.-- Args:- poly_det (Polygon): A polygon predicted by detector.- poly_gt (Polygon): A gt polygon.-- Returns:- iou (float): The IOU between two polygons.- """- assert isinstance(poly_det, Polygon)- assert isinstance(poly_gt, Polygon)- area_inters, _ = poly_intersection(poly_det, poly_gt)- area_union = poly_union(poly_det, poly_gt)- if area_union == 0:- return 0.0- return area_inters / area_union---def poly_nms(polygons, threshold):- assert isinstance(polygons, list)-- polygons = np.array(sorted(polygons, key=lambda x: x[-1]))-- keep_poly = []- index = [i for i in range(polygons.shape[0])]-- while len(index) > 0:- keep_poly.append(polygons[index[-1]].tolist())- A = polygons[index[-1]][:-1]- index = np.delete(index, -1)- iou_list = np.zeros((len(index), ))- for i in range(len(index)):- B = polygons[index[i]][:-1]- iou_list[i] = boundary_iou(A, B)- remove_index = np.where(iou_list > threshold)- index = np.delete(index, remove_index)-- return keep_polydiff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/utility.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/utility.pydeleted file mode 100755index 70bb7b71..00000000--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/utility.py+++ /dev/null@@ -1,70 +0,0 @@-import os-import imghdr-import cv2-import logging--def get_image_file_list(img_file):- imgs_lists = []- if img_file is None or not os.path.exists(img_file):- raise Exception("not found any img file in {}".format(img_file))-- img_end = {'jpg', 'bmp', 'png', 'jpeg', 'rgb', 'tif', 'tiff', 'gif', 'GIF'}- if os.path.isfile(img_file) and imghdr.what(img_file) in img_end:- imgs_lists.append(img_file)- elif os.path.isdir(img_file):- for single_file in os.listdir(img_file):- file_path = os.path.join(img_file, single_file)- if imghdr.what(file_path) in img_end:- imgs_lists.append(file_path)- if len(imgs_lists) == 0:- raise Exception("not found any img file in {}".format(img_file))- return imgs_lists---def check_and_read_gif(img_path):- if os.path.basename(img_path)[-3:] in ['gif', 'GIF']:- gif = cv2.VideoCapture(img_path)- ret, frame = gif.read()- if not ret:- # logger = logging.getLogger('ppocr')- print("Cannot read {}. This gif image maybe corrupted.")- # logger.info("Cannot read {}. This gif image maybe corrupted.")- return None, False- if len(frame.shape) == 2 or frame.shape[-1] == 1:- frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)- imgvalue = frame[:, :, ::-1]- return imgvalue, True- return None, False---def check_and_read(img_path):- if os.path.basename(img_path)[-3:] in ['gif', 'GIF']:- gif = cv2.VideoCapture(img_path)- ret, frame = gif.read()- if not ret:- logger = logging.getLogger('ppocr')- logger.info("Cannot read {}. This gif image maybe corrupted.")- return None, False- if len(frame.shape) == 2 or frame.shape[-1] == 1:- frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)- imgvalue = frame[:, :, ::-1]- return imgvalue, True, False- elif os.path.basename(img_path)[-3:] in ['pdf']:- import fitz- from PIL import Image- imgs = []- with fitz.open(img_path) as pdf:- for pg in range(0, pdf.pageCount):- page = pdf[pg]- mat = fitz.Matrix(2, 2)- pm = page.getPixmap(matrix=mat, alpha=False)-- # if width or height > 2000 pixels, don't enlarge the image- if pm.width > 2000 or pm.height > 2000:- pm = page.getPixmap(matrix=fitz.Matrix(1, 1), alpha=False)-- img = Image.frombytes("RGB", [pm.width, pm.height], pm.samples)- img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)- imgs.append(img)- return imgs, False, True- return None, False, False\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_cls.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_cls.pyindex 24c35345..7ebaa48b 100755--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_cls.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_cls.py@@ -1,20 +1,12 @@-import os-import sys--__dir__ = os.path.dirname(os.path.abspath(__file__))-sys.path.append(__dir__)-sys.path.append(os.path.abspath(os.path.join(__dir__, '../..')))-import cv2import copyimport numpy as npimport mathimport timeimport torch-from pytorchocr.base_ocr_v20 import BaseOCRV20-import tools.infer.pytorchocr_utility as utility-from pytorchocr.postprocess import build_post_process-from pytorchocr.utils.utility import get_image_file_list, check_and_read_gif+from ...pytorchocr.base_ocr_v20 import BaseOCRV20+from . import pytorchocr_utility as utility+from ...pytorchocr.postprocess import build_post_processclass TextClassifier(BaseOCRV20):@@ -34,7 +26,8 @@ class TextClassifier(BaseOCRV20):self.weights_path = args.cls_model_pathself.yaml_path = args.cls_yaml_path- network_config = utility.AnalysisConfig(self.weights_path, self.yaml_path)+ # network_config = utility.AnalysisConfig(self.weights_path, self.yaml_path)+ network_config = utility.get_arch_config(self.weights_path)super(TextClassifier, self).__init__(network_config, **kwargs)self.cls_image_shape = [int(v) for v in args.cls_image_shape.split(",")]@@ -46,7 +39,7 @@ class TextClassifier(BaseOCRV20):self.net.eval()# if self.use_gpu:# self.net.cuda()- self.net = self.net.to(self.device)+ self.net.to(self.device)def resize_norm_img(self, img):imgC, imgH, imgW = self.cls_image_shape@@ -119,38 +112,3 @@ class TextClassifier(BaseOCRV20):img_list[indices[beg_img_no + rno]] = cv2.rotate(img_list[indices[beg_img_no + rno]], 1)return img_list, cls_res, elapse---def main(args):- image_file_list = get_image_file_list(args.image_dir)- text_classifier = TextClassifier(args)- valid_image_file_list = []- img_list = []- for image_file in image_file_list:- img, flag = check_and_read_gif(image_file)- if not flag:- img = cv2.imread(image_file)- if img is None:- print("error in loading image:{}".format(image_file))- continue- valid_image_file_list.append(image_file)- img_list.append(img)- try:- img_list, cls_res, predict_time = text_classifier(img_list)- except:- print(- "ERROR!!!! \n"- "Please read the FAQ:https://github.com/PaddlePaddle/PaddleOCR#faq \n"- "If your model has tps module: "- "TPS does not support variable shape.\n"- "Please set --rec_image_shape='3,32,100' and --rec_char_type='en' ")- exit()- for ino in range(len(img_list)):- print("Predicts of {}:{}".format(valid_image_file_list[ino], cls_res[- ino]))- print("Total predict time for {} images, cost: {:.3f}".format(- len(img_list), predict_time))---if __name__ == '__main__':- main(utility.parse_args())\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_det.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_det.pyindex 6d4cbcd5..d6b36345 100755--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_det.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_det.py@@ -1,21 +1,12 @@-import osimport sys-__dir__ = os.path.dirname(os.path.abspath(__file__))-sys.path.append(__dir__)-sys.path.append(os.path.abspath(os.path.join(__dir__, '../..')))-import copy-import cv2import numpy as npimport time-import jsonimport torch-from pytorchocr.base_ocr_v20 import BaseOCRV20-import tools.infer.pytorchocr_utility as utility-from pytorchocr.utils.utility import get_image_file_list, check_and_read_gif-from pytorchocr.data import create_operators, transform-from pytorchocr.postprocess import build_post_process-+from ...pytorchocr.base_ocr_v20 import BaseOCRV20+from . import pytorchocr_utility as utility+from ...pytorchocr.data import create_operators, transform+from ...pytorchocr.postprocess import build_post_processclass TextDetector(BaseOCRV20):@@ -123,13 +114,14 @@ class TextDetector(BaseOCRV20):self.weights_path = args.det_model_pathself.yaml_path = args.det_yaml_path- network_config = utility.AnalysisConfig(self.weights_path, self.yaml_path)+ # network_config = utility.AnalysisConfig(self.weights_path, self.yaml_path)+ network_config = utility.get_arch_config(self.weights_path)super(TextDetector, self).__init__(network_config, **kwargs)self.load_pytorch_weights(self.weights_path)self.net.eval()# if self.use_gpu:# self.net.cuda()- self.net = self.net.to(self.device)+ self.net.to(self.device)def order_points_clockwise(self, pts):"""@@ -231,38 +223,3 @@ class TextDetector(BaseOCRV20):elapse = time.time() - starttimereturn dt_boxes, elapse----if __name__ == "__main__":- args = utility.parse_args()- image_file_list = get_image_file_list(args.image_dir)- text_detector = TextDetector(args)- count = 0- total_time = 0- draw_img_save = "./inference_results"- if not os.path.exists(draw_img_save):- os.makedirs(draw_img_save)- for image_file in image_file_list:- img, flag = check_and_read_gif(image_file)- if not flag:- img = cv2.imread(image_file)- if img is None:- print("error in loading image:{}".format(image_file))- continue- dt_boxes, elapse = text_detector(img)- if count > 0:- total_time += elapse- count += 1- save_pred = os.path.basename(image_file) + "\t" + str(- json.dumps(np.array(dt_boxes).astype(np.int32).tolist())) + "\n"- print(save_pred)- print("Predict time of {}: {}".format(image_file, elapse))- src_im = utility.draw_text_det_res(dt_boxes, image_file)- img_name_pure = os.path.split(image_file)[-1]- img_path = os.path.join(draw_img_save,- "det_res_{}".format(img_name_pure))- cv2.imwrite(img_path, src_im)- print("The visualized image saved in {}".format(img_path))- if count > 1:- print("Avg Time: {}".format(total_time / (count - 1)))diff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_rec.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_rec.pyindex f19aab16..9b88115b 100755--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_rec.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_rec.py@@ -1,19 +1,12 @@-import os-import sys--__dir__ = os.path.dirname(os.path.abspath(__file__))-sys.path.append(__dir__)-sys.path.append(os.path.abspath(os.path.join(__dir__, '../..')))from PIL import Imageimport cv2import numpy as npimport mathimport timeimport torch-from pytorchocr.base_ocr_v20 import BaseOCRV20-import tools.infer.pytorchocr_utility as utility-from pytorchocr.postprocess import build_post_process-from pytorchocr.utils.utility import get_image_file_list, check_and_read_gif+from ...pytorchocr.base_ocr_v20 import BaseOCRV20+from . import pytorchocr_utility as utility+from ...pytorchocr.postprocess import build_post_processclass TextRecognizer(BaseOCRV20):@@ -87,7 +80,8 @@ class TextRecognizer(BaseOCRV20):self.yaml_path = args.rec_yaml_pathchar_num = len(getattr(self.postprocess_op, 'character'))- network_config = utility.AnalysisConfig(self.weights_path, self.yaml_path, char_num)+ # network_config = utility.AnalysisConfig(self.weights_path, self.yaml_path, char_num)+ network_config = utility.get_arch_config(self.weights_path)weights = self.read_pytorch_weights(self.weights_path)self.out_channels = self.get_out_channels(weights)@@ -103,7 +97,7 @@ class TextRecognizer(BaseOCRV20):self.net.eval()# if self.use_gpu:# self.net.cuda()- self.net = self.net.to(self.device)+ self.net.to(self.device)def resize_norm_img(self, img, max_wh_ratio):imgC, imgH, imgW = self.rec_image_shape@@ -452,33 +446,3 @@ class TextRecognizer(BaseOCRV20):rec_res[indices[beg_img_no + rno]] = rec_result[rno]elapse += time.time() - starttimereturn rec_res, elapse---def main(args):- image_file_list = get_image_file_list(args.image_dir)- text_recognizer = TextRecognizer(args)- valid_image_file_list = []- img_list = []- for image_file in image_file_list:- img, flag = check_and_read_gif(image_file)- if not flag:- img = cv2.imread(image_file)- if img is None:- print("error in loading image:{}".format(image_file))- continue- valid_image_file_list.append(image_file)- img_list.append(img)- try:- rec_res, predict_time = text_recognizer(img_list)- except Exception as e:- print(e)- exit()- for ino in range(len(img_list)):- print("Predicts of {}:{}".format(valid_image_file_list[ino], rec_res[- ino]))- print("Total predict time for {} images, cost: {:.3f}".format(- len(img_list), predict_time))---if __name__ == '__main__':- main(utility.parse_args())\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_system.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_system.pyindex f0f9fd6b..9c180446 100755--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_system.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_system.py@@ -1,22 +1,10 @@-import os-import sys--__dir__ = os.path.dirname(os.path.abspath(__file__))-sys.path.append(__dir__)-sys.path.append(os.path.abspath(os.path.join(__dir__, '../..')))-import cv2import copyimport numpy as np-import time-from PIL import Image-import tools.infer.pytorchocr_utility as utility-import tools.infer.predict_rec as predict_rec-import tools.infer.predict_det as predict_det-import tools.infer.predict_cls as predict_cls-from pytorchocr.utils.utility import get_image_file_list, check_and_read_gif-from tools.infer.pytorchocr_utility import draw_ocr_box_txt+from . import predict_rec+from . import predict_det+from . import predict_clsclass TextSystem(object):@@ -121,51 +109,3 @@ def sorted_boxes(dt_boxes):_boxes[i] = _boxes[i + 1]_boxes[i + 1] = tmpreturn _boxes---def main(args):- image_file_list = get_image_file_list(args.image_dir)- text_sys = TextSystem(args)- is_visualize = True- font_path = args.vis_font_path- drop_score = args.drop_score- for image_file in image_file_list:- img, flag = check_and_read_gif(image_file)- if not flag:- img = cv2.imread(image_file)- if img is None:- print("error in loading image:{}".format(image_file))- continue- starttime = time.time()- dt_boxes, rec_res = text_sys(img)- elapse = time.time() - starttime- print("Predict time of %s: %.3fs" % (image_file, elapse))-- for text, score in rec_res:- print("{}, {:.3f}".format(text, score))-- if is_visualize:- image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))- boxes = dt_boxes- txts = [rec_res[i][0] for i in range(len(rec_res))]- scores = [rec_res[i][1] for i in range(len(rec_res))]-- draw_img = draw_ocr_box_txt(- image,- boxes,- txts,- scores,- drop_score=drop_score,- font_path=font_path)- draw_img_save = "./inference_results/"- if not os.path.exists(draw_img_save):- os.makedirs(draw_img_save)- cv2.imwrite(- os.path.join(draw_img_save, os.path.basename(image_file)),- draw_img[:, :, ::-1])- print("The visualized image saved in {}".format(- os.path.join(draw_img_save, os.path.basename(image_file))))---if __name__ == '__main__':- main(utility.parse_args())\ No newline at end of filediff --git a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/pytorchocr_utility.py b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/pytorchocr_utility.pyindex 2d30d2f6..fd832207 100755--- a/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/pytorchocr_utility.py+++ b/magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/pytorchocr_utility.py@@ -1,10 +1,15 @@-import os, sys+import osimport math+from pathlib import Pathimport numpy as npimport cv2-from PIL import Image, ImageDraw, ImageFontimport argparse++root_dir = Path(__file__).resolve().parent.parent.parent+DEFAULT_CFG_PATH = root_dir / "pytorchocr" / "modeling" / "arch_config.yaml"++def init_args():def str2bool(v):return v.lower() in ("true", "t", "1")@@ -64,7 +69,7 @@ def init_args():parser.add_argument("--rec_algorithm", type=str, default='CRNN')parser.add_argument("--rec_model_path", type=str)parser.add_argument("--rec_image_inverse", type=str2bool, default=True)- parser.add_argument("--rec_image_shape", type=str, default="3, 32, 320")+ parser.add_argument("--rec_image_shape", type=str, default="3, 48, 320")parser.add_argument("--rec_char_type", type=str, default='ch')parser.add_argument("--rec_batch_num", type=int, default=6)parser.add_argument("--max_text_length", type=int, default=25)@@ -165,215 +170,6 @@ def AnalysisConfig(weights_path, yaml_path=None, char_num=None):if yaml_path is not None:return read_network_config_from_yaml(yaml_path, char_num=char_num)- weights_basename = os.path.basename(weights_path)- weights_name = weights_basename.lower()-- # supported_weights = ['ch_ptocr_server_v2.0_det_infer.pth',- # 'ch_ptocr_server_v2.0_rec_infer.pth',- # 'ch_ptocr_mobile_v2.0_det_infer.pth',- # 'ch_ptocr_mobile_v2.0_rec_infer.pth',- # 'ch_ptocr_mobile_v2.0_cls_infer.pth',- # ]- # assert weights_name in supported_weights, \- # "supported weights are {} but input weights is {}".format(supported_weights, weights_name)-- if weights_name == 'ch_ptocr_server_v2.0_det_infer.pth':- network_config = {'model_type':'det',- 'algorithm':'DB',- 'Transform':None,- 'Backbone':{'name':'ResNet_vd', 'layers':18, 'disable_se':True},- 'Neck':{'name':'DBFPN', 'out_channels':256},- 'Head':{'name':'DBHead', 'k':50}}-- elif weights_name == 'ch_ptocr_server_v2.0_rec_infer.pth':- network_config = {'model_type':'rec',- 'algorithm':'CRNN',- 'Transform':None,- 'Backbone':{'name':'ResNet', 'layers':34},- 'Neck':{'name':'SequenceEncoder', 'hidden_size':256, 'encoder_type':'rnn'},- 'Head':{'name':'CTCHead', 'fc_decay': 4e-05}}-- elif weights_name in ['ch_ptocr_mobile_v2.0_det_infer.pth']:- network_config = {'model_type': 'det',- 'algorithm': 'DB',- 'Transform': None,- 'Backbone': {'name': 'MobileNetV3', 'model_name': 'large', 'scale': 0.5, 'disable_se': True},- 'Neck': {'name': 'DBFPN', 'out_channels': 96},- 'Head': {'name': 'DBHead', 'k': 50}}-- elif weights_name =='ch_ptocr_mobile_v2.0_rec_infer.pth':- network_config = {'model_type':'rec',- 'algorithm':'CRNN',- 'Transform':None,- 'Backbone':{'model_name':'small', 'name':'MobileNetV3', 'scale':0.5, 'small_stride':[1,2,2,2]},- 'Neck':{'name':'SequenceEncoder', 'hidden_size':48, 'encoder_type':'rnn'},- 'Head':{'name':'CTCHead', 'fc_decay': 4e-05}}-- elif weights_name == 'ch_ptocr_mobile_v2.0_cls_infer.pth':- network_config = {'model_type':'cls',- 'algorithm':'CLS',- 'Transform':None,- 'Backbone':{'name':'MobileNetV3', 'model_name':'small', 'scale':0.35},- 'Neck':None,- 'Head':{'name':'ClsHead', 'class_dim':2}}-- elif weights_name == 'ch_ptocr_v2_rec_infer.pth':- network_config = {'model_type': 'rec',- 'algorithm': 'CRNN',- 'Transform': None,- 'Backbone': {'name': 'MobileNetV1Enhance', 'scale': 0.5},- 'Neck': {'name': 'SequenceEncoder', 'hidden_size': 64, 'encoder_type': 'rnn'},- 'Head': {'name': 'CTCHead', 'mid_channels': 96, 'fc_decay': 2e-05}}-- elif weights_name == 'ch_ptocr_v2_det_infer.pth':- network_config = {'model_type': 'det',- 'algorithm': 'DB',- 'Transform': None,- 'Backbone': {'name': 'MobileNetV3', 'model_name': 'large', 'scale': 0.5, 'disable_se': True},- 'Neck': {'name': 'DBFPN', 'out_channels': 96},- 'Head': {'name': 'DBHead', 'k': 50}}-- elif weights_name == 'ch_ptocr_v3_rec_infer.pth':- network_config = {'model_type':'rec',- 'algorithm':'CRNN',- 'Transform':None,- 'Backbone':{'name':'MobileNetV1Enhance',- 'scale':0.5,- 'last_conv_stride': [1, 2],- 'last_pool_type': 'avg'},- 'Neck':{'name':'SequenceEncoder',- 'dims': 64,- 'depth': 2,- 'hidden_dims': 120,- 'use_guide': True,- 'encoder_type':'svtr'},- 'Head':{'name':'CTCHead', 'fc_decay': 2e-05}- }-- elif weights_name == 'ch_ptocr_v3_det_infer.pth':- network_config = {'model_type': 'det',- 'algorithm': 'DB',- 'Transform': None,- 'Backbone': {'name': 'MobileNetV3', 'model_name': 'large', 'scale': 0.5, 'disable_se': True},- 'Neck': {'name': 'RSEFPN', 'out_channels': 96, 'shortcut': True},- 'Head': {'name': 'DBHead', 'k': 50}}-- elif weights_name == 'det_mv3_db_v2.0_infer.pth':- network_config = {'model_type': 'det',- 'algorithm': 'DB',- 'Transform': None,- 'Backbone': {'name': 'MobileNetV3', 'model_name': 'large'},- 'Neck': {'name': 'DBFPN', 'out_channels': 256},- 'Head': {'name': 'DBHead', 'k': 50}}-- elif weights_name == 'det_r50_vd_db_v2.0_infer.pth':- network_config = {'model_type': 'det',- 'algorithm': 'DB',- 'Transform': None,- 'Backbone': {'name': 'ResNet_vd', 'layers': 50},- 'Neck': {'name': 'DBFPN', 'out_channels': 256},- 'Head': {'name': 'DBHead', 'k': 50}}-- elif weights_name == 'det_mv3_east_v2.0_infer.pth':- network_config = {'model_type': 'det',- 'algorithm': 'EAST',- 'Transform': None,- 'Backbone': {'name': 'MobileNetV3', 'model_name': 'large'},- 'Neck': {'name': 'EASTFPN', 'model_name': 'small'},- 'Head': {'name': 'EASTHead', 'model_name': 'small'}}-- elif weights_name == 'det_r50_vd_east_v2.0_infer.pth':- network_config = {'model_type': 'det',- 'algorithm': 'EAST',- 'Transform': None,- 'Backbone': {'name': 'ResNet_vd', 'layers': 50},- 'Neck': {'name': 'EASTFPN', 'model_name': 'large'},- 'Head': {'name': 'EASTHead', 'model_name': 'large'}}-- elif weights_name == 'det_r50_vd_sast_icdar15_v2.0_infer.pth':- network_config = {'model_type': 'det',- 'algorithm': 'SAST',- 'Transform': None,- 'Backbone': {'name': 'ResNet_SAST', 'layers': 50},- 'Neck': {'name': 'SASTFPN', 'with_cab': True},- 'Head': {'name': 'SASTHead'}}-- elif weights_name == 'det_r50_vd_sast_totaltext_v2.0_infer.pth':- network_config = {'model_type': 'det',- 'algorithm': 'SAST',- 'Transform': None,- 'Backbone': {'name': 'ResNet_SAST', 'layers': 50},- 'Neck': {'name': 'SASTFPN', 'with_cab': True},- 'Head': {'name': 'SASTHead'}}-- elif weights_name == 'en_server_pgneta_infer.pth':- network_config = {'model_type': 'e2e',- 'algorithm': 'PGNet',- 'Transform': None,- 'Backbone': {'name': 'ResNet', 'layers': 50},- 'Neck': {'name': 'PGFPN'},- 'Head': {'name': 'PGHead'}}-- elif weights_name == 'en_ptocr_mobile_v2.0_table_det_infer.pth':- network_config = {'model_type': 'det','algorithm': 'DB',- 'Transform': None,- 'Backbone': {'name': 'MobileNetV3', 'model_name': 'large', 'scale': 0.5, 'disable_se': False},- 'Neck': {'name': 'DBFPN', 'out_channels': 96},- 'Head': {'name': 'DBHead', 'k': 50}}-- elif weights_name == 'en_ptocr_mobile_v2.0_table_rec_infer.pth':- network_config = {'model_type': 'rec',- 'algorithm': 'CRNN',- 'Transform': None,- 'Backbone': {'model_name': 'large', 'name': 'MobileNetV3', },- 'Neck': {'name': 'SequenceEncoder', 'hidden_size': 96, 'encoder_type': 'rnn'},- 'Head': {'name': 'CTCHead', 'fc_decay': 4e-05}}-- elif 'om_' in weights_name and '_rec_' in weights_name:- network_config = {'model_type': 'rec',- 'algorithm': 'CRNN',- 'Transform': None,- 'Backbone': {'model_name': 'small', 'name': 'MobileNetV3', 'scale': 0.5,- 'small_stride': [1, 2, 2, 2]},- 'Neck': {'name': 'SequenceEncoder', 'hidden_size': 48, 'encoder_type': 'om'},- 'Head': {'name': 'CTCHead', 'fc_decay': 4e-05}}-- else:- network_config = {'model_type': 'rec',- 'algorithm': 'CRNN',- 'Transform': None,- 'Backbone': {'model_name': 'small', 'name': 'MobileNetV3', 'scale': 0.5,- 'small_stride': [1, 2, 2, 2]},- 'Neck': {'name': 'SequenceEncoder', 'hidden_size': 48, 'encoder_type': 'rnn'},- 'Head': {'name': 'CTCHead', 'fc_decay': 4e-05}}- # raise NotImplementedError-- return network_config---def draw_e2e_res(dt_boxes, strs, img_path):- src_im = cv2.imread(img_path)- for box, str in zip(dt_boxes, strs):- box = box.astype(np.int32).reshape((-1, 1, 2))- cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2)- cv2.putText(- src_im,- str,- org=(int(box[0, 0, 0]), int(box[0, 0, 1])),- fontFace=cv2.FONT_HERSHEY_COMPLEX,- fontScale=0.7,- color=(0, 255, 0),- thickness=1)- return src_im---def draw_text_det_res(dt_boxes, img_path):- src_im = cv2.imread(img_path)- for box in dt_boxes:- box = np.array(box).astype(np.int32).reshape(-1, 2)- cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2)- return src_im-def resize_img(img, input_size=600):"""@@ -387,58 +183,6 @@ def resize_img(img, input_size=600):return img-def draw_ocr_box_txt(image,- boxes,- txts,- scores=None,- drop_score=0.5,- font_path="./doc/simfang.ttf"):- h, w = image.height, image.width- img_left = image.copy()- img_right = Image.new('RGB', (w, h), (255, 255, 255))-- import random-- random.seed(0)- 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, 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.truetype(font_path, font_size, encoding="utf-8")- 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.truetype(font_path, font_size, encoding="utf-8")- 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))- return np.array(img_show)--def str_count(s):"""Count the number of Chinese characters,@@ -463,82 +207,6 @@ def str_count(s):return s_len - math.ceil(en_dg_count / 2)-def text_visual(texts,- scores,- img_h=400,- img_w=600,- threshold=0.,- font_path="./doc/simfang.ttf"):- """- create new blank img and draw txt on it- args:- texts(list): the text will be draw- scores(list|None): corresponding score of each txt- img_h(int): the height of blank img- img_w(int): the width of blank img- font_path: the path of font which is used to draw text- return(array):- """- if scores is not None:- assert len(texts) == len(- scores), "The number of txts and corresponding scores must match"-- def create_blank_img():- blank_img = np.ones(shape=[img_h, img_w], dtype=np.int8) * 255- blank_img[:, img_w - 1:] = 0- blank_img = Image.fromarray(blank_img).convert("RGB")- draw_txt = ImageDraw.Draw(blank_img)- return blank_img, draw_txt-- blank_img, draw_txt = create_blank_img()-- font_size = 20- txt_color = (0, 0, 0)- font = ImageFont.truetype(font_path, font_size, encoding="utf-8")-- gap = font_size + 5- txt_img_list = []- count, index = 1, 0- for idx, txt in enumerate(texts):- index += 1- if scores[idx] < threshold or math.isnan(scores[idx]):- index -= 1- continue- first_line = True- while str_count(txt) >= img_w // font_size - 4:- tmp = txt- txt = tmp[:img_w // font_size - 4]- if first_line:- new_txt = str(index) + ': ' + txt- first_line = False- else:- new_txt = ' ' + txt- draw_txt.text((0, gap * count), new_txt, txt_color, font=font)- txt = tmp[img_w // font_size - 4:]- if count >= img_h // gap - 1:- txt_img_list.append(np.array(blank_img))- blank_img, draw_txt = create_blank_img()- count = 0- count += 1- if first_line:- new_txt = str(index) + ': ' + txt + ' ' + '%.3f' % (scores[idx])- else:- new_txt = " " + txt + " " + '%.3f' % (scores[idx])- draw_txt.text((0, gap * count), new_txt, txt_color, font=font)- # whether add new blank img or not- if count >= img_h // gap - 1 and idx + 1 < len(texts):- txt_img_list.append(np.array(blank_img))- blank_img, draw_txt = create_blank_img()- count = 0- count += 1- txt_img_list.append(np.array(blank_img))- if len(txt_img_list) == 1:- blank_img = np.array(txt_img_list[0])- else:- blank_img = np.concatenate(txt_img_list, axis=1)- return np.array(blank_img)--def base64_to_cv2(b64str):import base64data = base64.b64decode(b64str.encode('utf8'))@@ -547,12 +215,13 @@ def base64_to_cv2(b64str):return data-def draw_boxes(image, boxes, scores=None, drop_score=0.5):- if scores is None:- scores = [1] * len(boxes)- for (box, score) in zip(boxes, scores):- if score < drop_score:- continue- box = np.reshape(np.array(box), [-1, 1, 2]).astype(np.int64)- image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)- return image\ No newline at end of file+def get_arch_config(model_path):+ from omegaconf import OmegaConf+ all_arch_config = OmegaConf.load(DEFAULT_CFG_PATH)+ path = Path(model_path)+ file_name = path.stem+ if file_name not in all_arch_config:+ raise ValueError(f"architecture {file_name} is not in arch_config.yaml")++ arch_config = all_arch_config[file_name]+ return arch_config\ No newline at end of file