
unstructured 默认的 partition_docx 不支持图像提取;需改用 unstructured_ingest 管道并显式启用 extract_image_block_types=["Image"],或先将 DOCX 转为 PDF 再处理,才能可靠识别和结构化图像内容。
unstructured 默认的 `partition_docx` 不支持图像提取;需改用 `unstructured_ingest` 管道并显式启用 `extract_image_block_types=["image"]`,或先将 docx 转为 pdf 再处理,才能可靠识别和结构化图像内容。
在使用 unstructured 库解析 .docx 文件时,一个常见误区是认为 partition_docx() 函数会自动识别并返回图像(Image 类型元素)。实际上,该函数默认仅提取文本内容(如 Text, Title, NarrativeText),完全忽略内嵌图像——即使文档中明确包含图片,也不会出现在输出的 elements 列表中,且不报错,导致调试困难。
✅ 正确方案:使用 unstructured_ingest 配置高精度图像提取
unstructured_ingest 是官方推荐的批量、可配置数据摄取框架,支持通过 additional_partition_args 启用图像块提取。关键参数为:
"extract_image_block_types": ["Image"]
同时需配合 strategy="hi_res"(高分辨率模式)及 partition_by_api=True(调用云端 API),因为图像提取依赖于服务端的 OCR 与布局分析能力(本地 partition_docx 不具备此功能)。
以下是完整可运行示例:
import os
import json
from unstructured_ingest.v2.pipeline.pipeline import Pipeline
from unstructured_ingest.v2.interfaces import ProcessorConfig
from unstructured_ingest.v2.processes.connectors.local import (
LocalIndexerConfig,
LocalDownloaderConfig,
LocalConnectionConfig,
LocalUploaderConfig
)
from unstructured_ingest.v2.processes.partitioner import PartitionerConfig
if __name__ == "__main__":
# 设置认证信息(务必替换为真实 API Key)
os.environ["UNSTRUCTURED_API_KEY"] = "your-api-key-here"
os.environ["UNSTRUCTURED_API_URL"] = "https://api.unstructuredapp.io/general/v0/general"
Pipeline.from_configs(
context=ProcessorConfig(),
indexer_config=LocalIndexerConfig(input_path="input"), # 指向含 test.docx 的目录
downloader_config=LocalDownloaderConfig(),
source_connection_config=LocalConnectionConfig(),
partitioner_config=PartitionerConfig(
partition_by_api=True,
api_key=os.getenv("UNSTRUCTURED_API_KEY"),
partition_endpoint=os.getenv("UNSTRUCTURED_API_URL"),
strategy="hi_res", # 必须启用高分辨率策略
additional_partition_args={
"extract_image_block_types": ["Image"], # ? 核心:显式声明提取图像
"split_pdf_page": False, # 对 DOCX 不生效,但无害
"infer_table_structure": True,
}
),
uploader_config=LocalUploaderConfig(output_dir="output") # 输出 JSON 到 output/
).run()✅ 执行后:生成的 JSON 输出中将包含 type: "Image" 元素,附带 metadata.image_path(临时路径)、metadata.coordinates(位置信息)及 Base64 编码的 text 字段(OCR 识别结果)。
⚠️ 注意事项与备选策略
- API 依赖性:extract_image_block_types 仅在调用 unstructured.io 云端 API(partition_by_api=True)时生效;本地 partition_docx() 无法实现。
- 格式限制:.docx 中的图像若以“内联对象”或“浮动对象”形式插入,可能因 Office 版本/导出方式影响识别稳定性。
- 更可靠替代方案:如遇识别不稳定,建议预处理——使用 python-docx 或 libreoffice --headless 将 DOCX 转为 PDF,再用 partition_pdf(strategy="hi_res", extract_images_in_pdf=True) 处理,效果更一致。
- 权限与环境:确保 UNSTRUCTURED_API_KEY 有效,且账户已开通 hi_res 策略权限(免费 tier 可能受限)。
总之,图像提取不是 partition_docx 的设计目标,而是 ingest + hi_res API 的专属能力。明确这一点,可避免在错误路径上反复调试。


















