(
self,
path_or_stream: Union[BytesIO, Path],
format: InputFormat,
backend: Type[AbstractDocumentBackend],
filename: Optional[str] = None,
limits: Optional[DocumentLimits] = None,
)
| 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 |
| 156 | ): |
| 157 | self.page_count = self._backend.page_count() |
| 158 | if not self.page_count <= self.limits.max_num_pages: |
| 159 | self.valid = False |
| 160 | elif self.page_count < self.limits.page_range[0]: |
| 161 | self.valid = False |
| 162 | |
| 163 | except (FileNotFoundError, OSError) as e: |
| 164 | self.valid = False |
| 165 | _log.exception( |
| 166 | f"File {self.file.name} not found or cannot be opened.", exc_info=e |
| 167 | ) |
no test coverage detected