ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

AutoRAG 数据解析模块 API 全解析:parser_node 装饰器与六大 Parse 模块的配置、调用与实现原理

AutoRAG 数据解析模块 API 全解析:parser_node 装饰器与六大 Parse 模块的配置、调用与实现原理 AutoRAG 数据解析模块 API 全解析parser_node 装饰器与六大 Parse 模块的配置、调用与实现原理【免费下载链接】AutoRAGAutoRAG: Now your agent can find anything in your computer. It gets smarter if you are using it frequently.项目地址: https://gitcode.com/GitHub_Trending/au/AutoRAG导读本文围绕 AutoRAG 数据流水线中的autorag.data.parse包展开该包是 RAG 构建流程中「文档解析Parsing」阶段的唯一入口它负责把原始文件PDF、CSV、JSON、Markdown、HTML、XML 或任意格式解析成结构化文本为后续分块chunking、向量化与检索提供原料。读完本文你将掌握该包的模块划分、统一的输入输出协议texts / path / page / last_modified_datetime、parser_node装饰器的行为以及langchain_parse、clova_ocr、llama_parse、table_hybrid_parse四大解析器的参数细节与底层实现并能在解析 YAML 配置中正确组合它们。包结构与 API 索引autorag.data.parse包共包含 6 个公开模块正是 API 文档legacy/docs/source/api_spec/autorag.data.parse.rst所列的 Submodules模块公开解析函数核心用途autorag.data.parse.baseparser_node装饰器统一解析器装饰与校验逻辑autorag.data.parse.runrun_parser解析阶段运行入口与结果落盘autorag.data.parse.langchain_parselangchain_parse基于 LangChain Loader 的本地解析autorag.data.parse.clovaclova_ocr基于 Naver Clova OCR 的云端 PDF 解析autorag.data.parse.llamaparsellama_parse基于 LlamaParse 的解析支持多模态autorag.data.parse.table_hybrid_parsetable_hybrid_parse含表/不含表页面混合解析从包入口 legacy/autorag/data/parse/init.py 可以看到默认直接导出的是langchain_parse其余模块通过module_type字符串在配置中按名加载具体注册机制见下文parse_modules与get_support_modules。统一协议parser_node 装饰器base 模块所有解析器都通过 legacy/autorag/data/parse/base.py 中的parser_node装饰器包装。它定义了整个解析阶段统一的数据契约def parser_node(func): functools.wraps(func) result_to_dataframe([texts, path, page, last_modified_datetime]) def wrapper( data_path_glob: str, file_type: str, parse_method: Optional[str] None, **kwargs, ) - Tuple[List[str], List[str], List[int], List[datetime]]: ...装饰器内部依次完成四件事文件收集与存在性检查用glob(data_path_glob)展开用户传入的路径模式若匹配不到任何文件则抛出FileNotFoundError(data does not exits in {data_path_glob})。file_type 白名单校验仅允许pdf、csv、json、md、html、xml、all_files七种取值其余值直接assert失败提示search type {file_type} is not supported。按类型筛选文件除all_files外仅保留os.path.basename(data_path).split(.)[-1] file_type的文件避免把无关格式喂给解析器。按函数名分发langchain_parse要求parse_method非空否则抛ValueError且当parse_method directory时会把 glob 拆成path目录与glob文件名模式两个参数传入clova_ocr、llama_parse、table_hybrid_parse则直接把筛选后的路径列表透传。包装函数返回的元组经过result_to_dataframe变为四列texts解析文本、path来源文件路径、page页码非分页解析为 -1、last_modified_datetime文件最后修改时间由_add_last_modified_datetime通过get_file_metadata补齐。这套统一契约保证了无论底层用哪个解析器下游 chunk 阶段拿到的 DataFrame 结构完全一致。运行入口run_parserrun 模块legacy/autorag/data/parse/run.py 的run_parser是解析阶段的总调度签名如下def run_parser( modules: List[Callable], module_params: List[Dict], data_path_glob: str, project_dir: str, all_files: bool, )它的职责包括自动补齐缺失文件类型的默认模块default_map为pdf、csv、md、html、xml提供了默认解析器例如 PDF 默认pdfminer、CSV 默认csv、Markdown 默认unstructuredmarkdown、HTML 默认bshtml、XML 默认unstructuredxml。当数据目录中出现 YAML 未配置的文件类型时会自动追加对应默认模块但JSON 例外——源码显式抛错JSON file type must have a jq_schema so you must set it in the YAML file.因为 JSON 解析必须由用户提供jq_schema无法默认推断。过滤无效模块移除那些file_type在数据集中根本不存在的模块配置避免空跑。并行执行与测速每个模块经measure_speed包装执行返回解析结果与执行时间。按类型落盘all_filesFalse时每个file_type保存为独立的file_type.parquetall_filesTrue时只允许一个解析模块多于一个直接抛ValueError结果保存为parsed_result.parquet最终还会把所有类型的解析结果合并写入project_dir/parsed_result.parquet并生成summary.csv含 filename、module_name、module_params、execution_time 列便于回溯每次解析用的模块与耗时。模块一langchain_parse —— 本地多格式解析langchain_parselegacy/autorag/data/parse/langchain_parse.py通过 LangChain 的 document loaders 解析文档是零外部依赖成本的首选。参数data_path_list文件路径列表、parse_methodLangChain loader 名称必填、**kwargs透传给 loader 实例的额外参数如编码、分隔符等。两种执行路径批量模式parse_method为pymupdf、pdfplumber、pypdf、pypdfium2、pdfminer、unstructuredpdf、csv、json、unstructuredmarkdown、bshtml、unstructuredxml等使用mp.Pool(num_workers)多进程并行num_workers mp.cpu_count()逐文件调用langchain_parse_pure。该函数从parse_modulesparse_method创建 loader调用.load()取文档列表texts取自每个文档的page_content仅 PDF 系列 loaderpymupdf、pdfplumber、pypdf、pypdfium2会按文档序号生成真实页码range(1, len(documents) 1)其余格式页码一律为-1。整批模式parse_method为directory或unstructured不拆文件直接对整个目录/文件集合解析。directory模式下装饰器会把 glob 拆成pathglob传入unstructured模式则把所有文件一次性交给UnstructuredLoader。此模式下没有逐页信息页码统一填-1。parse_modules 注册表parse_method的合法取值由 legacy/autorag/data/init.py 中的parse_modules字典定义PDFpdfminer、pdfplumber、pypdfium2、pypdf、pymupdf、unstructuredpdfCSVcsvJSONjson需配合 jq_schemaMarkdownunstructuredmarkdownHTMLbshtmlXMLunstructuredxml全部文件directory、unstructured、upstagedocumentparse其中upstagedocumentparse通过UpstageLayoutAnalysisLoader兼容适配legacy/autorag/data/init.py优先导入UpstageDocumentParseLoader失败时回退到UpstageLayoutAnalysisLoader并给出安装提示。模块二clova_ocr —— Naver Clova OCR 云端解析clova_ocrlegacy/autorag/data/parse/clova.py把 PDF 逐页转成图片后调用 Naver Clova OCR 识别文本适合扫描件、图片型 PDF。参数参数类型默认值说明urlstr环境变量CLOVA_URLClova OCR 请求 URL也可直接写进 YAMLapi_keystr环境变量CLOVA_API_KEY请求密钥也可直接写进 YAMLbatchint5并发批大小必须 ≤ 5否则抛ValueErrortable_detectionboolFalse是否启用表格检测实现要点凭证解析顺序为「显式参数 环境变量」两者都缺失时抛KeyError并提示设置方式。先用 PyMuPDFfitz把 PDF 每页渲染为 PNG 字节流pdf_to_images同时生成{pdf_path, pdf_page}的页面映射generate_image_info。通过aiohttp异步并发process_batch按 batch 限流调用clova_ocr_pure请求体为 Clova OCR V2 协议version: V2、images[].format: png、enableTableDetection字段随table_detection传入。响应解析逐字段拼接inferTextlineBreak为真时插入换行若响应含tables则调用json_to_html_table把 Clova 返回的表格单元格含rowSpan/colSpan合并单元格信息还原成带rowspan/colspan属性的 HTMLtable追加到文本尾部——这样表格结构信息不会在解析中丢失。返回的pages是真实页码从 1 开始path是原始 PDF 路径。模块三llama_parse —— LlamaCloud 解析支持多模态llama_parselegacy/autorag/data/parse/llamaparse.py基于 LlamaIndex 的LlamaParse服务需要设置LLAMA_CLOUD_API_KEY环境变量。参数参数类型默认值说明batchint8并发批大小use_vendor_multimodal_modelboolFalse是否启用供应商多模态模型vendor_multimodal_model_namestropenai-gpt4o多模态模型名use_own_keyboolFalse是否使用自己的多模态 API Keyvendor_multimodal_api_keystrNone自定义多模态 API Key**kwargs--透传给LlamaParse实例如result_type、language实现要点启用多模态时_add_multimodal_params会把多模态参数并入 kwargs并校验模型名合法性支持openai-gpt4o、openai-gpt-4o-mini读OPENAI_API_KEY、anthropic-sonnet-3.5读ANTHROPIC_API_KEY、gemini-1.5-flash/gemini-1.5-pro读GEMINI_API_KEYcustom-azure-model目前明确NotImplementedError未知模型名抛ValueError。若use_own_keyTrue则用vendor_multimodal_api_key显式覆盖环境变量。解析用parse_instance.aload_data(data_path)异步加载pages按文档数量从 1 递增texts取自每个文档的.text。模块四table_hybrid_parse —— 含表/无表页面混合解析table_hybrid_parselegacy/autorag/data/parse/table_hybrid_parse.py)是专门为「PDF 中既有纯文本页又有表格页」设计的混合策略把表格页交给表格能力更强的解析器把文本页交给普通解析器最后按页序合并避免表格页在纯文本解析中被破坏。参数参数类型说明text_parse_modulestr文本页解析模块名如langchain_parsetext_paramsdict文本解析器参数table_parse_modulestr表格页解析模块名如llamaparsetable_paramsdict表格解析器参数执行流程源码逻辑在临时目录下建text/与table/两个子目录。save_page_by_table用PyPDF2.PdfReader逐页拆出单页 PDF并用pdfplumber的page.extract_tables()判断该页是否含表格含表页存入table_dir、纯文本页存入text_dir同时维护「临时单页文件 → 原始 PDF」的映射。get_each_module_result分别对两个目录的*glob 调用指定的解析模块通过get_support_modules取回被parser_node包装前的原始函数执行得到各自的(texts, paths)。合并两批结果并按临时文件名排序保证原始页序再通过path_map_dict还原原始文件路径从文件名xxx_page_N.pdf中解析出真实页码。返回texts / path / pages临时目录随上下文自动清理。配置示例如何组合这些模块解析阶段通过项目目录下的 parse YAML 配置驱动模块清单如下最简配置legacy/sample_config/parse/simple_parse.yaml仅用langchain_parse的pdfminer解析 PDFmodules: - module_type: langchain_parse file_type: pdf parse_method: pdfminer全文件类型配置legacy/sample_config/parse/all_files_full.yamlfile_type: all_files时只能同时启用一个模块run_parser会校验可从directory、unstructured、upstagedocumentparse、clova、llamaparse中任选其一例如启用 Clova OCR 表格检测modules: - module_type: clova file_type: all_files table_detection: true或启用 LlamaParse 多模态韩语 markdown 输出 GPT-4o-mini 视觉modules: - module_type: llamaparse file_type: all_files result_type: markdown language: ko use_vendor_multimodal_model: true vendor_multimodal_model_name: openai-gpt-4o-mini混合解析配置legacy/sample_config/parse/parse_hybird.yaml表格页用 LlamaParse、文本页用 pdfplumber二者结果自动按页序合并modules: - module_type: table_hybrid_parse file_type: pdf text_parse_module: langchain_parse text_params: parse_method: pdfplumber table_parse_module: llamaparse table_params: result_type: markdown language: ko use_vendor_multimodal_model: true vendor_multimodal_model_name: openai-gpt-4o-mini其余更完整的示例含多文件类型、OCR、多模态可参考 legacy/sample_config/parse/file_types_full.yaml、legacy/sample_config/parse/parse_multimodal.yaml 与 legacy/sample_config/parse/parse_ocr.yaml。模块选型建议与注意事项综合源码实现选择解析器时可参考以下结论均以当前仓库代码为准普通文本型 PDF / CSV / Markdown / HTML / XML优先langchain_parse零 API 成本、多进程并行、支持真实页码适合绝大多数本地文件。扫描件、图片型 PDF选择clova_ocr注意batch上限为 5需提前配置CLOVA_URL/CLOVA_API_KEY或写入 YAML若文档含表格且需要保留表格结构务必开启table_detection: true。复杂版面、需要表格/版面还原选择llamaparse可组合result_type: markdown与多模态模型注意其多模态模型名白名单与对应 API Key 环境变量的约束。PDF 中表格与正文混杂选择table_hybrid_parse让不同解析器各司其职再按页序合并是兼顾成本与质量的最优解。JSON 必须显式配置jq_schema否则run_parser会直接报错all_files模式下只能配置一个解析模块。所有解析器的输出都会被parser_node统一补齐last_modified_datetime列并以 parquet 形式落盘到项目目录的parsed_result.parquetsummary.csv中记录了每个文件类型所用模块与平均执行时间可作为解析效果对比的依据。【免费下载链接】AutoRAGAutoRAG: Now your agent can find anything in your computer. It gets smarter if you are using it frequently.项目地址: https://gitcode.com/GitHub_Trending/au/AutoRAG创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表