r"""Creates a PdfFile object from a BytesIO object. Args: file (BytesIO): A BytesIO object representing the contents of the pdf file. filename (str): The name of the file. Returns: PdfFile: A PdfFile object.
(cls, file: BytesIO, filename: str)
| 191 | class PdfFile(File): |
| 192 | @classmethod |
| 193 | def from_bytes(cls, file: BytesIO, filename: str) -> "PdfFile": |
| 194 | r"""Creates a PdfFile object from a BytesIO object. |
| 195 | |
| 196 | Args: |
| 197 | file (BytesIO): A BytesIO object representing the contents of the |
| 198 | pdf file. |
| 199 | filename (str): The name of the file. |
| 200 | |
| 201 | Returns: |
| 202 | PdfFile: A PdfFile object. |
| 203 | """ |
| 204 | # Use fitz to extract text from pdf files |
| 205 | try: |
| 206 | import fitz |
| 207 | except ImportError: |
| 208 | raise ImportError( |
| 209 | "Please install `PyMuPDF` first. " |
| 210 | "You can install it by running " |
| 211 | "`pip install PyMuPDF`." |
| 212 | ) |
| 213 | pdf = fitz.open(stream=file.read(), filetype="pdf") |
| 214 | docs = [] |
| 215 | for i, page in enumerate(pdf): |
| 216 | text = page.get_text(sort=True) |
| 217 | text = strip_consecutive_newlines(text) |
| 218 | # Create a dictionary with the extracted text |
| 219 | doc = {"page_content": text.strip(), "page": i + 1} |
| 220 | docs.append(doc) |
| 221 | # Calculate a unique identifier for the file |
| 222 | file_id = md5(file.getvalue()).hexdigest() |
| 223 | # Reset the file pointer to the beginning |
| 224 | file.seek(0) |
| 225 | return cls( |
| 226 | name=filename, |
| 227 | file_id=file_id, |
| 228 | docs=docs, |
| 229 | raw_bytes=file.getvalue(), |
| 230 | ) |
| 231 | |
| 232 | |
| 233 | class TxtFile(File): |
nothing calls this directly
no test coverage detected