Skip to content

trading_agent.attachments.text_reader

The base of the classes that turn one kind of document into plain text.

Each document format has its own reader in its own file: PDF, Word, Excel, and plain text such as CSV, Markdown and JSON. They share only this base, which says which file endings a reader takes and what it returns.

Typical usage example:

extracted = PdfTextReader().read(Path('report.pdf'))

TextReadError

Bases: ValueError

A document could not be read as text.

ExtractedText dataclass

ExtractedText(text, page_count=None)

The text read from one document.

Attributes:

Name Type Description
text str

The document's text.

page_count int | None

How many pages it has, for formats with pages, or None.

TextReader

Bases: ABC

Reads documents of one format.

Attributes:

Name Type Description
extensions tuple[str, ...]

The lower-case file endings this reader takes, such as ".pdf".

media_type

The media type of those files, used when the sender gave none.

takes

takes(file_name)

Says whether this reader reads a file of this name.

Parameters:

Name Type Description Default
file_name str

The file's name.

required

Returns:

Type Description
bool

True when the name ends with one of the reader's endings.

Source code in src/trading_agent/attachments/text_reader.py
def takes(self, file_name: str) -> bool:
    """Says whether this reader reads a file of this name.

    Args:
        file_name (str): The file's name.

    Returns:
        bool: True when the name ends with one of the reader's endings.
    """
    return Path(file_name).suffix.lower() in self.extensions

read abstractmethod

read(path)

Reads a document's text.

Parameters:

Name Type Description Default
path Path

The document.

required

Returns:

Type Description
ExtractedText

Its text.

Raises:

Type Description
TextReadError

The file is damaged, protected or not of this format.

Source code in src/trading_agent/attachments/text_reader.py
@abc.abstractmethod
def read(self, path: Path) -> ExtractedText:
    """Reads a document's text.

    Args:
        path (Path): The document.

    Returns:
        ExtractedText: Its text.

    Raises:
        TextReadError: The file is damaged, protected or not of this format.
    """