doc-page-extractor 0.0.10__py3-none-any.whl → 0.1.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.
Potentially problematic release.
This version of doc-page-extractor might be problematic. Click here for more details.
- doc_page_extractor/__init__.py +12 -2
- doc_page_extractor/extractor.py +53 -10
- doc_page_extractor/latex.py +57 -0
- doc_page_extractor/struct_eqtable/__init__.py +49 -0
- doc_page_extractor/struct_eqtable/internvl/__init__.py +2 -0
- doc_page_extractor/struct_eqtable/internvl/conversation.py +394 -0
- doc_page_extractor/struct_eqtable/internvl/internvl.py +198 -0
- doc_page_extractor/struct_eqtable/internvl/internvl_lmdeploy.py +81 -0
- doc_page_extractor/struct_eqtable/pix2s/__init__.py +3 -0
- doc_page_extractor/struct_eqtable/pix2s/pix2s.py +76 -0
- doc_page_extractor/struct_eqtable/pix2s/pix2s_trt.py +1047 -0
- doc_page_extractor/table.py +71 -0
- doc_page_extractor/types.py +34 -3
- doc_page_extractor/utils.py +23 -1
- {doc_page_extractor-0.0.10.dist-info → doc_page_extractor-0.1.0.dist-info}/METADATA +6 -2
- {doc_page_extractor-0.0.10.dist-info → doc_page_extractor-0.1.0.dist-info}/RECORD +19 -9
- {doc_page_extractor-0.0.10.dist-info → doc_page_extractor-0.1.0.dist-info}/WHEEL +0 -0
- {doc_page_extractor-0.0.10.dist-info → doc_page_extractor-0.1.0.dist-info}/licenses/LICENSE +0 -0
- {doc_page_extractor-0.0.10.dist-info → doc_page_extractor-0.1.0.dist-info}/top_level.txt +0 -0
doc_page_extractor/__init__.py
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
from .extractor import DocExtractor
|
|
2
2
|
from .clipper import clip, clip_from_image
|
|
3
3
|
from .plot import plot
|
|
4
|
-
from .
|
|
5
|
-
from .
|
|
4
|
+
from .rectangle import Point, Rectangle
|
|
5
|
+
from .types import (
|
|
6
|
+
ExtractedResult,
|
|
7
|
+
OCRFragment,
|
|
8
|
+
LayoutClass,
|
|
9
|
+
TableLayoutParsedFormat,
|
|
10
|
+
Layout,
|
|
11
|
+
BaseLayout,
|
|
12
|
+
PlainLayout,
|
|
13
|
+
FormulaLayout,
|
|
14
|
+
TableLayout,
|
|
15
|
+
)
|
doc_page_extractor/extractor.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import os
|
|
2
2
|
|
|
3
|
-
from typing import Literal
|
|
3
|
+
from typing import Literal, Generator
|
|
4
4
|
from pathlib import Path
|
|
5
5
|
from PIL.Image import Image
|
|
6
6
|
from doclayout_yolo import YOLOv10
|
|
@@ -9,10 +9,22 @@ from .ocr import OCR
|
|
|
9
9
|
from .ocr_corrector import correct_fragments
|
|
10
10
|
from .raw_optimizer import RawOptimizer
|
|
11
11
|
from .rectangle import intersection_area, Rectangle
|
|
12
|
-
from .types import ExtractedResult, OCRFragment, LayoutClass, Layout
|
|
13
12
|
from .downloader import download
|
|
13
|
+
from .table import Table
|
|
14
|
+
from .latex import LaTeX
|
|
14
15
|
from .layout_order import LayoutOrder
|
|
15
16
|
from .overlap import merge_fragments_as_line, remove_overlap_layouts
|
|
17
|
+
from .clipper import clip_from_image
|
|
18
|
+
from .types import (
|
|
19
|
+
ExtractedResult,
|
|
20
|
+
OCRFragment,
|
|
21
|
+
TableLayoutParsedFormat,
|
|
22
|
+
Layout,
|
|
23
|
+
LayoutClass,
|
|
24
|
+
PlainLayout,
|
|
25
|
+
TableLayout,
|
|
26
|
+
FormulaLayout,
|
|
27
|
+
)
|
|
16
28
|
|
|
17
29
|
|
|
18
30
|
class DocExtractor:
|
|
@@ -21,12 +33,26 @@ class DocExtractor:
|
|
|
21
33
|
model_dir_path: str,
|
|
22
34
|
device: Literal["cpu", "cuda"] = "cpu",
|
|
23
35
|
ocr_for_each_layouts: bool = True,
|
|
36
|
+
extract_formula: bool = True,
|
|
37
|
+
extract_table_format: TableLayoutParsedFormat | None = None,
|
|
24
38
|
):
|
|
25
39
|
self._model_dir_path: str = model_dir_path
|
|
26
40
|
self._device: Literal["cpu", "cuda"] = device
|
|
27
41
|
self._ocr_for_each_layouts: bool = ocr_for_each_layouts
|
|
28
|
-
self.
|
|
42
|
+
self._extract_formula: bool = extract_formula
|
|
43
|
+
self._extract_table_format: TableLayoutParsedFormat | None = extract_table_format
|
|
29
44
|
self._yolo: YOLOv10 | None = None
|
|
45
|
+
self._ocr: OCR = OCR(
|
|
46
|
+
device=device,
|
|
47
|
+
model_dir_path=os.path.join(model_dir_path, "onnx_ocr"),
|
|
48
|
+
)
|
|
49
|
+
self._table: Table = Table(
|
|
50
|
+
device=device,
|
|
51
|
+
model_path=os.path.join(model_dir_path, "struct_eqtable"),
|
|
52
|
+
)
|
|
53
|
+
self._latex: LaTeX = LaTeX(
|
|
54
|
+
model_path=os.path.join(model_dir_path, "latex"),
|
|
55
|
+
)
|
|
30
56
|
self._layout_order: LayoutOrder = LayoutOrder(
|
|
31
57
|
model_path=os.path.join(model_dir_path, "layoutreader"),
|
|
32
58
|
)
|
|
@@ -40,7 +66,7 @@ class DocExtractor:
|
|
|
40
66
|
raw_optimizer = RawOptimizer(image, adjust_points)
|
|
41
67
|
fragments = list(self._ocr.search_fragments(raw_optimizer.image_np))
|
|
42
68
|
raw_optimizer.receive_raw_fragments(fragments)
|
|
43
|
-
layouts = self.
|
|
69
|
+
layouts = list(self._yolo_extract_layouts(raw_optimizer.image))
|
|
44
70
|
layouts = self._layouts_matched_by_fragments(fragments, layouts)
|
|
45
71
|
layouts = remove_overlap_layouts(layouts)
|
|
46
72
|
|
|
@@ -50,6 +76,8 @@ class DocExtractor:
|
|
|
50
76
|
layouts = self._layout_order.sort(layouts, raw_optimizer.image.size)
|
|
51
77
|
layouts = [layout for layout in layouts if self._should_keep_layout(layout)]
|
|
52
78
|
|
|
79
|
+
self._parse_table_and_formula_layouts(layouts, raw_optimizer)
|
|
80
|
+
|
|
53
81
|
for layout in layouts:
|
|
54
82
|
layout.fragments = merge_fragments_as_line(layout.fragments)
|
|
55
83
|
|
|
@@ -62,7 +90,7 @@ class DocExtractor:
|
|
|
62
90
|
adjusted_image=raw_optimizer.adjusted_image,
|
|
63
91
|
)
|
|
64
92
|
|
|
65
|
-
def
|
|
93
|
+
def _yolo_extract_layouts(self, source: Image) -> Generator[Layout, None, None]:
|
|
66
94
|
# about source parameter to see:
|
|
67
95
|
# https://github.com/opendatalab/DocLayout-YOLO/blob/7c4be36bc61f11b67cf4a44ee47f3c41e9800a91/doclayout_yolo/data/build.py#L157-L175
|
|
68
96
|
det_res = self._get_yolo().predict(
|
|
@@ -72,7 +100,6 @@ class DocExtractor:
|
|
|
72
100
|
device=self._device # Device to use (e.g., "cuda" or "cpu")
|
|
73
101
|
)
|
|
74
102
|
boxes = det_res[0].__dict__["boxes"]
|
|
75
|
-
layouts: list[Layout] = []
|
|
76
103
|
|
|
77
104
|
for cls_id, rect in zip(boxes.cls, boxes.xyxy):
|
|
78
105
|
cls_id = cls_id.item()
|
|
@@ -89,9 +116,12 @@ class DocExtractor:
|
|
|
89
116
|
lb=(x1, y2),
|
|
90
117
|
rb=(x2, y2),
|
|
91
118
|
)
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
119
|
+
if cls == LayoutClass.TABLE:
|
|
120
|
+
yield TableLayout(cls=cls, rect=rect, fragments=[], parsed=None)
|
|
121
|
+
elif cls == LayoutClass.ISOLATE_FORMULA:
|
|
122
|
+
yield FormulaLayout(cls=cls, rect=rect, fragments=[], latex=None)
|
|
123
|
+
else:
|
|
124
|
+
yield PlainLayout(cls=cls, rect=rect, fragments=[])
|
|
95
125
|
|
|
96
126
|
def _layouts_matched_by_fragments(self, fragments: list[OCRFragment], layouts: list[Layout]):
|
|
97
127
|
layouts_group = self._split_layouts_by_group(layouts)
|
|
@@ -107,6 +137,17 @@ class DocExtractor:
|
|
|
107
137
|
for layout in layouts:
|
|
108
138
|
correct_fragments(self._ocr, source, layout)
|
|
109
139
|
|
|
140
|
+
def _parse_table_and_formula_layouts(self, layouts: list[Layout], raw_optimizer: RawOptimizer):
|
|
141
|
+
for layout in layouts:
|
|
142
|
+
if isinstance(layout, FormulaLayout) and self._extract_formula:
|
|
143
|
+
image = clip_from_image(raw_optimizer.image, layout.rect)
|
|
144
|
+
layout.latex = self._latex.extract(image)
|
|
145
|
+
elif isinstance(layout, TableLayout) and self._extract_table_format is not None:
|
|
146
|
+
image = clip_from_image(raw_optimizer.image, layout.rect)
|
|
147
|
+
parsed = self._table.predict(image, self._extract_table_format)
|
|
148
|
+
if parsed is not None:
|
|
149
|
+
layout.parsed = (parsed, self._extract_table_format)
|
|
150
|
+
|
|
110
151
|
def _split_layouts_by_group(self, layouts: list[Layout]):
|
|
111
152
|
texts_layouts: list[Layout] = []
|
|
112
153
|
abandon_layouts: list[Layout] = []
|
|
@@ -149,9 +190,11 @@ class DocExtractor:
|
|
|
149
190
|
|
|
150
191
|
def _get_yolo(self) -> YOLOv10:
|
|
151
192
|
if self._yolo is None:
|
|
193
|
+
base_path = os.path.join(self._model_dir_path, "yolo")
|
|
194
|
+
os.makedirs(base_path, exist_ok=True)
|
|
152
195
|
yolo_model_url = "https://huggingface.co/opendatalab/PDF-Extract-Kit-1.0/resolve/main/models/Layout/YOLO/doclayout_yolo_ft.pt"
|
|
153
196
|
yolo_model_name = "doclayout_yolo_ft.pt"
|
|
154
|
-
yolo_model_path = Path(os.path.join(
|
|
197
|
+
yolo_model_path = Path(os.path.join(base_path, yolo_model_name))
|
|
155
198
|
if not yolo_model_path.exists():
|
|
156
199
|
download(yolo_model_url, yolo_model_path)
|
|
157
200
|
self._yolo = YOLOv10(str(yolo_model_path))
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import torch
|
|
3
|
+
import requests
|
|
4
|
+
|
|
5
|
+
from munch import Munch
|
|
6
|
+
from pix2tex.cli import LatexOCR
|
|
7
|
+
from PIL.Image import Image
|
|
8
|
+
from .utils import expand_image
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class LaTeX:
|
|
12
|
+
def __init__(self, model_path: str):
|
|
13
|
+
self._model_path: str = model_path
|
|
14
|
+
self._model: LatexOCR | None = None
|
|
15
|
+
|
|
16
|
+
def extract(self, image: Image) -> str | None:
|
|
17
|
+
image = expand_image(image, 0.1) # 添加边缘提高识别准确率
|
|
18
|
+
model = self._get_model()
|
|
19
|
+
with torch.no_grad():
|
|
20
|
+
return model(image)
|
|
21
|
+
|
|
22
|
+
def _get_model(self) -> LatexOCR:
|
|
23
|
+
if self._model is None:
|
|
24
|
+
if not os.path.exists(self._model_path):
|
|
25
|
+
self._download_model()
|
|
26
|
+
|
|
27
|
+
self._model = LatexOCR(Munch({
|
|
28
|
+
"config": os.path.join("settings", "config.yaml"),
|
|
29
|
+
"checkpoint": os.path.join(self._model_path, "weights.pth"),
|
|
30
|
+
"no_cuda": True,
|
|
31
|
+
"no_resize": False,
|
|
32
|
+
}))
|
|
33
|
+
return self._model
|
|
34
|
+
|
|
35
|
+
# from https://github.com/lukas-blecher/LaTeX-OCR/blob/5c1ac929bd19a7ecf86d5fb8d94771c8969fcb80/pix2tex/model/checkpoints/get_latest_checkpoint.py#L37-L45
|
|
36
|
+
def _download_model(self):
|
|
37
|
+
os.makedirs(self._model_path, exist_ok=True)
|
|
38
|
+
tag = "v0.0.1"
|
|
39
|
+
files: list[tuple[str, str]] = (
|
|
40
|
+
("weights.pth", f"https://github.com/lukas-blecher/LaTeX-OCR/releases/download/{tag}/weights.pth"),
|
|
41
|
+
("image_resizer.pth", f"https://github.com/lukas-blecher/LaTeX-OCR/releases/download/{tag}/image_resizer.pth")
|
|
42
|
+
)
|
|
43
|
+
for file_name, url in files:
|
|
44
|
+
file_path = os.path.join(self._model_path, file_name)
|
|
45
|
+
try:
|
|
46
|
+
with open(file_path, "wb") as file:
|
|
47
|
+
response = requests.get(url, stream=True, timeout=15)
|
|
48
|
+
response.raise_for_status()
|
|
49
|
+
for chunk in response.iter_content(chunk_size=8192):
|
|
50
|
+
if chunk: # 过滤掉保持连接的新块
|
|
51
|
+
file.write(chunk)
|
|
52
|
+
file.flush()
|
|
53
|
+
|
|
54
|
+
except BaseException as e:
|
|
55
|
+
if os.path.exists(file_path):
|
|
56
|
+
os.remove(file_path)
|
|
57
|
+
raise e
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from .pix2s import Pix2Struct, Pix2StructTensorRT
|
|
2
|
+
from .internvl import InternVL, InternVL_LMDeploy
|
|
3
|
+
|
|
4
|
+
from transformers import AutoConfig
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
__ALL_MODELS__ = {
|
|
8
|
+
'Pix2Struct': Pix2Struct,
|
|
9
|
+
'Pix2StructTensorRT': Pix2StructTensorRT,
|
|
10
|
+
'InternVL': InternVL,
|
|
11
|
+
'InternVL_LMDeploy': InternVL_LMDeploy,
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def get_model_name(model_path):
|
|
16
|
+
model_config = AutoConfig.from_pretrained(
|
|
17
|
+
model_path,
|
|
18
|
+
trust_remote_code=True,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
if 'Pix2Struct' in model_config.architectures[0]:
|
|
22
|
+
model_name = 'Pix2Struct'
|
|
23
|
+
elif 'InternVL' in model_config.architectures[0]:
|
|
24
|
+
model_name = 'InternVL'
|
|
25
|
+
else:
|
|
26
|
+
raise ValueError(f"Unsupported model type: {model_config.architectures[0]}")
|
|
27
|
+
|
|
28
|
+
return model_name
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def build_model(
|
|
32
|
+
model_ckpt='U4R/StructTable-InternVL2-1B',
|
|
33
|
+
cache_dir=None,
|
|
34
|
+
local_files_only=None,
|
|
35
|
+
**kwargs,
|
|
36
|
+
):
|
|
37
|
+
model_name = get_model_name(model_ckpt)
|
|
38
|
+
if model_name == 'InternVL' and kwargs.get('lmdeploy', False):
|
|
39
|
+
model_name = 'InternVL_LMDeploy'
|
|
40
|
+
elif model_name == 'Pix2Struct' and kwargs.get('tensorrt_path', None):
|
|
41
|
+
model_name = 'Pix2StructTensorRT'
|
|
42
|
+
|
|
43
|
+
model = __ALL_MODELS__[model_name](
|
|
44
|
+
model_ckpt,
|
|
45
|
+
cache_dir=cache_dir,
|
|
46
|
+
local_files_only=local_files_only,
|
|
47
|
+
**kwargs
|
|
48
|
+
)
|
|
49
|
+
return model
|
|
@@ -0,0 +1,394 @@
|
|
|
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
|
+
)
|