| 96 | |
| 97 | |
| 98 | class InputDocument(BaseModel): |
| 99 | file: PurePath |
| 100 | document_hash: str # = None |
| 101 | valid: bool = True |
| 102 | limits: DocumentLimits = DocumentLimits() |
| 103 | format: InputFormat # = None |
| 104 | |
| 105 | filesize: Optional[int] = None |
| 106 | page_count: int = 0 |
| 107 | |
| 108 | _backend: AbstractDocumentBackend # Internal PDF backend used |
| 109 | |
| 110 | def __init__( |
| 111 | self, |
| 112 | path_or_stream: Union[BytesIO, Path], |
| 113 | format: InputFormat, |
| 114 | backend: Type[AbstractDocumentBackend], |
| 115 | filename: Optional[str] = None, |
| 116 | limits: Optional[DocumentLimits] = None, |
| 117 | ): |
| 118 | super().__init__( |
| 119 | file="", document_hash="", format=InputFormat.PDF |
| 120 | ) # initialize with dummy values |
| 121 | |
| 122 | self.limits = limits or DocumentLimits() |
| 123 | self.format = format |
| 124 | |
| 125 | try: |
| 126 | if isinstance(path_or_stream, Path): |
| 127 | self.file = path_or_stream |
| 128 | self.filesize = path_or_stream.stat().st_size |
| 129 | if self.filesize > self.limits.max_file_size: |
| 130 | self.valid = False |
| 131 | else: |
| 132 | self.document_hash = create_file_hash(path_or_stream) |
| 133 | self._init_doc(backend, path_or_stream) |
| 134 | |
| 135 | elif isinstance(path_or_stream, BytesIO): |
| 136 | assert ( |
| 137 | filename is not None |
| 138 | ), "Can't construct InputDocument from stream without providing filename arg." |
| 139 | self.file = PurePath(filename) |
| 140 | self.filesize = path_or_stream.getbuffer().nbytes |
| 141 | |
| 142 | if self.filesize > self.limits.max_file_size: |
| 143 | self.valid = False |
| 144 | else: |
| 145 | self.document_hash = create_file_hash(path_or_stream) |
| 146 | self._init_doc(backend, path_or_stream) |
| 147 | else: |
| 148 | raise RuntimeError( |
| 149 | f"Unexpected type path_or_stream: {type(path_or_stream)}" |
| 150 | ) |
| 151 | |
| 152 | # For paginated backends, check if the maximum page count is exceeded. |
| 153 | if self.valid and self._backend.is_valid(): |
| 154 | if self._backend.supports_pagination() and isinstance( |
| 155 | self._backend, PaginatedDocumentBackend |
no test coverage detected