File size: 5,704 Bytes
b8b3105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Host tests of the output formats (standard library only): the official ``save_results`` Markdown rules, the strict
box parser (never ``eval``), pixel boxes and the JSON format.

    TT_VISIBLE_DEVICES=none python -m pytest -q code/tt_dsocr/tests/test_host_postprocess.py
"""

from __future__ import annotations

import json
import os
import re
import sys

import pytest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from tt_dsocr import postprocess as PP  # noqa: E402

EOS = "<|end▁of▁sentence|>"
DOC = ("<|ref|>title<|/ref|><|det|>[[52, 40, 948, 98]]<|/det|>\n# Report\n\n"
       "<|ref|>text<|/ref|><|det|>[[52, 120, 948, 300]]<|/det|>\nLet $a \\coloneqq b$ and $c \\eqqcolon d$.\n\n"
       "<|ref|>image<|/ref|><|det|>[[100, 400, 500, 800]]<|/det|>\n\n"
       "<|ref|>image<|/ref|><|det|>[[600, 400, 900, 800], [10, 10, 20, 20]]<|/det|>\n"
       "<|ref|>table<|/ref|><|det|>[[52, 820, 948, 960]]<|/det|>\n<table><tr><td>1</td></tr></table>" + EOS)


def official_markdown(outputs: str) -> str:
    """The official infer(save_results=True) text, transcribed from modeling_deepseekocr.py (re_match + the two
    replacement loops) for comparison (no eval is needed for the text)."""
    stop_str = "<|end▁of▁sentence|>"
    if outputs.endswith(stop_str):
        outputs = outputs[:-len(stop_str)]
    outputs = outputs.strip()
    pattern = r'(<\|ref\|>(.*?)<\|/ref\|><\|det\|>(.*?)<\|/det\|>)'
    matches = re.findall(pattern, outputs, re.DOTALL)
    mathes_image, mathes_other = [], []
    for a_match in matches:
        if '<|ref|>image<|/ref|>' in a_match[0]:
            mathes_image.append(a_match[0])
        else:
            mathes_other.append(a_match[0])
    for idx, a_match_image in enumerate(mathes_image):
        outputs = outputs.replace(a_match_image, '![](images/' + str(idx) + '.jpg)\n')
    for idx, a_match_other in enumerate(mathes_other):
        outputs = outputs.replace(a_match_other, '').replace('\\coloneqq', ':=').replace('\\eqqcolon', '=:')
    return outputs


@pytest.mark.parametrize("text", [
    DOC, "  plain text \\coloneqq without tags  ", "", EOS, "<|ref|>image<|/ref|><|det|>[[1, 2, 3, 4]]<|/det|>",
    "a<|ref|>text<|/ref|><|det|>[[1,2,3,4]]<|/det|>b<|ref|>text<|/ref|><|det|>[[1,2,3,4]]<|/det|>c",
    "<|ref|>multi\nline<|/ref|><|det|>[[0, 0, 999, 999]]<|/det|>\n\\eqqcolon",
    "<|ref|>broken<|/ref|><|det|>[[1, 2, 3]]<|/det|> rest", "<|ref|>unterminated<|/ref|><|det|>[[1, 2, 3, 4]]"])
def test_markdown_equals_the_official_rules(text):
    assert PP.to_markdown(text) == official_markdown(text)


def test_markdown_details():
    md = PP.to_markdown(DOC)
    assert md.startswith("\n# Report") and "![](images/0.jpg)\n" in md and "![](images/1.jpg)\n" in md
    assert ":= b" in md and "=: d" in md and "<|ref|>" not in md and "<|det|>" not in md and EOS not in md
    assert md.endswith("<table><tr><td>1</td></tr></table>")
    # the official code replaces \coloneqq only while removing a non-image group
    assert PP.to_markdown("x \\coloneqq y") == "x \\coloneqq y"
    # task "ocr": the labels are the recognized text, kept
    ocr = "<|ref|>Hello world<|/ref|><|det|>[[1, 2, 3, 4]]<|/det|>\n<|ref|>Line 2<|/ref|><|det|>[[5, 6, 7, 8]]<|/det|>"
    assert PP.to_markdown(ocr) == "\n" and PP.to_markdown(ocr, keep_labels=True) == "Hello world\nLine 2"


def test_parse_boxes_is_strict():
    assert PP.parse_boxes("[[1, 2, 3, 4]]") == [[1, 2, 3, 4]]
    assert PP.parse_boxes(" [[1,2,3,4], [5, 6, 7, 8.5]] ") == [[1, 2, 3, 4], [5, 6, 7, 8.5]]
    assert PP.parse_boxes("[[0, 0, 999, 999],]") == [[0, 0, 999, 999]]
    for bad in ("[[1, 2, 3]]", "[1, 2, 3, 4]", "[[1, 2, 3, 4, 5]]", "__import__('os').system('id')",
                "[[1, 2, 3, 4]] + [[5, 6, 7, 8]]", "[[1e9, 2, 3, 4]]", "[[a, 2, 3, 4]]", "[]", "", "[[[1, 2, 3, 4]]]",
                "[[1, 2, 3, 4]]" * 2, "[[1, 2, 3, 0x10]]", None, "[[" + "1, " * 5000 + "1]]"):
        assert PP.parse_boxes(bad) is None, bad


def test_extract_refs_pixels():
    refs = PP.extract_refs(DOC, 1000, 500)
    assert [r["label"] for r in refs] == ["title", "text", "image", "image", "table"]
    assert refs[0]["boxes_norm"] == [[52, 40, 948, 98]]
    assert refs[0]["boxes"] == [[int(52 / 999 * 1000), int(40 / 999 * 500), int(948 / 999 * 1000),
                                 int(98 / 999 * 500)]]
    assert refs[3]["boxes"] == [[600, 200, 900, 400], [10, 5, 20, 10]]
    assert PP.extract_refs(DOC, 999, 999)[2]["boxes"] == [[100, 400, 500, 800]]
    r = PP.extract_refs("<|ref|>x<|/ref|><|det|>oops<|/det|>", 100, 100)
    assert r == [{"label": "x", "boxes": [], "boxes_norm": [], "error": r[0]["error"]}] and r[0]["error"]
    assert PP.extract_refs("no tags", 10, 10) == []


def test_apply_format():
    raw = PP.strip_eos(DOC)
    assert PP.apply_format(raw, "markdown", "raw", (1000, 500))[0] == raw
    md, obj, refs = PP.apply_format(raw, "markdown", "markdown", (1000, 500))
    assert md == PP.to_markdown(raw) and obj is None and len(refs) == 5
    text, obj, refs = PP.apply_format(raw, "markdown", "json", (1000, 500))
    assert json.loads(text) == obj and obj["text"] == md and obj["refs"] == refs
    assert obj["image"] == {"width": 1000, "height": 500}
    loc = "<|ref|>the cat<|/ref|><|det|>[[100, 200, 300, 400]]<|/det|>"
    text, obj, _ = PP.apply_format(loc, "locate", "json", (999, 999))
    assert obj["refs"] == [{"label": "the cat", "boxes": [[100, 200, 300, 400]], "boxes_norm": [[100, 200, 300, 400]]}]
    with pytest.raises(ValueError):
        PP.apply_format(raw, "markdown", "xml", (1, 1))
    assert PP.strip_eos("abc" + EOS + EOS) == "abc"