File size: 7,893 Bytes
3530326
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8b1739
3530326
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8b1739
 
 
 
3530326
d8b1739
3530326
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270d701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
from __future__ import annotations

import json
import re
from typing import Any

import bleach
import markdown

TABLE_RE = re.compile(r"<table\b[\s\S]*?</table>", re.IGNORECASE)
JSON_OBJECT_RE = re.compile(
    r'\{[^{}]*?"bbox"\s*:\s*\[[^\]]+\][^{}]*?\}',
    re.IGNORECASE,
)
BBOX_TAG_RE = re.compile(
    r"""<(?:bbox|box)(?:\s+label=["']?([^"'>]+)["']?)?[^>]*>
        \s*\[?\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\]?
        \s*</(?:bbox|box)>""",
    re.IGNORECASE | re.VERBOSE,
)

TABLE_TAGS = [
    "table",
    "caption",
    "thead",
    "tbody",
    "tfoot",
    "tr",
    "th",
    "td",
    "br",
    "strong",
    "em",
]
TABLE_ATTRIBUTES = {
    "th": ["colspan", "rowspan", "scope"],
    "td": ["colspan", "rowspan"],
}
TEXT_TAGS = [
    "p",
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "ul",
    "ol",
    "li",
    "strong",
    "em",
    "code",
    "pre",
    "blockquote",
    "hr",
    "br",
]
TABLE_TEXT_MARKER = "`<table>...</table>`"


def _normalize_box(candidate: dict[str, Any], index: int) -> dict | None:
    bbox = candidate.get("bbox")
    if not isinstance(bbox, list) or len(bbox) != 4:
        return None

    try:
        coords = [float(value) for value in bbox]
    except (TypeError, ValueError):
        return None

    maximum = max(coords)
    scale = 1 if maximum <= 1 else (1000 if maximum <= 1000 else maximum)
    x1, y1, x2, y2 = [min(1, max(0, value / scale)) for value in coords]
    if x2 <= x1 or y2 <= y1:
        return None

    label = str(candidate.get("label") or candidate.get("type") or "element")
    return {
        "id": f"{index}-{'-'.join(str(value) for value in coords)}",
        "label": label[:48],
        "bbox": [x1, y1, x2, y2],
    }


def extract_bounding_boxes(raw_text: str) -> list[dict]:
    candidates: list[dict] = []
    for match in JSON_OBJECT_RE.finditer(raw_text):
        try:
            candidate = json.loads(match.group(0))
        except json.JSONDecodeError:
            continue
        if isinstance(candidate, dict):
            candidates.append(candidate)

    for match in BBOX_TAG_RE.finditer(raw_text):
        candidates.append(
            {
                "label": match.group(1) or "element",
                "bbox": [float(match.group(index)) for index in range(2, 6)],
            }
        )

    boxes = []
    for index, candidate in enumerate(candidates):
        normalized = _normalize_box(candidate, index)
        if normalized:
            boxes.append(normalized)
    return boxes[:250]


def extract_tables(raw_text: str) -> str:
    tables = TABLE_RE.findall(raw_text)
    if not tables:
        return ""
    return bleach.clean(
        "\n".join(tables),
        tags=TABLE_TAGS,
        attributes=TABLE_ATTRIBUTES,
        protocols=[],
        strip=True,
    )


def render_text(raw_text: str) -> str:
    text_with_table_markers = TABLE_RE.sub(
        f"\n\n{TABLE_TEXT_MARKER}\n\n",
        raw_text,
    )
    rendered = markdown.markdown(
        text_with_table_markers,
        extensions=["extra", "sane_lists"],
        output_format="html",
    )
    return bleach.clean(
        rendered,
        tags=TEXT_TAGS,
        attributes={},
        protocols=[],
        strip=True,
    )


def shape_parser_output(raw_text: str) -> dict:
    output = raw_text if isinstance(raw_text, str) else ""
    return {
        "raw_output": output,
        "output_chars": len(output),
        "boxes": extract_bounding_boxes(output),
        "tables_html": extract_tables(output),
        "text_html": render_text(output),
    }


def _structured_box(
    payload: dict[str, Any],
    *,
    label: str,
    index: int,
) -> dict | None:
    bbox = payload.get("bounding_box_normalized")
    if not isinstance(bbox, dict):
        return None
    return _normalize_box(
        {
            "label": label,
            "bbox": [
                bbox.get("top_left_x"),
                bbox.get("top_left_y"),
                bbox.get("bottom_right_x"),
                bbox.get("bottom_right_y"),
            ],
        },
        index,
    )


def _shape_blocks_page(page: dict[str, Any]) -> tuple[str, list[dict]]:
    blocks = page.get("blocks")
    if not isinstance(blocks, list):
        raise ValueError("blocks page is missing blocks")

    content: list[str] = []
    boxes: list[dict] = []
    for block in blocks:
        if not isinstance(block, dict):
            raise ValueError("invalid parse block")

        block_type = block.get("type")
        if block_type == "text":
            text = block.get("text")
            if not isinstance(text, dict) or not isinstance(text.get("content"), str):
                raise ValueError("invalid text block")
            content.append(text["content"])
            continue

        if block_type == "table":
            table = block.get("table")
            if not isinstance(table, dict) or not isinstance(table.get("html"), str):
                raise ValueError("invalid table block")
            content.append(table["html"])
            box = _structured_box(
                table,
                label=str(table.get("title") or "table"),
                index=len(boxes),
            )
        elif block_type == "image":
            image = block.get("image")
            if not isinstance(image, dict):
                raise ValueError("invalid image block")
            description = str(image.get("description") or "Image")
            content.append(f"*Image: {description}*")
            box = _structured_box(
                image,
                label=str(image.get("category") or image.get("id") or "image"),
                index=len(boxes),
            )
        else:
            raise ValueError("unsupported parse block")

        if box:
            boxes.append(box)

    return "\n\n".join(content), boxes


def _shape_markdown_page(page: dict[str, Any]) -> tuple[str, list[dict]]:
    markdown_page = page.get("markdown")
    if not isinstance(markdown_page, dict) or not isinstance(
        markdown_page.get("content"), str
    ):
        raise ValueError("invalid markdown page")

    boxes = []
    for image in markdown_page.get("images") or []:
        if not isinstance(image, dict):
            raise ValueError("invalid markdown image")
        box = _structured_box(
            image,
            label=str(image.get("category") or image.get("id") or "image"),
            index=len(boxes),
        )
        if box:
            boxes.append(box)
    return markdown_page["content"], boxes


def shape_parse_response(body: dict[str, Any]) -> dict:
    if not isinstance(body, dict):
        raise TypeError("parse response must be an object")
    pages = body.get("pages")
    if not isinstance(pages, list) or not pages:
        raise ValueError("parse response is missing pages")

    page_content: list[str] = []
    boxes: list[dict] = []
    for page in pages:
        if not isinstance(page, dict):
            raise ValueError("invalid parse page")
        page_type = page.get("type")
        if page_type == "blocks":
            content, page_boxes = _shape_blocks_page(page)
        elif page_type == "markdown":
            content, page_boxes = _shape_markdown_page(page)
        elif page_type == "raw_generation" and isinstance(
            page.get("raw_generation"), str
        ):
            content, page_boxes = page["raw_generation"], []
        else:
            raise ValueError("unsupported parse page")
        page_content.append(content)
        boxes.extend(page_boxes)

    text_output = "\n\n".join(page_content)
    shaped = shape_parser_output(text_output)
    return {
        **shaped,
        "raw_output": json.dumps(body, indent=2, ensure_ascii=False),
        "output_chars": len(text_output),
        "boxes": boxes[:250],
        "text_output": text_output,
        "response": body,
    }