86 lines
2.6 KiB
Python
86 lines
2.6 KiB
Python
from types import SimpleNamespace
|
|
|
|
from backend.app.ai_parser import (
|
|
_estimate_text_width,
|
|
_estimate_text_width_from_text_matrix,
|
|
_page_horizontal_offset,
|
|
_text_rect_from_matrix,
|
|
)
|
|
|
|
|
|
def test_text_rect_from_matrix_uses_rendered_height_and_baseline() -> None:
|
|
font_size_pt, x0_pt, top_pt, x1_pt, bottom_pt = _text_rect_from_matrix(
|
|
"食品名称: 天问礼品粽 (粽子/草木灰咸鸭蛋)",
|
|
[19.3618, 0.0, 0.0, 21.0, 435.9155, 629.3184],
|
|
942.06,
|
|
None,
|
|
)
|
|
|
|
assert font_size_pt == 21.0
|
|
assert x0_pt == 435.92
|
|
assert top_pt == 291.74
|
|
assert bottom_pt == 312.74
|
|
assert x1_pt > x0_pt
|
|
|
|
|
|
def test_text_rect_from_matrix_handles_small_text_without_collapsing_height() -> None:
|
|
font_size_pt, x0_pt, top_pt, x1_pt, bottom_pt = _text_rect_from_matrix(
|
|
"儿童青少年应避免过量摄入盐油糖。",
|
|
[4.3157, 0.0, 0.0, 8.0, 680.7383741, 516.1778],
|
|
942.06,
|
|
None,
|
|
)
|
|
|
|
assert font_size_pt == 8.0
|
|
assert x0_pt == 680.74
|
|
assert top_pt == 417.88
|
|
assert bottom_pt == 425.88
|
|
assert x1_pt > x0_pt
|
|
|
|
|
|
def test_text_rect_from_matrix_applies_page_horizontal_offset() -> None:
|
|
font_size_pt, x0_pt, top_pt, x1_pt, bottom_pt = _text_rect_from_matrix(
|
|
"材质:",
|
|
[7.0652, 0.0, 0.0, 12.36, 190.6111, 873.561],
|
|
942.06,
|
|
None,
|
|
24.21,
|
|
)
|
|
|
|
assert font_size_pt == 12.36
|
|
assert x0_pt == 166.4
|
|
assert top_pt == 56.14
|
|
assert bottom_pt == 68.5
|
|
assert x1_pt > x0_pt
|
|
|
|
|
|
def test_page_horizontal_offset_uses_artbox_left_inset() -> None:
|
|
page = SimpleNamespace(
|
|
artbox=SimpleNamespace(left=24.2137, width=1314.7563),
|
|
cropbox=SimpleNamespace(width=1363.4),
|
|
)
|
|
|
|
assert _page_horizontal_offset(page) == 24.2137
|
|
|
|
|
|
def test_text_matrix_width_is_tighter_than_fallback_for_food_name() -> None:
|
|
text = "食品名称: 天问礼品粽 (粽子/草木灰咸鸭蛋)"
|
|
reference_width = 374.51
|
|
|
|
fallback_width = round(_estimate_text_width(text, 21.0), 2)
|
|
matrix_width = round(_estimate_text_width_from_text_matrix(text, 19.3618) or 0.0, 2)
|
|
|
|
assert matrix_width > 0
|
|
assert abs(matrix_width - reference_width) < abs(fallback_width - reference_width)
|
|
|
|
|
|
def test_text_matrix_width_is_tighter_than_fallback_for_small_heading() -> None:
|
|
text = "营养成分表"
|
|
reference_width = 21.75
|
|
|
|
fallback_width = round(_estimate_text_width(text, 8.0), 2)
|
|
matrix_width = round(_estimate_text_width_from_text_matrix(text, 4.3157) or 0.0, 2)
|
|
|
|
assert matrix_width > 0
|
|
assert abs(matrix_width - reference_width) <= abs(fallback_width - reference_width)
|