Spaces:
Sleeping
Sleeping
""" | |
Модуль содержит класс для представления текстовых блоков документа. | |
""" | |
from dataclasses import asdict, dataclass, field | |
from typing import Any, Callable | |
from .parsed_structure import DocumentElement | |
class TextStyle: | |
""" | |
Стиль текстового блока. | |
""" | |
# Стиль параграфа | |
paragraph_style: str = "" | |
paragraph_style_name: str = "" | |
alignment: str = "" | |
# Автонумерация | |
has_numbering: bool = False | |
numbering_level: int = 0 | |
numbering_id: str = "" | |
numbering_format: str = "" # decimal, bullet, roman, etc. | |
# Флаги для bold | |
fully_bold: bool = False | |
partly_bold: bool = False | |
# Флаги для italic | |
fully_italic: bool = False | |
partly_italic: bool = False | |
# Флаги для underline | |
fully_underlined: bool = False | |
partly_underlined: bool = False | |
def to_dict(self) -> dict[str, Any]: | |
""" | |
Преобразует стиль в словарь. | |
Returns: | |
dict[str, Any]: Словарное представление стиля. | |
""" | |
return asdict(self) | |
class ParsedTextBlock(DocumentElement): | |
""" | |
Текстовый блок документа. | |
""" | |
text: str = "" | |
style: TextStyle = field(default_factory=TextStyle) | |
anchors: list[str] = field(default_factory=list) # Список идентификаторов якорей (закладок) | |
links: list[str] = field(default_factory=list) # Список идентификаторов ссылок | |
# Технические метаданные о блоке | |
metadata: list[dict[str, Any]] = field(default_factory=list) # Для хранения технической информации | |
# Примечания и сноски к тексту | |
footnotes: list[dict[str, Any]] = field(default_factory=list) # Для хранения сносок | |
title_of_table: int | None = None | |
def to_string(self) -> str: | |
""" | |
Преобразует текстовый блок в строковое представление. | |
Returns: | |
str: Текст блока. | |
""" | |
return self.text | |
def apply(self, func: Callable[[str], str]) -> None: | |
""" | |
Применяет функцию к тексту блока. | |
Args: | |
func (Callable[[str], str]): Функция для применения к тексту. | |
""" | |
self.text = func(self.text) | |
# Применяем к текстовым значениям в метаданных | |
if isinstance(self.metadata, list): | |
for item in self.metadata: | |
if isinstance(item, dict) and 'text' in item: | |
item['text'] = func(item['text']) | |
# Применяем к сноскам | |
if isinstance(self.footnotes, list): | |
for note in self.footnotes: | |
if isinstance(note, dict) and 'text' in note: | |
note['text'] = func(note['text']) | |
def to_dict(self) -> dict[str, Any]: | |
""" | |
Преобразует текстовый блок в словарь. | |
Returns: | |
dict[str, Any]: Словарное представление текстового блока. | |
""" | |
result = { | |
'text': self.text, | |
'style': self.style.to_dict(), | |
'anchors': self.anchors, | |
'links': self.links, | |
'metadata': self.metadata, | |
'footnotes': self.footnotes, | |
'page_number': self.page_number, | |
'index_in_document': self.index_in_document, | |
'title_of_table': self.title_of_table, | |
} | |
return result | |