Spaces:
Runtime error
Runtime error
Commit
·
3d948a1
1
Parent(s):
5406446
temp: attempt - force to png with pillow
Browse files
medrag_multi_modal/document_loader/image_loader/pymupdf_img_loader.py
CHANGED
|
@@ -2,8 +2,8 @@ import os
|
|
| 2 |
from typing import Any, Dict
|
| 3 |
|
| 4 |
import fitz
|
| 5 |
-
from PIL import Image
|
| 6 |
-
|
| 7 |
|
| 8 |
from .base_img_loader import BaseImageLoader
|
| 9 |
|
|
@@ -76,7 +76,7 @@ class PyMuPDFImageLoader(BaseImageLoader):
|
|
| 76 |
image_file_paths = []
|
| 77 |
|
| 78 |
pdf_document = fitz.open(self.document_file_path)
|
| 79 |
-
page = pdf_document
|
| 80 |
|
| 81 |
images = page.get_images(full=True)
|
| 82 |
for img_idx, image in enumerate(images):
|
|
@@ -85,33 +85,33 @@ class PyMuPDFImageLoader(BaseImageLoader):
|
|
| 85 |
image_bytes = base_image["image"]
|
| 86 |
image_ext = base_image["ext"]
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
|
| 116 |
pdf_document.close()
|
| 117 |
|
|
|
|
| 2 |
from typing import Any, Dict
|
| 3 |
|
| 4 |
import fitz
|
| 5 |
+
from PIL import Image, ImageOps, UnidentifiedImageError
|
| 6 |
+
import io
|
| 7 |
|
| 8 |
from .base_img_loader import BaseImageLoader
|
| 9 |
|
|
|
|
| 76 |
image_file_paths = []
|
| 77 |
|
| 78 |
pdf_document = fitz.open(self.document_file_path)
|
| 79 |
+
page = pdf_document.load_page(page_idx)
|
| 80 |
|
| 81 |
images = page.get_images(full=True)
|
| 82 |
for img_idx, image in enumerate(images):
|
|
|
|
| 85 |
image_bytes = base_image["image"]
|
| 86 |
image_ext = base_image["ext"]
|
| 87 |
|
| 88 |
+
try:
|
| 89 |
+
img = Image.open(io.BytesIO(image_bytes))
|
| 90 |
+
|
| 91 |
+
if img.mode in ['1', 'P']:
|
| 92 |
+
img = ImageOps.invert(img.convert('L'))
|
| 93 |
+
|
| 94 |
+
if img.mode == 'CMYK':
|
| 95 |
+
img = img.convert('RGB')
|
| 96 |
+
|
| 97 |
+
if image_ext not in ['png', 'jpg', 'jpeg']:
|
| 98 |
+
image_ext = 'png'
|
| 99 |
+
image_file_name = f"page{page_idx}_fig{img_idx}.png"
|
| 100 |
+
image_file_path = os.path.join(image_save_dir, image_file_name)
|
| 101 |
+
|
| 102 |
+
img.save(image_file_path, format="PNG")
|
| 103 |
+
else:
|
| 104 |
+
image_file_name = f"page{page_idx}_fig{img_idx}.{image_ext}"
|
| 105 |
+
image_file_path = os.path.join(image_save_dir, image_file_name)
|
| 106 |
+
|
| 107 |
+
with open(image_file_path, "wb") as image_file:
|
| 108 |
+
image_file.write(image_bytes)
|
| 109 |
+
|
| 110 |
+
image_file_paths.append(image_file_path)
|
| 111 |
+
|
| 112 |
+
except (UnidentifiedImageError, OSError) as e:
|
| 113 |
+
print(f"Skipping image at page {page_idx}, fig {img_idx} due to an error: {e}")
|
| 114 |
+
continue
|
| 115 |
|
| 116 |
pdf_document.close()
|
| 117 |
|