Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion parse_document_model/attributes.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from abc import ABC
from typing import Optional

from pydantic import BaseModel
from pydantic import BaseModel, Field, field_validator


class BoundingBox(BaseModel):
Expand All @@ -25,3 +26,11 @@ class PageAttributes(Attributes):

class TextAttributes(Attributes):
bounding_box: list[BoundingBox] = []
level: Optional[int] = Field(None, gw=1, le=4)

@field_validator('level')
@classmethod
def check_level(cls, v) -> int:
if v is not None and v not in range(1, 5):
raise ValueError("Level must be between 1 and 4 or None")
return v
33 changes: 33 additions & 0 deletions test/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,36 @@ def test_url_marks():
else:
with pytest.raises(ValueError):
UrlMark(**mark_json)


def test_text_attributes_level():
valid_text_attributes = [
{"bounding_box": [], "level": 1},
{"bounding_box": [], "level": 2},
{"bounding_box": [], "level": 3},
{"bounding_box": [], "level": 4},
{"bounding_box": [], "level": None},
{"bounding_box": []},
{}
]

for attributes_json in valid_text_attributes:
text_attributes = TextAttributes(**attributes_json)
assert isinstance(text_attributes, TextAttributes)
assert isinstance(text_attributes.level, (int, type(None)))
if text_attributes.level is not None:
assert text_attributes.level in range(1, 5)
assert attributes_json["level"] == text_attributes.level
else:
assert "level" not in attributes_json or attributes_json["level"] is None

invalid_text_attributes = [
{"bounding_box": [], "level": -1},
{"bounding_box": [], "level": "invalid"},
{"bounding_box": [], "level": 2.5},
{"bounding_box": [], "level": 5},
]

for attributes_json in invalid_text_attributes:
with pytest.raises(ValueError):
TextAttributes(**attributes_json)