doc-page-extractor 0.2.0__py3-none-any.whl → 1.0.2__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.
- doc_page_extractor/__init__.py +5 -15
- doc_page_extractor/check_env.py +40 -0
- doc_page_extractor/extractor.py +88 -215
- doc_page_extractor/model.py +97 -0
- doc_page_extractor/parser.py +51 -0
- doc_page_extractor/plot.py +52 -79
- doc_page_extractor/redacter.py +111 -0
- doc_page_extractor-1.0.2.dist-info/METADATA +120 -0
- doc_page_extractor-1.0.2.dist-info/RECORD +11 -0
- {doc_page_extractor-0.2.0.dist-info → doc_page_extractor-1.0.2.dist-info}/WHEEL +1 -2
- doc_page_extractor-1.0.2.dist-info/licenses/LICENSE +21 -0
- doc_page_extractor/clipper.py +0 -119
- doc_page_extractor/downloader.py +0 -16
- doc_page_extractor/latex.py +0 -31
- doc_page_extractor/layout_order.py +0 -237
- doc_page_extractor/layoutreader.py +0 -126
- doc_page_extractor/models.py +0 -92
- doc_page_extractor/ocr.py +0 -200
- doc_page_extractor/ocr_corrector.py +0 -126
- doc_page_extractor/onnxocr/__init__.py +0 -1
- doc_page_extractor/onnxocr/cls_postprocess.py +0 -26
- doc_page_extractor/onnxocr/db_postprocess.py +0 -246
- doc_page_extractor/onnxocr/imaug.py +0 -32
- doc_page_extractor/onnxocr/operators.py +0 -187
- doc_page_extractor/onnxocr/predict_base.py +0 -57
- doc_page_extractor/onnxocr/predict_cls.py +0 -109
- doc_page_extractor/onnxocr/predict_det.py +0 -139
- doc_page_extractor/onnxocr/predict_rec.py +0 -344
- doc_page_extractor/onnxocr/predict_system.py +0 -97
- doc_page_extractor/onnxocr/rec_postprocess.py +0 -896
- doc_page_extractor/onnxocr/utils.py +0 -71
- doc_page_extractor/overlap.py +0 -167
- doc_page_extractor/raw_optimizer.py +0 -104
- doc_page_extractor/rectangle.py +0 -72
- doc_page_extractor/rotation.py +0 -158
- doc_page_extractor/struct_eqtable/__init__.py +0 -49
- doc_page_extractor/struct_eqtable/internvl/__init__.py +0 -2
- doc_page_extractor/struct_eqtable/internvl/conversation.py +0 -394
- doc_page_extractor/struct_eqtable/internvl/internvl.py +0 -198
- doc_page_extractor/struct_eqtable/internvl/internvl_lmdeploy.py +0 -81
- doc_page_extractor/struct_eqtable/pix2s/__init__.py +0 -3
- doc_page_extractor/struct_eqtable/pix2s/pix2s.py +0 -76
- doc_page_extractor/struct_eqtable/pix2s/pix2s_trt.py +0 -1047
- doc_page_extractor/table.py +0 -70
- doc_page_extractor/types.py +0 -91
- doc_page_extractor/utils.py +0 -32
- doc_page_extractor-0.2.0.dist-info/METADATA +0 -85
- doc_page_extractor-0.2.0.dist-info/RECORD +0 -45
- doc_page_extractor-0.2.0.dist-info/licenses/LICENSE +0 -661
- doc_page_extractor-0.2.0.dist-info/top_level.txt +0 -2
- tests/__init__.py +0 -0
- tests/test_history_bus.py +0 -55
|
@@ -1,394 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Conversation prompt templates.
|
|
3
|
-
|
|
4
|
-
We kindly request that you import fastchat instead of copying this file if you wish to use it.
|
|
5
|
-
If you have changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates.
|
|
6
|
-
"""
|
|
7
|
-
|
|
8
|
-
import dataclasses
|
|
9
|
-
from enum import IntEnum, auto
|
|
10
|
-
from typing import Any, Dict, List, Tuple, Union
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
class SeparatorStyle(IntEnum):
|
|
14
|
-
"""Separator styles."""
|
|
15
|
-
|
|
16
|
-
ADD_COLON_SINGLE = auto()
|
|
17
|
-
ADD_COLON_TWO = auto()
|
|
18
|
-
ADD_COLON_SPACE_SINGLE = auto()
|
|
19
|
-
NO_COLON_SINGLE = auto()
|
|
20
|
-
NO_COLON_TWO = auto()
|
|
21
|
-
ADD_NEW_LINE_SINGLE = auto()
|
|
22
|
-
LLAMA2 = auto()
|
|
23
|
-
CHATGLM = auto()
|
|
24
|
-
CHATML = auto()
|
|
25
|
-
CHATINTERN = auto()
|
|
26
|
-
DOLLY = auto()
|
|
27
|
-
RWKV = auto()
|
|
28
|
-
PHOENIX = auto()
|
|
29
|
-
ROBIN = auto()
|
|
30
|
-
FALCON_CHAT = auto()
|
|
31
|
-
CHATGLM3 = auto()
|
|
32
|
-
INTERNVL_ZH = auto()
|
|
33
|
-
MPT = auto()
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
@dataclasses.dataclass
|
|
37
|
-
class Conversation:
|
|
38
|
-
"""A class that manages prompt templates and keeps all conversation history."""
|
|
39
|
-
|
|
40
|
-
# The name of this template
|
|
41
|
-
name: str
|
|
42
|
-
# The template of the system prompt
|
|
43
|
-
system_template: str = '{system_message}'
|
|
44
|
-
# The system message
|
|
45
|
-
system_message: str = ''
|
|
46
|
-
# The names of two roles
|
|
47
|
-
roles: Tuple[str] = ('USER', 'ASSISTANT')
|
|
48
|
-
# All messages. Each item is (role, message).
|
|
49
|
-
messages: List[List[str]] = ()
|
|
50
|
-
# The number of few shot examples
|
|
51
|
-
offset: int = 0
|
|
52
|
-
# The separator style and configurations
|
|
53
|
-
sep_style: SeparatorStyle = SeparatorStyle.ADD_COLON_SINGLE
|
|
54
|
-
sep: str = '\n'
|
|
55
|
-
sep2: str = None
|
|
56
|
-
# Stop criteria (the default one is EOS token)
|
|
57
|
-
stop_str: Union[str, List[str]] = None
|
|
58
|
-
# Stops generation if meeting any token in this list
|
|
59
|
-
stop_token_ids: List[int] = None
|
|
60
|
-
|
|
61
|
-
def get_prompt(self) -> str:
|
|
62
|
-
"""Get the prompt for generation."""
|
|
63
|
-
system_prompt = self.system_template.format(system_message=self.system_message)
|
|
64
|
-
if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE:
|
|
65
|
-
ret = system_prompt + self.sep
|
|
66
|
-
for role, message in self.messages:
|
|
67
|
-
if message:
|
|
68
|
-
ret += role + ': ' + message + self.sep
|
|
69
|
-
else:
|
|
70
|
-
ret += role + ':'
|
|
71
|
-
return ret
|
|
72
|
-
elif self.sep_style == SeparatorStyle.ADD_COLON_TWO:
|
|
73
|
-
seps = [self.sep, self.sep2]
|
|
74
|
-
ret = system_prompt + seps[0]
|
|
75
|
-
for i, (role, message) in enumerate(self.messages):
|
|
76
|
-
if message:
|
|
77
|
-
ret += role + ': ' + message + seps[i % 2]
|
|
78
|
-
else:
|
|
79
|
-
ret += role + ':'
|
|
80
|
-
return ret
|
|
81
|
-
elif self.sep_style == SeparatorStyle.ADD_COLON_SPACE_SINGLE:
|
|
82
|
-
ret = system_prompt + self.sep
|
|
83
|
-
for role, message in self.messages:
|
|
84
|
-
if message:
|
|
85
|
-
ret += role + ': ' + message + self.sep
|
|
86
|
-
else:
|
|
87
|
-
ret += role + ': ' # must be end with a space
|
|
88
|
-
return ret
|
|
89
|
-
elif self.sep_style == SeparatorStyle.ADD_NEW_LINE_SINGLE:
|
|
90
|
-
ret = '' if system_prompt == '' else system_prompt + self.sep
|
|
91
|
-
for role, message in self.messages:
|
|
92
|
-
if message:
|
|
93
|
-
ret += role + '\n' + message + self.sep
|
|
94
|
-
else:
|
|
95
|
-
ret += role + '\n'
|
|
96
|
-
return ret
|
|
97
|
-
elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE:
|
|
98
|
-
ret = system_prompt
|
|
99
|
-
for role, message in self.messages:
|
|
100
|
-
if message:
|
|
101
|
-
ret += role + message + self.sep
|
|
102
|
-
else:
|
|
103
|
-
ret += role
|
|
104
|
-
return ret
|
|
105
|
-
elif self.sep_style == SeparatorStyle.NO_COLON_TWO:
|
|
106
|
-
seps = [self.sep, self.sep2]
|
|
107
|
-
ret = system_prompt
|
|
108
|
-
for i, (role, message) in enumerate(self.messages):
|
|
109
|
-
if message:
|
|
110
|
-
ret += role + message + seps[i % 2]
|
|
111
|
-
else:
|
|
112
|
-
ret += role
|
|
113
|
-
return ret
|
|
114
|
-
elif self.sep_style == SeparatorStyle.RWKV:
|
|
115
|
-
ret = system_prompt
|
|
116
|
-
for i, (role, message) in enumerate(self.messages):
|
|
117
|
-
if message:
|
|
118
|
-
ret += (
|
|
119
|
-
role
|
|
120
|
-
+ ': '
|
|
121
|
-
+ message.replace('\r\n', '\n').replace('\n\n', '\n')
|
|
122
|
-
)
|
|
123
|
-
ret += '\n\n'
|
|
124
|
-
else:
|
|
125
|
-
ret += role + ':'
|
|
126
|
-
return ret
|
|
127
|
-
elif self.sep_style == SeparatorStyle.LLAMA2:
|
|
128
|
-
seps = [self.sep, self.sep2]
|
|
129
|
-
if self.system_message:
|
|
130
|
-
ret = system_prompt
|
|
131
|
-
else:
|
|
132
|
-
ret = '[INST] '
|
|
133
|
-
for i, (role, message) in enumerate(self.messages):
|
|
134
|
-
tag = self.roles[i % 2]
|
|
135
|
-
if message:
|
|
136
|
-
if i == 0:
|
|
137
|
-
ret += message + ' '
|
|
138
|
-
else:
|
|
139
|
-
ret += tag + ' ' + message + seps[i % 2]
|
|
140
|
-
else:
|
|
141
|
-
ret += tag
|
|
142
|
-
return ret
|
|
143
|
-
elif self.sep_style == SeparatorStyle.CHATGLM:
|
|
144
|
-
# source: https://huggingface.co/THUDM/chatglm-6b/blob/1d240ba371910e9282298d4592532d7f0f3e9f3e/modeling_chatglm.py#L1302-L1308
|
|
145
|
-
# source2: https://huggingface.co/THUDM/chatglm2-6b/blob/e186c891cf64310ac66ef10a87e6635fa6c2a579/modeling_chatglm.py#L926
|
|
146
|
-
round_add_n = 1 if self.name == 'chatglm2' else 0
|
|
147
|
-
if system_prompt:
|
|
148
|
-
ret = system_prompt + self.sep
|
|
149
|
-
else:
|
|
150
|
-
ret = ''
|
|
151
|
-
|
|
152
|
-
for i, (role, message) in enumerate(self.messages):
|
|
153
|
-
if i % 2 == 0:
|
|
154
|
-
ret += f'[Round {i//2 + round_add_n}]{self.sep}'
|
|
155
|
-
|
|
156
|
-
if message:
|
|
157
|
-
ret += f'{role}:{message}{self.sep}'
|
|
158
|
-
else:
|
|
159
|
-
ret += f'{role}:'
|
|
160
|
-
return ret
|
|
161
|
-
elif self.sep_style == SeparatorStyle.CHATML:
|
|
162
|
-
ret = '' if system_prompt == '' else system_prompt + self.sep + '\n'
|
|
163
|
-
for role, message in self.messages:
|
|
164
|
-
if message:
|
|
165
|
-
ret += role + '\n' + message + self.sep + '\n'
|
|
166
|
-
else:
|
|
167
|
-
ret += role + '\n'
|
|
168
|
-
return ret
|
|
169
|
-
elif self.sep_style == SeparatorStyle.CHATGLM3:
|
|
170
|
-
ret = ''
|
|
171
|
-
if self.system_message:
|
|
172
|
-
ret += system_prompt
|
|
173
|
-
for role, message in self.messages:
|
|
174
|
-
if message:
|
|
175
|
-
ret += role + '\n' + ' ' + message
|
|
176
|
-
else:
|
|
177
|
-
ret += role
|
|
178
|
-
return ret
|
|
179
|
-
elif self.sep_style == SeparatorStyle.CHATINTERN:
|
|
180
|
-
# source: https://huggingface.co/internlm/internlm-chat-7b-8k/blob/bd546fa984b4b0b86958f56bf37f94aa75ab8831/modeling_internlm.py#L771
|
|
181
|
-
seps = [self.sep, self.sep2]
|
|
182
|
-
ret = system_prompt
|
|
183
|
-
for i, (role, message) in enumerate(self.messages):
|
|
184
|
-
# if i % 2 == 0:
|
|
185
|
-
# ret += "<s>"
|
|
186
|
-
if message:
|
|
187
|
-
ret += role + ':' + message + seps[i % 2] + '\n'
|
|
188
|
-
else:
|
|
189
|
-
ret += role + ':'
|
|
190
|
-
return ret
|
|
191
|
-
elif self.sep_style == SeparatorStyle.DOLLY:
|
|
192
|
-
seps = [self.sep, self.sep2]
|
|
193
|
-
ret = system_prompt
|
|
194
|
-
for i, (role, message) in enumerate(self.messages):
|
|
195
|
-
if message:
|
|
196
|
-
ret += role + ':\n' + message + seps[i % 2]
|
|
197
|
-
if i % 2 == 1:
|
|
198
|
-
ret += '\n\n'
|
|
199
|
-
else:
|
|
200
|
-
ret += role + ':\n'
|
|
201
|
-
return ret
|
|
202
|
-
elif self.sep_style == SeparatorStyle.PHOENIX:
|
|
203
|
-
ret = system_prompt
|
|
204
|
-
for role, message in self.messages:
|
|
205
|
-
if message:
|
|
206
|
-
ret += role + ': ' + '<s>' + message + '</s>'
|
|
207
|
-
else:
|
|
208
|
-
ret += role + ': ' + '<s>'
|
|
209
|
-
return ret
|
|
210
|
-
elif self.sep_style == SeparatorStyle.ROBIN:
|
|
211
|
-
ret = system_prompt + self.sep
|
|
212
|
-
for role, message in self.messages:
|
|
213
|
-
if message:
|
|
214
|
-
ret += role + ':\n' + message + self.sep
|
|
215
|
-
else:
|
|
216
|
-
ret += role + ':\n'
|
|
217
|
-
return ret
|
|
218
|
-
elif self.sep_style == SeparatorStyle.FALCON_CHAT:
|
|
219
|
-
ret = ''
|
|
220
|
-
if self.system_message:
|
|
221
|
-
ret += system_prompt + self.sep
|
|
222
|
-
for role, message in self.messages:
|
|
223
|
-
if message:
|
|
224
|
-
ret += role + ': ' + message + self.sep
|
|
225
|
-
else:
|
|
226
|
-
ret += role + ':'
|
|
227
|
-
|
|
228
|
-
return ret
|
|
229
|
-
elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
|
|
230
|
-
seps = [self.sep, self.sep2]
|
|
231
|
-
ret = self.system_message + seps[0]
|
|
232
|
-
for i, (role, message) in enumerate(self.messages):
|
|
233
|
-
if message:
|
|
234
|
-
ret += role + ': ' + message + seps[i % 2]
|
|
235
|
-
else:
|
|
236
|
-
ret += role + ':'
|
|
237
|
-
return ret
|
|
238
|
-
elif self.sep_style == SeparatorStyle.MPT:
|
|
239
|
-
ret = system_prompt + self.sep
|
|
240
|
-
for role, message in self.messages:
|
|
241
|
-
if message:
|
|
242
|
-
if type(message) is tuple:
|
|
243
|
-
message, _, _ = message
|
|
244
|
-
ret += role + message + self.sep
|
|
245
|
-
else:
|
|
246
|
-
ret += role
|
|
247
|
-
return ret
|
|
248
|
-
else:
|
|
249
|
-
raise ValueError(f'Invalid style: {self.sep_style}')
|
|
250
|
-
|
|
251
|
-
def set_system_message(self, system_message: str):
|
|
252
|
-
"""Set the system message."""
|
|
253
|
-
self.system_message = system_message
|
|
254
|
-
|
|
255
|
-
def append_message(self, role: str, message: str):
|
|
256
|
-
"""Append a new message."""
|
|
257
|
-
self.messages.append([role, message])
|
|
258
|
-
|
|
259
|
-
def update_last_message(self, message: str):
|
|
260
|
-
"""Update the last output.
|
|
261
|
-
|
|
262
|
-
The last message is typically set to be None when constructing the prompt,
|
|
263
|
-
so we need to update it in-place after getting the response from a model.
|
|
264
|
-
"""
|
|
265
|
-
self.messages[-1][1] = message
|
|
266
|
-
|
|
267
|
-
def to_gradio_chatbot(self):
|
|
268
|
-
"""Convert the conversation to gradio chatbot format."""
|
|
269
|
-
ret = []
|
|
270
|
-
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
|
271
|
-
if i % 2 == 0:
|
|
272
|
-
ret.append([msg, None])
|
|
273
|
-
else:
|
|
274
|
-
ret[-1][-1] = msg
|
|
275
|
-
return ret
|
|
276
|
-
|
|
277
|
-
def to_openai_api_messages(self):
|
|
278
|
-
"""Convert the conversation to OpenAI chat completion format."""
|
|
279
|
-
ret = [{'role': 'system', 'content': self.system_message}]
|
|
280
|
-
|
|
281
|
-
for i, (_, msg) in enumerate(self.messages[self.offset :]):
|
|
282
|
-
if i % 2 == 0:
|
|
283
|
-
ret.append({'role': 'user', 'content': msg})
|
|
284
|
-
else:
|
|
285
|
-
if msg is not None:
|
|
286
|
-
ret.append({'role': 'assistant', 'content': msg})
|
|
287
|
-
return ret
|
|
288
|
-
|
|
289
|
-
def copy(self):
|
|
290
|
-
return Conversation(
|
|
291
|
-
name=self.name,
|
|
292
|
-
system_template=self.system_template,
|
|
293
|
-
system_message=self.system_message,
|
|
294
|
-
roles=self.roles,
|
|
295
|
-
messages=[[x, y] for x, y in self.messages],
|
|
296
|
-
offset=self.offset,
|
|
297
|
-
sep_style=self.sep_style,
|
|
298
|
-
sep=self.sep,
|
|
299
|
-
sep2=self.sep2,
|
|
300
|
-
stop_str=self.stop_str,
|
|
301
|
-
stop_token_ids=self.stop_token_ids,
|
|
302
|
-
)
|
|
303
|
-
|
|
304
|
-
def dict(self):
|
|
305
|
-
return {
|
|
306
|
-
'template_name': self.name,
|
|
307
|
-
'system_message': self.system_message,
|
|
308
|
-
'roles': self.roles,
|
|
309
|
-
'messages': self.messages,
|
|
310
|
-
'offset': self.offset,
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
# A global registry for all conversation templates
|
|
315
|
-
conv_templates: Dict[str, Conversation] = {}
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
def register_conv_template(template: Conversation, override: bool = False):
|
|
319
|
-
"""Register a new conversation template."""
|
|
320
|
-
if not override:
|
|
321
|
-
assert (
|
|
322
|
-
template.name not in conv_templates
|
|
323
|
-
), f'{template.name} has been registered.'
|
|
324
|
-
|
|
325
|
-
conv_templates[template.name] = template
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
def get_conv_template(name: str) -> Conversation:
|
|
329
|
-
"""Get a conversation template."""
|
|
330
|
-
return conv_templates[name].copy()
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
# Both Hermes-2 and internlm2-chat are chatml-format conversation templates. The difference
|
|
334
|
-
# is that during training, the preprocessing function for the Hermes-2 template doesn't add
|
|
335
|
-
# <s> at the beginning of the tokenized sequence, while the internlm2-chat template does.
|
|
336
|
-
# Therefore, they are completely equivalent during inference.
|
|
337
|
-
register_conv_template(
|
|
338
|
-
Conversation(
|
|
339
|
-
name='Hermes-2',
|
|
340
|
-
system_template='<|im_start|>system\n{system_message}',
|
|
341
|
-
# note: The new system prompt was not used here to avoid changes in benchmark performance.
|
|
342
|
-
# system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
|
|
343
|
-
# system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
|
|
344
|
-
system_message='You are a Table Image to LaTeX/Markdown/HMTL Code converter.',
|
|
345
|
-
roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
|
|
346
|
-
sep_style=SeparatorStyle.MPT,
|
|
347
|
-
sep='<|im_end|>',
|
|
348
|
-
stop_token_ids=[
|
|
349
|
-
2,
|
|
350
|
-
6,
|
|
351
|
-
7,
|
|
352
|
-
8,
|
|
353
|
-
],
|
|
354
|
-
stop_str='<|endoftext|>',
|
|
355
|
-
)
|
|
356
|
-
)
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
register_conv_template(
|
|
360
|
-
Conversation(
|
|
361
|
-
name='internlm2-chat',
|
|
362
|
-
system_template='<|im_start|>system\n{system_message}',
|
|
363
|
-
# note: The new system prompt was not used here to avoid changes in benchmark performance.
|
|
364
|
-
# system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
|
|
365
|
-
system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
|
|
366
|
-
roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
|
|
367
|
-
sep_style=SeparatorStyle.MPT,
|
|
368
|
-
sep='<|im_end|>',
|
|
369
|
-
stop_token_ids=[
|
|
370
|
-
2,
|
|
371
|
-
92543,
|
|
372
|
-
92542
|
|
373
|
-
]
|
|
374
|
-
)
|
|
375
|
-
)
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
register_conv_template(
|
|
379
|
-
Conversation(
|
|
380
|
-
name='phi3-chat',
|
|
381
|
-
system_template='<|system|>\n{system_message}',
|
|
382
|
-
# note: The new system prompt was not used here to avoid changes in benchmark performance.
|
|
383
|
-
# system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
|
|
384
|
-
system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
|
|
385
|
-
roles=('<|user|>\n', '<|assistant|>\n'),
|
|
386
|
-
sep_style=SeparatorStyle.MPT,
|
|
387
|
-
sep='<|end|>',
|
|
388
|
-
stop_token_ids=[
|
|
389
|
-
2,
|
|
390
|
-
32000,
|
|
391
|
-
32007
|
|
392
|
-
]
|
|
393
|
-
)
|
|
394
|
-
)
|
|
@@ -1,198 +0,0 @@
|
|
|
1
|
-
import torch
|
|
2
|
-
|
|
3
|
-
from torch import nn
|
|
4
|
-
from transformers import AutoModel, AutoTokenizer, AutoImageProcessor, GenerationConfig
|
|
5
|
-
|
|
6
|
-
from .conversation import get_conv_template
|
|
7
|
-
|
|
8
|
-
class InternVL(nn.Module):
|
|
9
|
-
def __init__(
|
|
10
|
-
self,
|
|
11
|
-
model_path='U4R/StructTable-InternVL2-1B',
|
|
12
|
-
max_new_tokens=1024,
|
|
13
|
-
max_time=30,
|
|
14
|
-
flash_attn=True,
|
|
15
|
-
cache_dir=None,
|
|
16
|
-
local_files_only=None,
|
|
17
|
-
**kwargs,
|
|
18
|
-
):
|
|
19
|
-
super().__init__()
|
|
20
|
-
self.model_path = model_path
|
|
21
|
-
self.max_new_tokens = max_new_tokens
|
|
22
|
-
self.max_generate_time = max_time
|
|
23
|
-
self.flash_attn = flash_attn
|
|
24
|
-
self.cache_dir = cache_dir
|
|
25
|
-
self.local_files_only = local_files_only
|
|
26
|
-
|
|
27
|
-
# init model and image processor from ckpt path
|
|
28
|
-
self.init_tokenizer(model_path)
|
|
29
|
-
self.init_image_processor(model_path)
|
|
30
|
-
self.init_model(model_path)
|
|
31
|
-
|
|
32
|
-
self.prompt_template = {
|
|
33
|
-
'latex': '<latex>',
|
|
34
|
-
'html': '<html>',
|
|
35
|
-
'markdown': '<markdown>',
|
|
36
|
-
}
|
|
37
|
-
# support output format
|
|
38
|
-
self.supported_output_format = ['latex', 'html', 'markdown']
|
|
39
|
-
|
|
40
|
-
def init_model(self, model_path):
|
|
41
|
-
self.model = AutoModel.from_pretrained(
|
|
42
|
-
pretrained_model_name_or_path=model_path,
|
|
43
|
-
trust_remote_code=True,
|
|
44
|
-
torch_dtype=torch.bfloat16,
|
|
45
|
-
low_cpu_mem_usage=True,
|
|
46
|
-
use_flash_attn=self.flash_attn,
|
|
47
|
-
cache_dir=self.cache_dir,
|
|
48
|
-
local_files_only=self.local_files_only,
|
|
49
|
-
)
|
|
50
|
-
self.model.eval()
|
|
51
|
-
|
|
52
|
-
def init_image_processor(self, image_processor_path):
|
|
53
|
-
self.image_processor = AutoImageProcessor.from_pretrained(
|
|
54
|
-
pretrained_model_name_or_path=image_processor_path,
|
|
55
|
-
trust_remote_code=True,
|
|
56
|
-
cache_dir=self.cache_dir,
|
|
57
|
-
local_files_only=self.local_files_only,
|
|
58
|
-
)
|
|
59
|
-
|
|
60
|
-
def init_tokenizer(self, tokenizer_path):
|
|
61
|
-
self.tokenizer = AutoTokenizer.from_pretrained(
|
|
62
|
-
pretrained_model_name_or_path=tokenizer_path,
|
|
63
|
-
trust_remote_code=True,
|
|
64
|
-
use_fast=False,
|
|
65
|
-
cache_dir=self.cache_dir,
|
|
66
|
-
local_files_only=self.local_files_only,
|
|
67
|
-
)
|
|
68
|
-
|
|
69
|
-
self.image_context_token = '<IMG_CONTEXT>'
|
|
70
|
-
self.image_token_num = 256
|
|
71
|
-
self.image_start_token = '<img>'
|
|
72
|
-
self.image_end_token = '</img>'
|
|
73
|
-
self.img_context_token_id = self.tokenizer.convert_tokens_to_ids(self.image_context_token)
|
|
74
|
-
|
|
75
|
-
def format_image_tokens(self, path_num):
|
|
76
|
-
return f'{self.image_start_token}{self.image_context_token* self.image_token_num * path_num}{self.image_end_token}'
|
|
77
|
-
|
|
78
|
-
def forward(self, images, output_format='latex', **kwargs):
|
|
79
|
-
# process image to tokens
|
|
80
|
-
if not isinstance(images, list):
|
|
81
|
-
images = [images]
|
|
82
|
-
|
|
83
|
-
pixel_values_list = []
|
|
84
|
-
for image in images:
|
|
85
|
-
path_images = self.dynamic_preprocess(
|
|
86
|
-
image, image_size=448, max_num=12
|
|
87
|
-
)
|
|
88
|
-
pixel_values = self.image_processor(
|
|
89
|
-
path_images,
|
|
90
|
-
return_tensors='pt'
|
|
91
|
-
)['pixel_values'].to(torch.bfloat16)
|
|
92
|
-
pixel_values_list.append(pixel_values)
|
|
93
|
-
|
|
94
|
-
batch_size = len(pixel_values_list)
|
|
95
|
-
conversation_list = []
|
|
96
|
-
for bs_idx in range(batch_size):
|
|
97
|
-
pixel_values= pixel_values_list[bs_idx].to(torch.bfloat16)
|
|
98
|
-
|
|
99
|
-
image_tokens = self.format_image_tokens(pixel_values.shape[0])
|
|
100
|
-
question = '<image>\n' + self.prompt_template[output_format]
|
|
101
|
-
answer = None
|
|
102
|
-
|
|
103
|
-
template = get_conv_template(self.model.config.template)
|
|
104
|
-
template.append_message(template.roles[0], question)
|
|
105
|
-
template.append_message(template.roles[1], answer)
|
|
106
|
-
conversation = template.get_prompt()
|
|
107
|
-
conversation = conversation.replace('<image>', image_tokens, 1)
|
|
108
|
-
conversation_list.append(conversation)
|
|
109
|
-
|
|
110
|
-
device = next(self.parameters()).device
|
|
111
|
-
self.tokenizer.padding_side = 'left'
|
|
112
|
-
model_inputs = self.tokenizer(
|
|
113
|
-
conversation_list,
|
|
114
|
-
return_tensors='pt',
|
|
115
|
-
padding=True,
|
|
116
|
-
max_length=self.tokenizer.model_max_length,
|
|
117
|
-
truncation=True,
|
|
118
|
-
).to(device)
|
|
119
|
-
pixel_values = torch.cat(pixel_values_list, axis=0).to(device)
|
|
120
|
-
|
|
121
|
-
# generation config
|
|
122
|
-
generation_config = dict(
|
|
123
|
-
max_new_tokens=self.max_new_tokens,
|
|
124
|
-
max_time=self.max_generate_time,
|
|
125
|
-
img_context_token_id=self.img_context_token_id,
|
|
126
|
-
pad_token_id=self.tokenizer.pad_token_id,
|
|
127
|
-
eos_token_id=self.tokenizer.eos_token_id,
|
|
128
|
-
do_sample=False,
|
|
129
|
-
no_repeat_ngram_size=20,
|
|
130
|
-
)
|
|
131
|
-
|
|
132
|
-
# generate text from image tokens
|
|
133
|
-
model_output = self.model.generate(
|
|
134
|
-
pixel_values=pixel_values,
|
|
135
|
-
input_ids=model_inputs.input_ids,
|
|
136
|
-
attention_mask=model_inputs.attention_mask,
|
|
137
|
-
**generation_config,
|
|
138
|
-
# **kwargs
|
|
139
|
-
)
|
|
140
|
-
|
|
141
|
-
batch_decode_texts = self.tokenizer.batch_decode(
|
|
142
|
-
model_output,
|
|
143
|
-
skip_special_tokens=True
|
|
144
|
-
)
|
|
145
|
-
return batch_decode_texts
|
|
146
|
-
|
|
147
|
-
def find_closest_aspect_ratio(self, aspect_ratio, target_ratios, width, height, image_size):
|
|
148
|
-
best_ratio_diff = float('inf')
|
|
149
|
-
best_ratio = (1, 1)
|
|
150
|
-
area = width * height
|
|
151
|
-
for ratio in target_ratios:
|
|
152
|
-
target_aspect_ratio = ratio[0] / ratio[1]
|
|
153
|
-
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
|
|
154
|
-
if ratio_diff < best_ratio_diff:
|
|
155
|
-
best_ratio_diff = ratio_diff
|
|
156
|
-
best_ratio = ratio
|
|
157
|
-
elif ratio_diff == best_ratio_diff:
|
|
158
|
-
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
|
|
159
|
-
best_ratio = ratio
|
|
160
|
-
return best_ratio
|
|
161
|
-
|
|
162
|
-
def dynamic_preprocess(self, image, min_num=1, max_num=12, image_size=448, use_thumbnail=True):
|
|
163
|
-
orig_width, orig_height = image.size
|
|
164
|
-
aspect_ratio = orig_width / orig_height
|
|
165
|
-
|
|
166
|
-
# calculate the existing image aspect ratio
|
|
167
|
-
target_ratios = set(
|
|
168
|
-
(i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
|
|
169
|
-
i * j <= max_num and i * j >= min_num)
|
|
170
|
-
target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
|
|
171
|
-
|
|
172
|
-
# find the closest aspect ratio to the target
|
|
173
|
-
target_aspect_ratio = self.find_closest_aspect_ratio(
|
|
174
|
-
aspect_ratio, target_ratios, orig_width, orig_height, image_size)
|
|
175
|
-
|
|
176
|
-
# calculate the target width and height
|
|
177
|
-
target_width = image_size * target_aspect_ratio[0]
|
|
178
|
-
target_height = image_size * target_aspect_ratio[1]
|
|
179
|
-
blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
|
|
180
|
-
|
|
181
|
-
# resize the image
|
|
182
|
-
resized_img = image.resize((target_width, target_height))
|
|
183
|
-
processed_images = []
|
|
184
|
-
for i in range(blocks):
|
|
185
|
-
box = (
|
|
186
|
-
(i % (target_width // image_size)) * image_size,
|
|
187
|
-
(i // (target_width // image_size)) * image_size,
|
|
188
|
-
((i % (target_width // image_size)) + 1) * image_size,
|
|
189
|
-
((i // (target_width // image_size)) + 1) * image_size
|
|
190
|
-
)
|
|
191
|
-
# split the image
|
|
192
|
-
split_img = resized_img.crop(box)
|
|
193
|
-
processed_images.append(split_img)
|
|
194
|
-
assert len(processed_images) == blocks
|
|
195
|
-
if use_thumbnail and len(processed_images) != 1:
|
|
196
|
-
thumbnail_img = image.resize((image_size, image_size))
|
|
197
|
-
processed_images.append(thumbnail_img)
|
|
198
|
-
return processed_images
|
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
import torch
|
|
2
|
-
from torch import nn
|
|
3
|
-
|
|
4
|
-
from transformers import AutoTokenizer
|
|
5
|
-
try:
|
|
6
|
-
from lmdeploy import pipeline, GenerationConfig, PytorchEngineConfig, ChatTemplateConfig
|
|
7
|
-
except:
|
|
8
|
-
print("\033[93mimport lmdeploy failed, if do not use lmdeploy, ignore this message\033[0m")
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
class InternVL_LMDeploy(nn.Module):
|
|
12
|
-
def __init__(
|
|
13
|
-
self,
|
|
14
|
-
model_path='U4R/StructTable-InternVL2-1B',
|
|
15
|
-
max_new_tokens=1024,
|
|
16
|
-
batch_size=4,
|
|
17
|
-
cache_dir=None,
|
|
18
|
-
local_files_only=None,
|
|
19
|
-
**kwargs,
|
|
20
|
-
):
|
|
21
|
-
super().__init__()
|
|
22
|
-
self.model_path = model_path
|
|
23
|
-
self.max_new_tokens = max_new_tokens
|
|
24
|
-
self.max_batch_size = batch_size
|
|
25
|
-
self.cache_dir = cache_dir
|
|
26
|
-
self.local_files_only = local_files_only
|
|
27
|
-
|
|
28
|
-
# init model and tokenizer from ckpt path
|
|
29
|
-
self.init_tokenizer(model_path)
|
|
30
|
-
self.init_model(model_path)
|
|
31
|
-
|
|
32
|
-
self.prompt_template = {
|
|
33
|
-
'latex': '<latex>',
|
|
34
|
-
'html': '<html>',
|
|
35
|
-
'markdown': '<markdown>',
|
|
36
|
-
}
|
|
37
|
-
# support output format
|
|
38
|
-
self.supported_output_format = ['latex', 'html', 'markdown']
|
|
39
|
-
|
|
40
|
-
def init_tokenizer(self, tokenizer_path):
|
|
41
|
-
self.tokenizer = AutoTokenizer.from_pretrained(
|
|
42
|
-
pretrained_model_name_or_path=tokenizer_path,
|
|
43
|
-
trust_remote_code=True,
|
|
44
|
-
use_fast=False,
|
|
45
|
-
cache_dir=self.cache_dir,
|
|
46
|
-
local_files_only=self.local_files_only,
|
|
47
|
-
)
|
|
48
|
-
|
|
49
|
-
def init_model(self, model_path):
|
|
50
|
-
engine_config = PytorchEngineConfig(
|
|
51
|
-
dtype='bfloat16',
|
|
52
|
-
max_batch_size=self.max_batch_size,
|
|
53
|
-
cache_max_entry_count=0.1
|
|
54
|
-
)
|
|
55
|
-
self.pipeline = pipeline(
|
|
56
|
-
model_path,
|
|
57
|
-
backend_config=engine_config,
|
|
58
|
-
chat_template_config=ChatTemplateConfig(model_name='internvl2-internlm2')
|
|
59
|
-
)
|
|
60
|
-
|
|
61
|
-
def forward(self, images, output_format='latex', **kwargs):
|
|
62
|
-
# process image to tokens
|
|
63
|
-
if not isinstance(images, list):
|
|
64
|
-
images = [images]
|
|
65
|
-
|
|
66
|
-
prompts = [self.prompt_template[output_format]] * len(images)
|
|
67
|
-
generation_config = GenerationConfig(
|
|
68
|
-
max_new_tokens=self.max_new_tokens,
|
|
69
|
-
do_sample=False,
|
|
70
|
-
temperature=1.0,
|
|
71
|
-
stop_token_ids=[self.tokenizer.eos_token_id],
|
|
72
|
-
)
|
|
73
|
-
|
|
74
|
-
responses = self.pipeline(
|
|
75
|
-
[(x, y) for x, y in zip(prompts, images)],
|
|
76
|
-
gen_config=generation_config,
|
|
77
|
-
)
|
|
78
|
-
batch_decode_texts = [responce.text for responce in responses]
|
|
79
|
-
return batch_decode_texts
|
|
80
|
-
|
|
81
|
-
|