mineru 2.5.3__py3-none-any.whl → 2.6.0__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.
Files changed (104) hide show
  1. mineru/backend/pipeline/model_init.py +25 -3
  2. mineru/backend/pipeline/model_json_to_middle_json.py +2 -2
  3. mineru/backend/pipeline/model_list.py +0 -1
  4. mineru/backend/utils.py +24 -0
  5. mineru/backend/vlm/model_output_to_middle_json.py +2 -2
  6. mineru/backend/vlm/{custom_logits_processors.py → utils.py} +36 -2
  7. mineru/backend/vlm/vlm_analyze.py +43 -50
  8. mineru/backend/vlm/vlm_magic_model.py +155 -1
  9. mineru/cli/common.py +26 -23
  10. mineru/cli/fast_api.py +2 -8
  11. mineru/cli/gradio_app.py +104 -13
  12. mineru/cli/models_download.py +1 -0
  13. mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py +152 -0
  14. mineru/model/mfr/pp_formulanet_plus_m/processors.py +657 -0
  15. mineru/model/mfr/unimernet/unimernet_hf/modeling_unimernet.py +1 -326
  16. mineru/model/mfr/utils.py +338 -0
  17. mineru/model/ocr/paddleocr2pytorch/pytorch_paddle.py +103 -16
  18. mineru/model/table/rec/unet_table/main.py +1 -1
  19. mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/data/imaug/operators.py +5 -5
  20. mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/backbones/__init__.py +2 -1
  21. mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/backbones/rec_lcnetv3.py +7 -7
  22. mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/backbones/rec_pphgnetv2.py +2 -2
  23. mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/heads/__init__.py +2 -0
  24. mineru/model/utils/pytorchocr/modeling/heads/rec_ppformulanet_head.py +1383 -0
  25. mineru/model/utils/pytorchocr/modeling/heads/rec_unimernet_head.py +2631 -0
  26. mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/postprocess/rec_postprocess.py +25 -28
  27. mineru/model/utils/pytorchocr/utils/__init__.py +0 -0
  28. mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/arch_config.yaml +130 -0
  29. mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_arabic_dict.txt +747 -0
  30. mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_cyrillic_dict.txt +850 -0
  31. mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_devanagari_dict.txt +568 -0
  32. mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_ta_dict.txt +513 -0
  33. mineru/model/utils/pytorchocr/utils/resources/dict/ppocrv5_te_dict.txt +540 -0
  34. mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/models_config.yml +15 -15
  35. mineru/model/utils/pytorchocr/utils/resources/pp_formulanet_arch_config.yaml +24 -0
  36. mineru/model/utils/tools/infer/__init__.py +1 -0
  37. mineru/model/{ocr/paddleocr2pytorch → utils}/tools/infer/predict_det.py +6 -3
  38. mineru/model/{ocr/paddleocr2pytorch → utils}/tools/infer/predict_rec.py +16 -25
  39. mineru/model/vlm_vllm_model/server.py +4 -1
  40. mineru/resources/header.html +2 -2
  41. mineru/utils/enum_class.py +1 -0
  42. mineru/utils/guess_suffix_or_lang.py +9 -1
  43. mineru/utils/llm_aided.py +4 -2
  44. mineru/utils/ocr_utils.py +16 -0
  45. mineru/utils/table_merge.py +102 -13
  46. mineru/version.py +1 -1
  47. {mineru-2.5.3.dist-info → mineru-2.6.0.dist-info}/METADATA +33 -6
  48. mineru-2.6.0.dist-info/RECORD +195 -0
  49. mineru-2.5.3.dist-info/RECORD +0 -181
  50. /mineru/model/{ocr/paddleocr2pytorch/pytorchocr → mfr/pp_formulanet_plus_m}/__init__.py +0 -0
  51. /mineru/model/{ocr/paddleocr2pytorch/tools/infer → utils}/__init__.py +0 -0
  52. /mineru/model/{ocr/paddleocr2pytorch/pytorchocr/modeling → utils/pytorchocr}/__init__.py +0 -0
  53. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/base_ocr_v20.py +0 -0
  54. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/data/__init__.py +0 -0
  55. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/data/imaug/__init__.py +0 -0
  56. /mineru/model/{ocr/paddleocr2pytorch/pytorchocr/utils → utils/pytorchocr/modeling}/__init__.py +0 -0
  57. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/architectures/__init__.py +0 -0
  58. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/architectures/base_model.py +0 -0
  59. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/backbones/det_mobilenet_v3.py +0 -0
  60. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/backbones/rec_donut_swin.py +0 -0
  61. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/backbones/rec_hgnet.py +0 -0
  62. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/backbones/rec_mobilenet_v3.py +0 -0
  63. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/backbones/rec_mv1_enhance.py +0 -0
  64. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/backbones/rec_svtrnet.py +0 -0
  65. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/common.py +0 -0
  66. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/heads/cls_head.py +0 -0
  67. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/heads/det_db_head.py +0 -0
  68. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/heads/rec_ctc_head.py +0 -0
  69. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/heads/rec_multi_head.py +0 -0
  70. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/necks/__init__.py +0 -0
  71. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/necks/db_fpn.py +0 -0
  72. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/necks/intracl.py +0 -0
  73. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/modeling/necks/rnn.py +0 -0
  74. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/postprocess/__init__.py +0 -0
  75. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/postprocess/cls_postprocess.py +0 -0
  76. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/postprocess/db_postprocess.py +0 -0
  77. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/arabic_dict.txt +0 -0
  78. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/chinese_cht_dict.txt +0 -0
  79. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/cyrillic_dict.txt +0 -0
  80. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/devanagari_dict.txt +0 -0
  81. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/en_dict.txt +0 -0
  82. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/japan_dict.txt +0 -0
  83. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/ka_dict.txt +0 -0
  84. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/korean_dict.txt +0 -0
  85. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/latin_dict.txt +0 -0
  86. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/ppocr_keys_v1.txt +0 -0
  87. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/ppocrv4_doc_dict.txt +0 -0
  88. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/ppocrv5_dict.txt +0 -0
  89. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/ppocrv5_el_dict.txt +0 -0
  90. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/ppocrv5_en_dict.txt +0 -0
  91. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/ppocrv5_eslav_dict.txt +0 -0
  92. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/ppocrv5_korean_dict.txt +0 -0
  93. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/ppocrv5_latin_dict.txt +0 -0
  94. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/ppocrv5_th_dict.txt +0 -0
  95. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/ta_dict.txt +0 -0
  96. /mineru/model/{ocr/paddleocr2pytorch → utils}/pytorchocr/utils/resources/dict/te_dict.txt +0 -0
  97. /mineru/model/{ocr/paddleocr2pytorch → utils}/tools/__init__.py +0 -0
  98. /mineru/model/{ocr/paddleocr2pytorch → utils}/tools/infer/predict_cls.py +0 -0
  99. /mineru/model/{ocr/paddleocr2pytorch → utils}/tools/infer/predict_system.py +0 -0
  100. /mineru/model/{ocr/paddleocr2pytorch → utils}/tools/infer/pytorchocr_utility.py +0 -0
  101. {mineru-2.5.3.dist-info → mineru-2.6.0.dist-info}/WHEEL +0 -0
  102. {mineru-2.5.3.dist-info → mineru-2.6.0.dist-info}/entry_points.txt +0 -0
  103. {mineru-2.5.3.dist-info → mineru-2.6.0.dist-info}/licenses/LICENSE.md +0 -0
  104. {mineru-2.5.3.dist-info → mineru-2.6.0.dist-info}/top_level.txt +0 -0
@@ -1,5 +1,4 @@
1
1
  import os
2
- import re
3
2
  import warnings
4
3
  from typing import Optional
5
4
 
@@ -13,6 +12,7 @@ from transformers.models.vision_encoder_decoder.modeling_vision_encoder_decoder
13
12
 
14
13
  from .unimer_swin import UnimerSwinConfig, UnimerSwinModel, UnimerSwinImageProcessor
15
14
  from .unimer_mbart import UnimerMBartConfig, UnimerMBartForCausalLM
15
+ from ...utils import latex_rm_whitespace
16
16
 
17
17
  AutoConfig.register(UnimerSwinConfig.model_type, UnimerSwinConfig)
18
18
  AutoConfig.register(UnimerMBartConfig.model_type, UnimerMBartConfig)
@@ -57,331 +57,6 @@ class TokenizerWrapper:
57
57
  del toks[b][i]
58
58
  return toks
59
59
 
60
-
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):
108
- """
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|protect|null)')
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
- re.compile(r'\\textunderscore'): r'\\_',
347
- re.compile(r'\\fint'): r'⨏',
348
- re.compile(r'\\up '): r'\\ ',
349
- re.compile(r'\\vline = '): r'\\models ',
350
- re.compile(r'\\vDash '): r'\\models ',
351
- re.compile(r'\\sq \\sqcup '): r'\\square ',
352
- re.compile(r'\\copyright'): r'©',
353
- }
354
- QQUAD_PATTERN = re.compile(r'\\qquad(?!\s)')
355
-
356
- def latex_rm_whitespace(s: str):
357
- """Remove unnecessary whitespace from LaTeX code."""
358
- s = fix_unbalanced_braces(s)
359
- s = fix_latex_left_right(s)
360
- s = fix_latex_environments(s)
361
-
362
- # 使用预编译的正则表达式
363
- s = UP_PATTERN.sub(
364
- lambda m: m.group(0) if m.group(1) in ["arrow", "downarrow", "lus", "silon"] else f"\\{m.group(1)}", s
365
- )
366
- s = COMMANDS_TO_REMOVE_PATTERN.sub('', s)
367
-
368
- # 应用所有替换
369
- for pattern, replacement in REPLACEMENTS_PATTERNS.items():
370
- s = pattern.sub(replacement, s)
371
-
372
- # 处理LaTeX中的反斜杠和空格
373
- s = process_latex(s)
374
-
375
- # \qquad后补空格
376
- s = QQUAD_PATTERN.sub(r'\\qquad ', s)
377
-
378
- # 如果字符串以反斜杠结尾,去掉最后的反斜杠
379
- while s.endswith('\\'):
380
- s = s[:-1]
381
-
382
- return s
383
-
384
-
385
60
  class UnimernetModel(VisionEncoderDecoderModel):
386
61
  def __init__(
387
62
  self,
@@ -0,0 +1,338 @@
1
+ import re
2
+
3
+ LEFT_PATTERN = re.compile(r'(\\left)(\S*)')
4
+ RIGHT_PATTERN = re.compile(r'(\\right)(\S*)')
5
+ LEFT_COUNT_PATTERN = re.compile(r'\\left(?![a-zA-Z])')
6
+ RIGHT_COUNT_PATTERN = re.compile(r'\\right(?![a-zA-Z])')
7
+ LEFT_RIGHT_REMOVE_PATTERN = re.compile(r'\\left\.?|\\right\.?')
8
+
9
+ def fix_latex_left_right(s, fix_delimiter=True):
10
+ """
11
+ 修复LaTeX中的\\left和\\right命令
12
+ 1. 确保它们后面跟有效分隔符
13
+ 2. 平衡\\left和\\right的数量
14
+ """
15
+ # 白名单分隔符
16
+ valid_delims_list = [r'(', r')', r'[', r']', r'{', r'}', r'/', r'|',
17
+ r'\{', r'\}', r'\lceil', r'\rceil', r'\lfloor',
18
+ r'\rfloor', r'\backslash', r'\uparrow', r'\downarrow',
19
+ r'\Uparrow', r'\Downarrow', r'\|', r'\.']
20
+
21
+ # 为\left后缺失有效分隔符的情况添加点
22
+ def fix_delim(match, is_left=True):
23
+ cmd = match.group(1) # \left 或 \right
24
+ rest = match.group(2) if len(match.groups()) > 1 else ""
25
+ if not rest or rest not in valid_delims_list:
26
+ return cmd + "."
27
+ return match.group(0)
28
+
29
+ # 使用更精确的模式匹配\left和\right命令
30
+ # 确保它们是独立的命令,不是其他命令的一部分
31
+ # 使用预编译正则和统一回调函数
32
+ if fix_delimiter:
33
+ s = LEFT_PATTERN.sub(lambda m: fix_delim(m, True), s)
34
+ s = RIGHT_PATTERN.sub(lambda m: fix_delim(m, False), s)
35
+
36
+ # 更精确地计算\left和\right的数量
37
+ left_count = len(LEFT_COUNT_PATTERN.findall(s)) # 不匹配\lefteqn等
38
+ right_count = len(RIGHT_COUNT_PATTERN.findall(s)) # 不匹配\rightarrow等
39
+
40
+ if left_count == right_count:
41
+ # 如果数量相等,检查是否在同一组
42
+ return fix_left_right_pairs(s)
43
+ # return s
44
+ else:
45
+ # 如果数量不等,移除所有\left和\right
46
+ # logger.debug(f"latex:{s}")
47
+ # logger.warning(f"left_count: {left_count}, right_count: {right_count}")
48
+ return LEFT_RIGHT_REMOVE_PATTERN.sub('', s)
49
+
50
+
51
+ def fix_left_right_pairs(latex_formula):
52
+ """
53
+ 检测并修复LaTeX公式中\\left和\\right不在同一组的情况
54
+
55
+ Args:
56
+ latex_formula (str): 输入的LaTeX公式
57
+
58
+ Returns:
59
+ str: 修复后的LaTeX公式
60
+ """
61
+ # 用于跟踪花括号嵌套层级
62
+ brace_stack = []
63
+ # 用于存储\left信息: (位置, 深度, 分隔符)
64
+ left_stack = []
65
+ # 存储需要调整的\right信息: (开始位置, 结束位置, 目标位置)
66
+ adjustments = []
67
+
68
+ i = 0
69
+ while i < len(latex_formula):
70
+ # 检查是否是转义字符
71
+ if i > 0 and latex_formula[i - 1] == '\\':
72
+ backslash_count = 0
73
+ j = i - 1
74
+ while j >= 0 and latex_formula[j] == '\\':
75
+ backslash_count += 1
76
+ j -= 1
77
+
78
+ if backslash_count % 2 == 1:
79
+ i += 1
80
+ continue
81
+
82
+ # 检测\left命令
83
+ if i + 5 < len(latex_formula) and latex_formula[i:i + 5] == "\\left" and i + 5 < len(latex_formula):
84
+ delimiter = latex_formula[i + 5]
85
+ left_stack.append((i, len(brace_stack), delimiter))
86
+ i += 6 # 跳过\left和分隔符
87
+ continue
88
+
89
+ # 检测\right命令
90
+ elif i + 6 < len(latex_formula) and latex_formula[i:i + 6] == "\\right" and i + 6 < len(latex_formula):
91
+ delimiter = latex_formula[i + 6]
92
+
93
+ if left_stack:
94
+ left_pos, left_depth, left_delim = left_stack.pop()
95
+
96
+ # 如果\left和\right不在同一花括号深度
97
+ if left_depth != len(brace_stack):
98
+ # 找到\left所在花括号组的结束位置
99
+ target_pos = find_group_end(latex_formula, left_pos, left_depth)
100
+ if target_pos != -1:
101
+ # 记录需要移动的\right
102
+ adjustments.append((i, i + 7, target_pos))
103
+
104
+ i += 7 # 跳过\right和分隔符
105
+ continue
106
+
107
+ # 处理花括号
108
+ if latex_formula[i] == '{':
109
+ brace_stack.append(i)
110
+ elif latex_formula[i] == '}':
111
+ if brace_stack:
112
+ brace_stack.pop()
113
+
114
+ i += 1
115
+
116
+ # 应用调整,从后向前处理以避免索引变化
117
+ if not adjustments:
118
+ return latex_formula
119
+
120
+ result = list(latex_formula)
121
+ adjustments.sort(reverse=True, key=lambda x: x[0])
122
+
123
+ for start, end, target in adjustments:
124
+ # 提取\right部分
125
+ right_part = result[start:end]
126
+ # 从原位置删除
127
+ del result[start:end]
128
+ # 在目标位置插入
129
+ result.insert(target, ''.join(right_part))
130
+
131
+ return ''.join(result)
132
+
133
+
134
+ def find_group_end(text, pos, depth):
135
+ """查找特定深度的花括号组的结束位置"""
136
+ current_depth = depth
137
+ i = pos
138
+
139
+ while i < len(text):
140
+ if text[i] == '{' and (i == 0 or not is_escaped(text, i)):
141
+ current_depth += 1
142
+ elif text[i] == '}' and (i == 0 or not is_escaped(text, i)):
143
+ current_depth -= 1
144
+ if current_depth < depth:
145
+ return i
146
+ i += 1
147
+
148
+ return -1 # 未找到对应结束位置
149
+
150
+
151
+ def is_escaped(text, pos):
152
+ """检查字符是否被转义"""
153
+ backslash_count = 0
154
+ j = pos - 1
155
+ while j >= 0 and text[j] == '\\':
156
+ backslash_count += 1
157
+ j -= 1
158
+
159
+ return backslash_count % 2 == 1
160
+
161
+
162
+ def fix_unbalanced_braces(latex_formula):
163
+ """
164
+ 检测LaTeX公式中的花括号是否闭合,并删除无法配对的花括号
165
+
166
+ Args:
167
+ latex_formula (str): 输入的LaTeX公式
168
+
169
+ Returns:
170
+ str: 删除无法配对的花括号后的LaTeX公式
171
+ """
172
+ stack = [] # 存储左括号的索引
173
+ unmatched = set() # 存储不匹配括号的索引
174
+ i = 0
175
+
176
+ while i < len(latex_formula):
177
+ # 检查是否是转义的花括号
178
+ if latex_formula[i] in ['{', '}']:
179
+ # 计算前面连续的反斜杠数量
180
+ backslash_count = 0
181
+ j = i - 1
182
+ while j >= 0 and latex_formula[j] == '\\':
183
+ backslash_count += 1
184
+ j -= 1
185
+
186
+ # 如果前面有奇数个反斜杠,则该花括号是转义的,不参与匹配
187
+ if backslash_count % 2 == 1:
188
+ i += 1
189
+ continue
190
+
191
+ # 否则,该花括号参与匹配
192
+ if latex_formula[i] == '{':
193
+ stack.append(i)
194
+ else: # latex_formula[i] == '}'
195
+ if stack: # 有对应的左括号
196
+ stack.pop()
197
+ else: # 没有对应的左括号
198
+ unmatched.add(i)
199
+
200
+ i += 1
201
+
202
+ # 所有未匹配的左括号
203
+ unmatched.update(stack)
204
+
205
+ # 构建新字符串,删除不匹配的括号
206
+ return ''.join(char for i, char in enumerate(latex_formula) if i not in unmatched)
207
+
208
+
209
+ def process_latex(input_string):
210
+ """
211
+ 处理LaTeX公式中的反斜杠:
212
+ 1. 如果\后跟特殊字符(#$%&~_^\\{})或空格,保持不变
213
+ 2. 如果\后跟两个小写字母,保持不变
214
+ 3. 其他情况,在\后添加空格
215
+
216
+ Args:
217
+ input_string (str): 输入的LaTeX公式
218
+
219
+ Returns:
220
+ str: 处理后的LaTeX公式
221
+ """
222
+
223
+ def replace_func(match):
224
+ # 获取\后面的字符
225
+ next_char = match.group(1)
226
+
227
+ # 如果是特殊字符或空格,保持不变
228
+ if next_char in "#$%&~_^|\\{} \t\n\r\v\f":
229
+ return match.group(0)
230
+
231
+ # 如果是字母,检查下一个字符
232
+ if 'a' <= next_char <= 'z' or 'A' <= next_char <= 'Z':
233
+ pos = match.start() + 2 # \x后的位置
234
+ if pos < len(input_string) and ('a' <= input_string[pos] <= 'z' or 'A' <= input_string[pos] <= 'Z'):
235
+ # 下一个字符也是字母,保持不变
236
+ return match.group(0)
237
+
238
+ # 其他情况,在\后添加空格
239
+ return '\\' + ' ' + next_char
240
+
241
+ # 匹配\后面跟一个字符的情况
242
+ pattern = r'\\(.)'
243
+
244
+ return re.sub(pattern, replace_func, input_string)
245
+
246
+ # 常见的在KaTeX/MathJax中可用的数学环境
247
+ ENV_TYPES = ['array', 'matrix', 'pmatrix', 'bmatrix', 'vmatrix',
248
+ 'Bmatrix', 'Vmatrix', 'cases', 'aligned', 'gathered', 'align', 'align*']
249
+ ENV_BEGIN_PATTERNS = {env: re.compile(r'\\begin\{' + env + r'\}') for env in ENV_TYPES}
250
+ ENV_END_PATTERNS = {env: re.compile(r'\\end\{' + env + r'\}') for env in ENV_TYPES}
251
+ ENV_FORMAT_PATTERNS = {env: re.compile(r'\\begin\{' + env + r'\}\{([^}]*)\}') for env in ENV_TYPES}
252
+
253
+ def fix_latex_environments(s):
254
+ """
255
+ 检测LaTeX中环境(如array)的\\begin和\\end是否匹配
256
+ 1. 如果缺少\\begin标签则在开头添加
257
+ 2. 如果缺少\\end标签则在末尾添加
258
+ """
259
+ for env in ENV_TYPES:
260
+ begin_count = len(ENV_BEGIN_PATTERNS[env].findall(s))
261
+ end_count = len(ENV_END_PATTERNS[env].findall(s))
262
+
263
+ if begin_count != end_count:
264
+ if end_count > begin_count:
265
+ format_match = ENV_FORMAT_PATTERNS[env].search(s)
266
+ default_format = '{c}' if env == 'array' else ''
267
+ format_str = '{' + format_match.group(1) + '}' if format_match else default_format
268
+
269
+ missing_count = end_count - begin_count
270
+ begin_command = '\\begin{' + env + '}' + format_str + ' '
271
+ s = begin_command * missing_count + s
272
+ else:
273
+ missing_count = begin_count - end_count
274
+ s = s + (' \\end{' + env + '}') * missing_count
275
+
276
+ return s
277
+
278
+
279
+ REPLACEMENTS_PATTERNS = {
280
+ re.compile(r'\\underbar'): r'\\underline',
281
+ re.compile(r'\\Bar'): r'\\hat',
282
+ re.compile(r'\\Hat'): r'\\hat',
283
+ re.compile(r'\\Tilde'): r'\\tilde',
284
+ re.compile(r'\\slash'): r'/',
285
+ re.compile(r'\\textperthousand'): r'‰',
286
+ re.compile(r'\\sun'): r'☉',
287
+ re.compile(r'\\textunderscore'): r'\\_',
288
+ re.compile(r'\\fint'): r'⨏',
289
+ re.compile(r'\\up '): r'\\ ',
290
+ re.compile(r'\\vline = '): r'\\models ',
291
+ re.compile(r'\\vDash '): r'\\models ',
292
+ re.compile(r'\\sq \\sqcup '): r'\\square ',
293
+ re.compile(r'\\copyright'): r'©',
294
+ }
295
+ QQUAD_PATTERN = re.compile(r'\\qquad(?!\s)')
296
+
297
+
298
+ def remove_up_commands(s: str):
299
+ """Remove unnecessary up commands from LaTeX code."""
300
+ UP_PATTERN = re.compile(r'\\up([a-zA-Z]+)')
301
+ s = UP_PATTERN.sub(
302
+ lambda m: m.group(0) if m.group(1) in ["arrow", "downarrow", "lus", "silon"] else f"\\{m.group(1)}", s
303
+ )
304
+ return s
305
+
306
+
307
+ def remove_unsupported_commands(s: str):
308
+ """Remove unsupported LaTeX commands."""
309
+ COMMANDS_TO_REMOVE_PATTERN = re.compile(
310
+ r'\\(?:lefteqn|boldmath|ensuremath|centering|textsubscript|sides|textsl|textcent|emph|protect|null)')
311
+ s = COMMANDS_TO_REMOVE_PATTERN.sub('', s)
312
+ return s
313
+
314
+
315
+ def latex_rm_whitespace(s: str):
316
+ """Remove unnecessary whitespace from LaTeX code."""
317
+ s = fix_unbalanced_braces(s)
318
+ s = fix_latex_left_right(s)
319
+ s = fix_latex_environments(s)
320
+
321
+ s = remove_up_commands(s)
322
+ s = remove_unsupported_commands(s)
323
+
324
+ # 应用所有替换
325
+ for pattern, replacement in REPLACEMENTS_PATTERNS.items():
326
+ s = pattern.sub(replacement, s)
327
+
328
+ # 处理LaTeX中的反斜杠和空格
329
+ s = process_latex(s)
330
+
331
+ # \qquad后补空格
332
+ s = QQUAD_PATTERN.sub(r'\\qquad ', s)
333
+
334
+ # 如果字符串以反斜杠结尾,去掉最后的反斜杠
335
+ while s.endswith('\\'):
336
+ s = s[:-1]
337
+
338
+ return s