magic-pdf 1.3.7__py3-none-any.whl → 1.3.9__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- magic_pdf/libs/version.py +1 -1
- magic_pdf/model/sub_modules/mfr/unimernet/unimernet_hf/modeling_unimernet.py +310 -15
- magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorch_paddle.py +3 -2
- magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/arch_config.yaml +25 -0
- magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/dict/ppocrv4_doc_dict.txt +15629 -0
- magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/models_config.yml +5 -1
- {magic_pdf-1.3.7.dist-info → magic_pdf-1.3.9.dist-info}/METADATA +12 -3
- {magic_pdf-1.3.7.dist-info → magic_pdf-1.3.9.dist-info}/RECORD +12 -11
- {magic_pdf-1.3.7.dist-info → magic_pdf-1.3.9.dist-info}/LICENSE.md +0 -0
- {magic_pdf-1.3.7.dist-info → magic_pdf-1.3.9.dist-info}/WHEEL +0 -0
- {magic_pdf-1.3.7.dist-info → magic_pdf-1.3.9.dist-info}/entry_points.txt +0 -0
- {magic_pdf-1.3.7.dist-info → magic_pdf-1.3.9.dist-info}/top_level.txt +0 -0
magic_pdf/libs/version.py
CHANGED
@@ -1 +1 @@
|
|
1
|
-
__version__ = "1.3.
|
1
|
+
__version__ = "1.3.9"
|
@@ -5,6 +5,7 @@ from typing import Optional
|
|
5
5
|
|
6
6
|
import torch
|
7
7
|
from ftfy import fix_text
|
8
|
+
from loguru import logger
|
8
9
|
|
9
10
|
from transformers import AutoConfig, AutoModel, AutoModelForCausalLM, AutoTokenizer, PretrainedConfig, PreTrainedModel
|
10
11
|
from transformers import VisionEncoderDecoderConfig, VisionEncoderDecoderModel
|
@@ -57,22 +58,316 @@ class TokenizerWrapper:
|
|
57
58
|
return toks
|
58
59
|
|
59
60
|
|
60
|
-
|
61
|
-
|
61
|
+
LEFT_PATTERN = re.compile(r'(\\left)(\S*)')
|
62
|
+
RIGHT_PATTERN = re.compile(r'(\\right)(\S*)')
|
63
|
+
LEFT_COUNT_PATTERN = re.compile(r'\\left(?![a-zA-Z])')
|
64
|
+
RIGHT_COUNT_PATTERN = re.compile(r'\\right(?![a-zA-Z])')
|
65
|
+
LEFT_RIGHT_REMOVE_PATTERN = re.compile(r'\\left\.?|\\right\.?')
|
66
|
+
|
67
|
+
def fix_latex_left_right(s):
|
68
|
+
"""
|
69
|
+
修复LaTeX中的\left和\right命令
|
70
|
+
1. 确保它们后面跟有效分隔符
|
71
|
+
2. 平衡\left和\right的数量
|
72
|
+
"""
|
73
|
+
# 白名单分隔符
|
74
|
+
valid_delims_list = [r'(', r')', r'[', r']', r'{', r'}', r'/', r'|',
|
75
|
+
r'\{', r'\}', r'\lceil', r'\rceil', r'\lfloor',
|
76
|
+
r'\rfloor', r'\backslash', r'\uparrow', r'\downarrow',
|
77
|
+
r'\Uparrow', r'\Downarrow', r'\|', r'\.']
|
78
|
+
|
79
|
+
# 为\left后缺失有效分隔符的情况添加点
|
80
|
+
def fix_delim(match, is_left=True):
|
81
|
+
cmd = match.group(1) # \left 或 \right
|
82
|
+
rest = match.group(2) if len(match.groups()) > 1 else ""
|
83
|
+
if not rest or rest not in valid_delims_list:
|
84
|
+
return cmd + "."
|
85
|
+
return match.group(0)
|
86
|
+
|
87
|
+
# 使用更精确的模式匹配\left和\right命令
|
88
|
+
# 确保它们是独立的命令,不是其他命令的一部分
|
89
|
+
# 使用预编译正则和统一回调函数
|
90
|
+
s = LEFT_PATTERN.sub(lambda m: fix_delim(m, True), s)
|
91
|
+
s = RIGHT_PATTERN.sub(lambda m: fix_delim(m, False), s)
|
92
|
+
|
93
|
+
# 更精确地计算\left和\right的数量
|
94
|
+
left_count = len(LEFT_COUNT_PATTERN.findall(s)) # 不匹配\lefteqn等
|
95
|
+
right_count = len(RIGHT_COUNT_PATTERN.findall(s)) # 不匹配\rightarrow等
|
96
|
+
|
97
|
+
if left_count == right_count:
|
98
|
+
# 如果数量相等,检查是否在同一组
|
99
|
+
return fix_left_right_pairs(s)
|
100
|
+
else:
|
101
|
+
# 如果数量不等,移除所有\left和\right
|
102
|
+
# logger.debug(f"latex:{s}")
|
103
|
+
# logger.warning(f"left_count: {left_count}, right_count: {right_count}")
|
104
|
+
return LEFT_RIGHT_REMOVE_PATTERN.sub('', s)
|
105
|
+
|
106
|
+
|
107
|
+
def fix_left_right_pairs(latex_formula):
|
62
108
|
"""
|
63
|
-
|
64
|
-
|
65
|
-
|
66
|
-
|
67
|
-
|
68
|
-
|
69
|
-
|
70
|
-
|
71
|
-
|
72
|
-
|
73
|
-
|
74
|
-
|
75
|
-
|
109
|
+
检测并修复LaTeX公式中\left和\right不在同一组的情况
|
110
|
+
|
111
|
+
Args:
|
112
|
+
latex_formula (str): 输入的LaTeX公式
|
113
|
+
|
114
|
+
Returns:
|
115
|
+
str: 修复后的LaTeX公式
|
116
|
+
"""
|
117
|
+
# 用于跟踪花括号嵌套层级
|
118
|
+
brace_stack = []
|
119
|
+
# 用于存储\left信息: (位置, 深度, 分隔符)
|
120
|
+
left_stack = []
|
121
|
+
# 存储需要调整的\right信息: (开始位置, 结束位置, 目标位置)
|
122
|
+
adjustments = []
|
123
|
+
|
124
|
+
i = 0
|
125
|
+
while i < len(latex_formula):
|
126
|
+
# 检查是否是转义字符
|
127
|
+
if i > 0 and latex_formula[i - 1] == '\\':
|
128
|
+
backslash_count = 0
|
129
|
+
j = i - 1
|
130
|
+
while j >= 0 and latex_formula[j] == '\\':
|
131
|
+
backslash_count += 1
|
132
|
+
j -= 1
|
133
|
+
|
134
|
+
if backslash_count % 2 == 1:
|
135
|
+
i += 1
|
136
|
+
continue
|
137
|
+
|
138
|
+
# 检测\left命令
|
139
|
+
if i + 5 < len(latex_formula) and latex_formula[i:i + 5] == "\\left" and i + 5 < len(latex_formula):
|
140
|
+
delimiter = latex_formula[i + 5]
|
141
|
+
left_stack.append((i, len(brace_stack), delimiter))
|
142
|
+
i += 6 # 跳过\left和分隔符
|
143
|
+
continue
|
144
|
+
|
145
|
+
# 检测\right命令
|
146
|
+
elif i + 6 < len(latex_formula) and latex_formula[i:i + 6] == "\\right" and i + 6 < len(latex_formula):
|
147
|
+
delimiter = latex_formula[i + 6]
|
148
|
+
|
149
|
+
if left_stack:
|
150
|
+
left_pos, left_depth, left_delim = left_stack.pop()
|
151
|
+
|
152
|
+
# 如果\left和\right不在同一花括号深度
|
153
|
+
if left_depth != len(brace_stack):
|
154
|
+
# 找到\left所在花括号组的结束位置
|
155
|
+
target_pos = find_group_end(latex_formula, left_pos, left_depth)
|
156
|
+
if target_pos != -1:
|
157
|
+
# 记录需要移动的\right
|
158
|
+
adjustments.append((i, i + 7, target_pos))
|
159
|
+
|
160
|
+
i += 7 # 跳过\right和分隔符
|
161
|
+
continue
|
162
|
+
|
163
|
+
# 处理花括号
|
164
|
+
if latex_formula[i] == '{':
|
165
|
+
brace_stack.append(i)
|
166
|
+
elif latex_formula[i] == '}':
|
167
|
+
if brace_stack:
|
168
|
+
brace_stack.pop()
|
169
|
+
|
170
|
+
i += 1
|
171
|
+
|
172
|
+
# 应用调整,从后向前处理以避免索引变化
|
173
|
+
if not adjustments:
|
174
|
+
return latex_formula
|
175
|
+
|
176
|
+
result = list(latex_formula)
|
177
|
+
adjustments.sort(reverse=True, key=lambda x: x[0])
|
178
|
+
|
179
|
+
for start, end, target in adjustments:
|
180
|
+
# 提取\right部分
|
181
|
+
right_part = result[start:end]
|
182
|
+
# 从原位置删除
|
183
|
+
del result[start:end]
|
184
|
+
# 在目标位置插入
|
185
|
+
result.insert(target, ''.join(right_part))
|
186
|
+
|
187
|
+
return ''.join(result)
|
188
|
+
|
189
|
+
|
190
|
+
def find_group_end(text, pos, depth):
|
191
|
+
"""查找特定深度的花括号组的结束位置"""
|
192
|
+
current_depth = depth
|
193
|
+
i = pos
|
194
|
+
|
195
|
+
while i < len(text):
|
196
|
+
if text[i] == '{' and (i == 0 or not is_escaped(text, i)):
|
197
|
+
current_depth += 1
|
198
|
+
elif text[i] == '}' and (i == 0 or not is_escaped(text, i)):
|
199
|
+
current_depth -= 1
|
200
|
+
if current_depth < depth:
|
201
|
+
return i
|
202
|
+
i += 1
|
203
|
+
|
204
|
+
return -1 # 未找到对应结束位置
|
205
|
+
|
206
|
+
|
207
|
+
def is_escaped(text, pos):
|
208
|
+
"""检查字符是否被转义"""
|
209
|
+
backslash_count = 0
|
210
|
+
j = pos - 1
|
211
|
+
while j >= 0 and text[j] == '\\':
|
212
|
+
backslash_count += 1
|
213
|
+
j -= 1
|
214
|
+
|
215
|
+
return backslash_count % 2 == 1
|
216
|
+
|
217
|
+
|
218
|
+
def fix_unbalanced_braces(latex_formula):
|
219
|
+
"""
|
220
|
+
检测LaTeX公式中的花括号是否闭合,并删除无法配对的花括号
|
221
|
+
|
222
|
+
Args:
|
223
|
+
latex_formula (str): 输入的LaTeX公式
|
224
|
+
|
225
|
+
Returns:
|
226
|
+
str: 删除无法配对的花括号后的LaTeX公式
|
227
|
+
"""
|
228
|
+
stack = [] # 存储左括号的索引
|
229
|
+
unmatched = set() # 存储不匹配括号的索引
|
230
|
+
i = 0
|
231
|
+
|
232
|
+
while i < len(latex_formula):
|
233
|
+
# 检查是否是转义的花括号
|
234
|
+
if latex_formula[i] in ['{', '}']:
|
235
|
+
# 计算前面连续的反斜杠数量
|
236
|
+
backslash_count = 0
|
237
|
+
j = i - 1
|
238
|
+
while j >= 0 and latex_formula[j] == '\\':
|
239
|
+
backslash_count += 1
|
240
|
+
j -= 1
|
241
|
+
|
242
|
+
# 如果前面有奇数个反斜杠,则该花括号是转义的,不参与匹配
|
243
|
+
if backslash_count % 2 == 1:
|
244
|
+
i += 1
|
245
|
+
continue
|
246
|
+
|
247
|
+
# 否则,该花括号参与匹配
|
248
|
+
if latex_formula[i] == '{':
|
249
|
+
stack.append(i)
|
250
|
+
else: # latex_formula[i] == '}'
|
251
|
+
if stack: # 有对应的左括号
|
252
|
+
stack.pop()
|
253
|
+
else: # 没有对应的左括号
|
254
|
+
unmatched.add(i)
|
255
|
+
|
256
|
+
i += 1
|
257
|
+
|
258
|
+
# 所有未匹配的左括号
|
259
|
+
unmatched.update(stack)
|
260
|
+
|
261
|
+
# 构建新字符串,删除不匹配的括号
|
262
|
+
return ''.join(char for i, char in enumerate(latex_formula) if i not in unmatched)
|
263
|
+
|
264
|
+
|
265
|
+
def process_latex(input_string):
|
266
|
+
"""
|
267
|
+
处理LaTeX公式中的反斜杠:
|
268
|
+
1. 如果\后跟特殊字符(#$%&~_^\\{})或空格,保持不变
|
269
|
+
2. 如果\后跟两个小写字母,保持不变
|
270
|
+
3. 其他情况,在\后添加空格
|
271
|
+
|
272
|
+
Args:
|
273
|
+
input_string (str): 输入的LaTeX公式
|
274
|
+
|
275
|
+
Returns:
|
276
|
+
str: 处理后的LaTeX公式
|
277
|
+
"""
|
278
|
+
|
279
|
+
def replace_func(match):
|
280
|
+
# 获取\后面的字符
|
281
|
+
next_char = match.group(1)
|
282
|
+
|
283
|
+
# 如果是特殊字符或空格,保持不变
|
284
|
+
if next_char in "#$%&~_^|\\{} \t\n\r\v\f":
|
285
|
+
return match.group(0)
|
286
|
+
|
287
|
+
# 如果是字母,检查下一个字符
|
288
|
+
if 'a' <= next_char <= 'z' or 'A' <= next_char <= 'Z':
|
289
|
+
pos = match.start() + 2 # \x后的位置
|
290
|
+
if pos < len(input_string) and ('a' <= input_string[pos] <= 'z' or 'A' <= input_string[pos] <= 'Z'):
|
291
|
+
# 下一个字符也是字母,保持不变
|
292
|
+
return match.group(0)
|
293
|
+
|
294
|
+
# 其他情况,在\后添加空格
|
295
|
+
return '\\' + ' ' + next_char
|
296
|
+
|
297
|
+
# 匹配\后面跟一个字符的情况
|
298
|
+
pattern = r'\\(.)'
|
299
|
+
|
300
|
+
return re.sub(pattern, replace_func, input_string)
|
301
|
+
|
302
|
+
# 常见的在KaTeX/MathJax中可用的数学环境
|
303
|
+
ENV_TYPES = ['array', 'matrix', 'pmatrix', 'bmatrix', 'vmatrix',
|
304
|
+
'Bmatrix', 'Vmatrix', 'cases', 'aligned', 'gathered']
|
305
|
+
ENV_BEGIN_PATTERNS = {env: re.compile(r'\\begin\{' + env + r'\}') for env in ENV_TYPES}
|
306
|
+
ENV_END_PATTERNS = {env: re.compile(r'\\end\{' + env + r'\}') for env in ENV_TYPES}
|
307
|
+
ENV_FORMAT_PATTERNS = {env: re.compile(r'\\begin\{' + env + r'\}\{([^}]*)\}') for env in ENV_TYPES}
|
308
|
+
|
309
|
+
def fix_latex_environments(s):
|
310
|
+
"""
|
311
|
+
检测LaTeX中环境(如array)的\begin和\end是否匹配
|
312
|
+
1. 如果缺少\begin标签则在开头添加
|
313
|
+
2. 如果缺少\end标签则在末尾添加
|
314
|
+
"""
|
315
|
+
for env in ENV_TYPES:
|
316
|
+
begin_count = len(ENV_BEGIN_PATTERNS[env].findall(s))
|
317
|
+
end_count = len(ENV_END_PATTERNS[env].findall(s))
|
318
|
+
|
319
|
+
if begin_count != end_count:
|
320
|
+
if end_count > begin_count:
|
321
|
+
format_match = ENV_FORMAT_PATTERNS[env].search(s)
|
322
|
+
default_format = '{c}' if env == 'array' else ''
|
323
|
+
format_str = '{' + format_match.group(1) + '}' if format_match else default_format
|
324
|
+
|
325
|
+
missing_count = end_count - begin_count
|
326
|
+
begin_command = '\\begin{' + env + '}' + format_str + ' '
|
327
|
+
s = begin_command * missing_count + s
|
328
|
+
else:
|
329
|
+
missing_count = begin_count - end_count
|
330
|
+
s = s + (' \\end{' + env + '}') * missing_count
|
331
|
+
|
332
|
+
return s
|
333
|
+
|
334
|
+
|
335
|
+
UP_PATTERN = re.compile(r'\\up([a-zA-Z]+)')
|
336
|
+
COMMANDS_TO_REMOVE_PATTERN = re.compile(
|
337
|
+
r'\\(?:lefteqn|boldmath|ensuremath|centering|textsubscript|sides|textsl|textcent|emph)')
|
338
|
+
REPLACEMENTS_PATTERNS = {
|
339
|
+
re.compile(r'\\underbar'): r'\\underline',
|
340
|
+
re.compile(r'\\Bar'): r'\\hat',
|
341
|
+
re.compile(r'\\Hat'): r'\\hat',
|
342
|
+
re.compile(r'\\Tilde'): r'\\tilde',
|
343
|
+
re.compile(r'\\slash'): r'/',
|
344
|
+
re.compile(r'\\textperthousand'): r'‰',
|
345
|
+
re.compile(r'\\sun'): r'☉'
|
346
|
+
}
|
347
|
+
QQUAD_PATTERN = re.compile(r'\\qquad(?!\s)')
|
348
|
+
|
349
|
+
def latex_rm_whitespace(s: str):
|
350
|
+
"""Remove unnecessary whitespace from LaTeX code."""
|
351
|
+
s = fix_unbalanced_braces(s)
|
352
|
+
s = fix_latex_left_right(s)
|
353
|
+
s = fix_latex_environments(s)
|
354
|
+
|
355
|
+
# 使用预编译的正则表达式
|
356
|
+
s = UP_PATTERN.sub(
|
357
|
+
lambda m: m.group(0) if m.group(1) in ["arrow", "downarrow", "lus", "silon"] else f"\\{m.group(1)}", s
|
358
|
+
)
|
359
|
+
s = COMMANDS_TO_REMOVE_PATTERN.sub('', s)
|
360
|
+
|
361
|
+
# 应用所有替换
|
362
|
+
for pattern, replacement in REPLACEMENTS_PATTERNS.items():
|
363
|
+
s = pattern.sub(replacement, s)
|
364
|
+
|
365
|
+
# 处理LaTeX中的反斜杠和空格
|
366
|
+
s = process_latex(s)
|
367
|
+
|
368
|
+
# \qquad后补空格
|
369
|
+
s = QQUAD_PATTERN.sub(r'\\qquad ', s)
|
370
|
+
|
76
371
|
return s
|
77
372
|
|
78
373
|
|
@@ -55,7 +55,8 @@ class PytorchPaddleOCR(TextSystem):
|
|
55
55
|
self.lang = kwargs.get('lang', 'ch')
|
56
56
|
|
57
57
|
device = get_device()
|
58
|
-
if device == 'cpu' and self.lang
|
58
|
+
if device == 'cpu' and self.lang in ['ch', 'ch_server']:
|
59
|
+
logger.warning("The current device in use is CPU. To ensure the speed of parsing, the language is automatically switched to ch_lite.")
|
59
60
|
self.lang = 'ch_lite'
|
60
61
|
|
61
62
|
if self.lang in latin_lang:
|
@@ -79,7 +80,7 @@ class PytorchPaddleOCR(TextSystem):
|
|
79
80
|
kwargs['rec_char_dict_path'] = os.path.join(root_dir, 'pytorchocr', 'utils', 'resources', 'dict', dict_file)
|
80
81
|
# kwargs['rec_batch_num'] = 8
|
81
82
|
|
82
|
-
kwargs['device'] =
|
83
|
+
kwargs['device'] = device
|
83
84
|
|
84
85
|
default_args = vars(args)
|
85
86
|
default_args.update(kwargs)
|
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/arch_config.yaml
CHANGED
@@ -171,6 +171,31 @@ ch_PP-OCRv4_rec_server_infer:
|
|
171
171
|
nrtr_dim: 384
|
172
172
|
max_text_length: 25
|
173
173
|
|
174
|
+
ch_PP-OCRv4_rec_server_doc_infer:
|
175
|
+
model_type: rec
|
176
|
+
algorithm: SVTR_HGNet
|
177
|
+
Transform:
|
178
|
+
Backbone:
|
179
|
+
name: PPHGNet_small
|
180
|
+
Head:
|
181
|
+
name: MultiHead
|
182
|
+
out_channels_list:
|
183
|
+
CTCLabelDecode: 15631
|
184
|
+
head_list:
|
185
|
+
- CTCHead:
|
186
|
+
Neck:
|
187
|
+
name: svtr
|
188
|
+
dims: 120
|
189
|
+
depth: 2
|
190
|
+
hidden_dims: 120
|
191
|
+
kernel_size: [ 1, 3 ]
|
192
|
+
use_guide: True
|
193
|
+
Head:
|
194
|
+
fc_decay: 0.00001
|
195
|
+
- NRTRHead:
|
196
|
+
nrtr_dim: 384
|
197
|
+
max_text_length: 25
|
198
|
+
|
174
199
|
chinese_cht_PP-OCRv3_rec_infer:
|
175
200
|
model_type: rec
|
176
201
|
algorithm: SVTR
|