-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathimage_extractor.py
152 lines (128 loc) · 5.4 KB
/
image_extractor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import logging
import os
import subprocess
from uuid import uuid4
from pypdf import PdfReader
from PIL import Image
import io
import sys
def generate_uuid_filename(extension):
return f"{uuid4()}{extension.lower()}"
def ensure_directory_exists(path):
if not os.path.exists(path):
os.makedirs(path)
def extract_images(file_path: str):
output_path = os.path.join(os.path.dirname(file_path), "extracted_images")
_, file_extension = os.path.splitext(file_path)
file_extension = file_extension.lower()
if file_extension == ".pdf":
extract_images_from_pdf(file_path, output_path)
elif file_extension == ".docx":
extract_images_from_docx(file_path, output_path)
elif file_extension == ".pptx":
extract_images_from_pptx(file_path, output_path)
else:
logging.error(f"Unsupported file type: {file_extension}")
def extract_images_from_pdf(pdf_file_path: str, output_path: str):
try:
reader = PdfReader(pdf_file_path)
seen_images = set()
ensure_directory_exists(output_path)
for page in reader.pages:
for image in page.images:
image_data = image.data
image_hash = hash(image_data)
if image_hash in seen_images:
continue
seen_images.add(image_hash)
ext = os.path.splitext(image.name)[1].lower()
if ext == ".jpeg":
ext = ".jpg"
elif ext == ".jp2":
try:
with Image.open(io.BytesIO(image_data)) as img:
if img.mode == "RGBA":
img = img.convert("RGB")
ext = ".png"
image_data = io.BytesIO()
img.save(image_data, format="PNG")
image_data = image_data.getvalue()
except Exception as e:
logging.error(f"Failed to convert JP2 to PNG: {e}")
continue
image_filename = generate_uuid_filename(ext)
file_path = os.path.join(output_path, image_filename)
with open(file_path, "wb") as fp:
fp.write(image_data)
except Exception as e:
logging.error(f"Failed to extract images from {pdf_file_path}: {e}")
def extract_images_from_docx(docx_file_path: str, output_path: str):
try:
ensure_directory_exists(output_path)
subprocess.run(
["unzip", "-j", docx_file_path, "word/media/*", "-d", output_path],
check=True,
shell=False,
)
for filename in os.listdir(output_path):
original_path = os.path.join(output_path, filename)
_, ext = os.path.splitext(filename)
if ext.lower() == ".jpeg":
ext = ".jpg"
elif ext.lower() == ".jp2":
try:
with Image.open(original_path) as img:
if img.mode == "RGBA":
img = img.convert("RGB")
ext = ".png"
img.save(original_path, format="PNG")
except Exception as e:
logging.error(f"Failed to convert JP2 to PNG: {e}")
os.remove(original_path)
continue
new_filename = generate_uuid_filename(ext)
new_path = os.path.join(output_path, new_filename)
os.rename(original_path, new_path)
except Exception as e:
logging.error(f"Failed to extract images from {docx_file_path}: {e}")
def extract_images_from_pptx(pptx_file_path: str, output_path: str):
try:
ensure_directory_exists(output_path)
subprocess.run(
["unzip", "-j", pptx_file_path, "ppt/media/*", "-d", output_path],
check=True,
shell=False,
)
valid_extensions = {".jpg", ".jpeg", ".png", ".jp2"}
for filename in os.listdir(output_path):
original_path = os.path.join(output_path, filename)
_, ext = os.path.splitext(filename)
if ext.lower() == ".jpeg":
ext = ".jpg"
elif ext.lower() == ".jp2":
try:
with Image.open(original_path) as img:
if img.mode == "RGBA":
img = img.convert("RGB")
ext = ".png"
img.save(original_path, format="PNG")
except Exception as e:
logging.error(f"Failed to convert JP2 to PNG: {e}")
os.remove(original_path)
continue
if ext.lower() in valid_extensions:
new_filename = generate_uuid_filename(ext)
new_path = os.path.join(output_path, new_filename)
os.rename(original_path, new_path)
else:
os.remove(original_path)
except subprocess.CalledProcessError as e:
logging.error(f"Failed to unzip and extract images from {pptx_file_path}: {e}")
except Exception as e:
logging.error(f"An error occurred while processing {pptx_file_path}: {e}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python extract_images.py <file_path>")
sys.exit(1)
file_path = sys.argv[1]
extract_images(file_path)