Update app.py
Browse files
app.py
CHANGED
@@ -17,26 +17,57 @@ def trim_whitespace(image):
|
|
17 |
return trimmed_image
|
18 |
|
19 |
def convert_pdf_to_images(pdf_path, zoom=2):
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
|
|
29 |
return images
|
30 |
|
31 |
-
|
32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
images = []
|
34 |
-
|
35 |
-
|
36 |
-
image
|
37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
return images
|
39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
def remove_background_from_image(image):
|
41 |
return remove(image)
|
42 |
|
|
|
17 |
return trimmed_image
|
18 |
|
19 |
def convert_pdf_to_images(pdf_path, zoom=2):
|
20 |
+
try:
|
21 |
+
|
22 |
+
pdf_document = fitz.open(pdf_path)
|
23 |
+
name_with_extension = os.path.basename(pdf_path)
|
24 |
+
name = os.path.splitext(name_with_extension)[0]
|
25 |
+
images = []
|
26 |
+
for page_num in range(len(pdf_document)):
|
27 |
+
page = pdf_document.load_page(page_num)
|
28 |
+
matrix = fitz.Matrix(zoom, zoom)
|
29 |
+
pix = page.get_pixmap(matrix=matrix)
|
30 |
+
image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
31 |
+
trimmed_image = trim_whitespace(image)
|
32 |
+
images.append(trimmed_image)
|
33 |
return images
|
34 |
|
35 |
+
import os
|
36 |
+
from io import BytesIO
|
37 |
+
from docx import Document
|
38 |
+
from PIL import Image
|
39 |
+
|
40 |
+
def convert_docx_to_jpeg(docx_bytes):
|
41 |
+
"""
|
42 |
+
Convert each image in a DOCX file to a separate JPEG image and return them as a list.
|
43 |
+
|
44 |
+
Args:
|
45 |
+
- docx_bytes: The binary content of the DOCX file.
|
46 |
+
|
47 |
+
Returns:
|
48 |
+
- A list of PIL Image objects in JPEG format.
|
49 |
+
"""
|
50 |
+
document = Document(BytesIO(docx_bytes))
|
51 |
images = []
|
52 |
+
|
53 |
+
for rel in document.part.rels.values():
|
54 |
+
if "image" in rel.target_ref:
|
55 |
+
image_stream = rel.target_part.blob
|
56 |
+
image = Image.open(BytesIO(image_stream))
|
57 |
+
jpeg_image = BytesIO()
|
58 |
+
image.convert('RGB').save(jpeg_image, format="JPEG")
|
59 |
+
jpeg_image.seek(0)
|
60 |
+
images.append(Image.open(jpeg_image))
|
61 |
+
|
62 |
return images
|
63 |
|
64 |
+
# Example usage:
|
65 |
+
# with open("example.docx", "rb") as f:
|
66 |
+
# docx_bytes = f.read()
|
67 |
+
# images = convert_docx_to_jpeg(docx_bytes)
|
68 |
+
# for img in images:
|
69 |
+
# img.show()
|
70 |
+
|
71 |
def remove_background_from_image(image):
|
72 |
return remove(image)
|
73 |
|