sidebar-pptx-generator/scripts/doc_image_extractor.py
12.1 KB| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | doc_image_extractor.py |
| 4 | |
| 5 | 从多种文档格式中提取内嵌图片。 |
| 6 | 支持格式:PPTX、DOCX、XLSX |
| 7 | |
| 8 | 依赖安装: |
| 9 | pip install PyMuPDF python-pptx python-docx openpyxl |
| 10 | |
| 11 | 用法: |
| 12 | # 单个文件 |
| 13 | python doc_image_extractor.py <文档路径> [输出目录] |
| 14 | |
| 15 | # 多个文件 |
| 16 | python doc_image_extractor.py file1.pdf file2.pptx file3.docx [输出目录] |
| 17 | |
| 18 | # 批量扫描目录 |
| 19 | python doc_image_extractor.py --dir <目录路径> [输出目录] |
| 20 | python doc_image_extractor.py -d <目录路径> [输出目录] |
| 21 | """ |
| 22 | |
| 23 | import sys |
| 24 | import os |
| 25 | import argparse |
| 26 | from pathlib import Path |
| 27 | from typing import Optional, List, Dict |
| 28 | |
| 29 | MIN_IMAGE_SIZE = 100 * 1024 |
| 30 | |
| 31 | # -------------------- 依赖检查 -------------------- |
| 32 | |
| 33 | def _require(package_name: str, install_cmd: str): |
| 34 | """尝试导入包,失败时提示安装并退出。""" |
| 35 | try: |
| 36 | __import__(package_name) |
| 37 | except ImportError: |
| 38 | print(f"❌ 缺少依赖: {package_name}") |
| 39 | print(f" 请运行: {install_cmd}") |
| 40 | sys.exit(1) |
| 41 | |
| 42 | |
| 43 | # -------------------- PPTX 图片提取 -------------------- |
| 44 | |
| 45 | def extract_images_from_pptx(filepath: str, output_dir: str) -> int: |
| 46 | """使用 python-pptx 从 PPTX 中提取图片。""" |
| 47 | _require("pptx", "pip install python-pptx") |
| 48 | from pptx import Presentation |
| 49 | |
| 50 | prs = Presentation(filepath) |
| 51 | image_count = 0 |
| 52 | |
| 53 | for slide_num, slide in enumerate(prs.slides, start=1): |
| 54 | for shape in slide.shapes: |
| 55 | if hasattr(shape, "image") and shape.image: |
| 56 | try: |
| 57 | image = shape.image |
| 58 | image_bytes = image.blob |
| 59 | # 跳过过小图片 |
| 60 | if len(image_bytes) < MIN_IMAGE_SIZE: |
| 61 | continue |
| 62 | |
| 63 | # 确定扩展名 |
| 64 | content_type = image.content_type |
| 65 | ext = content_type.split("/")[-1] if "/" in content_type else "png" |
| 66 | if ext == "jpeg": |
| 67 | ext = "jpg" |
| 68 | |
| 69 | image_count += 1 |
| 70 | image_filename = f"pptx_s{slide_num}_img{image_count}.{ext}" |
| 71 | image_path = os.path.join(output_dir, image_filename) |
| 72 | with open(image_path, "wb") as f: |
| 73 | f.write(image_bytes) |
| 74 | except Exception: |
| 75 | continue |
| 76 | |
| 77 | return image_count |
| 78 | |
| 79 | |
| 80 | # -------------------- DOCX 图片提取 -------------------- |
| 81 | |
| 82 | def extract_images_from_docx(filepath: str, output_dir: str) -> int: |
| 83 | """使用 python-docx 从 DOCX 中提取图片。""" |
| 84 | _require("docx", "pip install python-docx") |
| 85 | from docx import Document |
| 86 | |
| 87 | doc = Document(filepath) |
| 88 | image_count = 0 |
| 89 | |
| 90 | for rel in doc.part.rels.values(): |
| 91 | if "image" in rel.reltype: |
| 92 | try: |
| 93 | image = rel.target_part |
| 94 | image_bytes = image.blob |
| 95 | # 跳过过小图片 |
| 96 | if len(image_bytes) < MIN_IMAGE_SIZE: |
| 97 | continue |
| 98 | |
| 99 | # 确定扩展名 |
| 100 | content_type = image.content_type if hasattr(image, "content_type") else "image/png" |
| 101 | ext = content_type.split("/")[-1] if "/" in content_type else "png" |
| 102 | if ext == "jpeg": |
| 103 | ext = "jpg" |
| 104 | |
| 105 | image_count += 1 |
| 106 | image_filename = f"docx_img{image_count}.{ext}" |
| 107 | image_path = os.path.join(output_dir, image_filename) |
| 108 | with open(image_path, "wb") as f: |
| 109 | f.write(image_bytes) |
| 110 | except Exception: |
| 111 | continue |
| 112 | |
| 113 | return image_count |
| 114 | |
| 115 | |
| 116 | # -------------------- XLSX 图片提取 -------------------- |
| 117 | |
| 118 | def extract_images_from_xlsx(filepath: str, output_dir: str) -> int: |
| 119 | """使用 openpyxl 从 XLSX 中提取图片。""" |
| 120 | _require("openpyxl", "pip install openpyxl") |
| 121 | from openpyxl import load_workbook |
| 122 | |
| 123 | wb = load_workbook(filepath) |
| 124 | image_count = 0 |
| 125 | |
| 126 | for sheet_name in wb.sheetnames: |
| 127 | sheet = wb[sheet_name] |
| 128 | if hasattr(sheet, "_images"): |
| 129 | for img in sheet._images: |
| 130 | try: |
| 131 | image_bytes = img._data() |
| 132 | if len(image_bytes) < MIN_IMAGE_SIZE: |
| 133 | continue |
| 134 | |
| 135 | # 确定扩展名 |
| 136 | ext = img.format.lower() if img.format else "png" |
| 137 | if ext == "jpeg": |
| 138 | ext = "jpg" |
| 139 | |
| 140 | image_count += 1 |
| 141 | image_filename = f"xlsx_{sheet_name}_img{image_count}.{ext}" |
| 142 | # 清理文件名中的非法字符 |
| 143 | image_filename = "".join(c if c.isalnum() or c in "._-" else "_" for c in image_filename) |
| 144 | image_path = os.path.join(output_dir, image_filename) |
| 145 | with open(image_path, "wb") as f: |
| 146 | f.write(image_bytes) |
| 147 | except Exception: |
| 148 | continue |
| 149 | |
| 150 | return image_count |
| 151 | |
| 152 | |
| 153 | # -------------------- 核心数据 -------------------- |
| 154 | |
| 155 | SUPPORTED_FORMATS = { |
| 156 | ".pptx": extract_images_from_pptx, |
| 157 | ".docx": extract_images_from_docx, |
| 158 | ".xlsx": extract_images_from_xlsx, |
| 159 | } |
| 160 | |
| 161 | |
| 162 | def scan_directory(directory: str) -> List[str]: |
| 163 | """扫描目录中所有支持的文档文件(不包含子目录)。""" |
| 164 | files = [] |
| 165 | for entry in os.listdir(directory): |
| 166 | path = os.path.join(directory, entry) |
| 167 | if os.path.isfile(path) and Path(path).suffix.lower() in SUPPORTED_FORMATS: |
| 168 | files.append(path) |
| 169 | return files |
| 170 | |
| 171 | |
| 172 | def extract_images_from_file(filepath: str, output_dir: str) -> int: |
| 173 | """从单个文件中提取图片。""" |
| 174 | filepath = os.path.abspath(filepath) |
| 175 | if not os.path.exists(filepath): |
| 176 | raise FileNotFoundError(f"文件不存在: {filepath}") |
| 177 | |
| 178 | ext = Path(filepath).suffix.lower() |
| 179 | if ext not in SUPPORTED_FORMATS: |
| 180 | raise ValueError( |
| 181 | f"不支持的文件格式: {ext}\n" |
| 182 | f"支持的格式: {', '.join(SUPPORTED_FORMATS.keys())}" |
| 183 | ) |
| 184 | |
| 185 | os.makedirs(output_dir, exist_ok=True) |
| 186 | extractor = SUPPORTED_FORMATS[ext] |
| 187 | return extractor(filepath, output_dir) |
| 188 | |
| 189 | |
| 190 | def extract_images( |
| 191 | inputs: List[str], |
| 192 | output_dir: str, |
| 193 | flat: bool = False |
| 194 | ) -> Dict[str, int]: |
| 195 | """ |
| 196 | 批量提取图片。 |
| 197 | |
| 198 | 参数: |
| 199 | inputs: 文件路径或目录路径列表 |
| 200 | output_dir: 根输出目录 |
| 201 | flat: 为 True 时所有图片输出到同一目录;为 False 时按文件名分子目录 |
| 202 | |
| 203 | 返回: |
| 204 | {文件路径: 提取图片数量} |
| 205 | """ |
| 206 | results = {} |
| 207 | |
| 208 | # 收集所有文件 |
| 209 | all_files = [] |
| 210 | for item in inputs: |
| 211 | item = os.path.abspath(item) |
| 212 | if os.path.isdir(item): |
| 213 | files = scan_directory(item) |
| 214 | all_files.extend(files) |
| 215 | if not files: |
| 216 | print(f"⚠️ 目录中未找到支持的文档: {item}") |
| 217 | elif os.path.isfile(item): |
| 218 | all_files.append(item) |
| 219 | else: |
| 220 | print(f"⚠️ 路径不存在或不是文件/目录: {item}") |
| 221 | |
| 222 | if not all_files: |
| 223 | print("⚠️ 没有找到可处理的文件") |
| 224 | return results |
| 225 | |
| 226 | # 去重并保持顺序 |
| 227 | seen = set() |
| 228 | unique_files = [f for f in all_files if not (f in seen or seen.add(f))] |
| 229 | |
| 230 | total_files = len(unique_files) |
| 231 | print(f"📦 共发现 {total_files} 个待处理文件") |
| 232 | print("=" * 50) |
| 233 | |
| 234 | # 如果输出目录不存在,提示正在创建 |
| 235 | output_dir = os.path.abspath(output_dir) |
| 236 | if not os.path.exists(output_dir): |
| 237 | print(f"📁 输出目录不存在,正在创建: {output_dir}") |
| 238 | os.makedirs(output_dir, exist_ok=True) |
| 239 | total_images = 0 |
| 240 | |
| 241 | for idx, filepath in enumerate(unique_files, start=1): |
| 242 | basename = Path(filepath).stem |
| 243 | ext = Path(filepath).suffix.lower() |
| 244 | |
| 245 | if flat: |
| 246 | # 所有图片放一起,文件名加前缀区分 |
| 247 | file_output_dir = output_dir |
| 248 | prefix = f"{basename}_" |
| 249 | else: |
| 250 | # 每个文件一个子目录 |
| 251 | file_output_dir = os.path.join(output_dir, basename) |
| 252 | prefix = "" |
| 253 | |
| 254 | print(f"\n[{idx}/{total_files}] 📄 {filepath}") |
| 255 | print(f" 输出到: {file_output_dir}") |
| 256 | |
| 257 | try: |
| 258 | # 创建临时子目录(flat 模式下不需要) |
| 259 | if not flat: |
| 260 | os.makedirs(file_output_dir, exist_ok=True) |
| 261 | |
| 262 | # 提取到临时目录,再重命名(flat 模式下需要加前缀) |
| 263 | import tempfile |
| 264 | tmp_dir = tempfile.mkdtemp() |
| 265 | count = extract_images_from_file(filepath, tmp_dir) |
| 266 | |
| 267 | if flat and count > 0: |
| 268 | # flat 模式:把文件移到根目录并加前缀 |
| 269 | for fname in os.listdir(tmp_dir): |
| 270 | src = os.path.join(tmp_dir, fname) |
| 271 | dst = os.path.join(file_output_dir, f"{prefix}{fname}") |
| 272 | # 处理重名 |
| 273 | counter = 1 |
| 274 | orig_dst = dst |
| 275 | while os.path.exists(dst): |
| 276 | stem = Path(orig_dst).stem |
| 277 | suffix = Path(orig_dst).suffix |
| 278 | dst = os.path.join(file_output_dir, f"{stem}_{counter}{suffix}") |
| 279 | counter += 1 |
| 280 | os.rename(src, dst) |
| 281 | os.rmdir(tmp_dir) |
| 282 | elif count > 0: |
| 283 | # 子目录模式:直接移过去 |
| 284 | for fname in os.listdir(tmp_dir): |
| 285 | src = os.path.join(tmp_dir, fname) |
| 286 | dst = os.path.join(file_output_dir, fname) |
| 287 | counter = 1 |
| 288 | orig_dst = dst |
| 289 | while os.path.exists(dst): |
| 290 | stem = Path(orig_dst).stem |
| 291 | suffix = Path(orig_dst).suffix |
| 292 | dst = os.path.join(file_output_dir, f"{stem}_{counter}{suffix}") |
| 293 | counter += 1 |
| 294 | os.rename(src, dst) |
| 295 | os.rmdir(tmp_dir) |
| 296 | else: |
| 297 | # 没提取到图片,清理临时目录 |
| 298 | import shutil |
| 299 | shutil.rmtree(tmp_dir, ignore_errors=True) |
| 300 | if not flat: |
| 301 | # 空目录也清理 |
| 302 | try: |
| 303 | os.rmdir(file_output_dir) |
| 304 | except OSError: |
| 305 | pass |
| 306 | |
| 307 | results[filepath] = count |
| 308 | total_images += count |
| 309 | print(f" ✅ 提取 {count} 张图片") |
| 310 | |
| 311 | except Exception as e: |
| 312 | results[filepath] = 0 |
| 313 | print(f" ❌ 失败: {e}") |
| 314 | |
| 315 | # 汇总 |
| 316 | print("\n" + "=" * 50) |
| 317 | print(f"🎉 处理完成: {total_files} 个文件, 共 {total_images} 张图片") |
| 318 | print(f"📁 输出目录: {os.path.abspath(output_dir)}") |
| 319 | return results |
| 320 | |
| 321 | |
| 322 | # -------------------- CLI -------------------- |
| 323 | |
| 324 | def build_parser() -> argparse.ArgumentParser: |
| 325 | parser = argparse.ArgumentParser( |
| 326 | description="从文档中提取内嵌图片", |
| 327 | formatter_class=argparse.RawDescriptionHelpFormatter, |
| 328 | epilog=""" |
| 329 | 示例: |
| 330 | %(prog)s report.docx |
| 331 | %(prog)s report.docx slides.pptx -o ./images |
| 332 | %(prog)s --dir ./docs -o ./images |
| 333 | %(prog)s --dir ./docs --flat -o ./all_images |
| 334 | """, |
| 335 | ) |
| 336 | parser.add_argument( |
| 337 | "inputs", |
| 338 | nargs="*", |
| 339 | help="要处理的文件或目录路径(可多选)", |
| 340 | ) |
| 341 | parser.add_argument( |
| 342 | "-d", "--dir", |
| 343 | action="append", |
| 344 | default=[], |
| 345 | help="扫描目录中的所有支持文件(可多次使用)", |
| 346 | ) |
| 347 | parser.add_argument( |
| 348 | "-o", "--output", |
| 349 | default="extracted_images", |
| 350 | help="输出目录(默认: extracted_images)", |
| 351 | ) |
| 352 | parser.add_argument( |
| 353 | "--flat", |
| 354 | action="store_true", |
| 355 | help="扁平输出:所有图片放到同一目录,不按文件分目录", |
| 356 | ) |
| 357 | return parser |
| 358 | |
| 359 | |
| 360 | def main(): |
| 361 | parser = build_parser() |
| 362 | args = parser.parse_args() |
| 363 | |
| 364 | # 收集所有输入 |
| 365 | all_inputs = list(args.inputs) if args.inputs else [] |
| 366 | for d in args.dir: |
| 367 | all_inputs.append(d) |
| 368 | |
| 369 | if not all_inputs: |
| 370 | parser.print_help() |
| 371 | sys.exit(1) |
| 372 | |
| 373 | extract_images(all_inputs, args.output, flat=args.flat) |
| 374 | |
| 375 | |
| 376 | if __name__ == "__main__": |
| 377 | main() |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

