Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
Realese 0.8.0 (#586)
drunkpig9f352df0eb66
diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.ymlindex 75510f74..9e5a7454 100644--- a/.github/workflows/cli.yml+++ b/.github/workflows/cli.yml@@ -6,20 +6,24 @@ on:push:branches:- "master"+ - "dev"paths-ignore:- "cmds/**"- "**.md"+ - "**.yml"pull_request:branches:- "master"+ - "dev"paths-ignore:- "cmds/**"- "**.md"+ - "**.yml"workflow_dispatch:jobs:cli-test:- runs-on: ubuntu-latest- timeout-minutes: 40+ runs-on: pdf+ timeout-minutes: 120strategy:fail-fast: true@@ -28,27 +32,22 @@ jobs:uses: actions/checkout@v3with:fetch-depth: 2-- - name: check-requirements- run: |- pip install -r requirements.txt- pip install -r requirements-qa.txt- pip install magic-pdf- - name: test_cli++ - name: installrun: |- cp magic-pdf.template.json ~/magic-pdf.json- echo $GITHUB_WORKSPACE- cd $GITHUB_WORKSPACE && export PYTHONPATH=. && pytest -s -v tests/test_unit.py- cd $GITHUB_WORKSPACE && pytest -s -v tests/test_cli/test_cli.py-- - name: benchmark+ echo $GITHUB_WORKSPACE && sh tests/retry_env.sh+ - name: unit test+ run: |+ cd $GITHUB_WORKSPACE && export PYTHONPATH=. && coverage run -m pytest tests/test_unit.py --cov=magic_pdf/ --cov-report term-missing --cov-report html+ cd $GITHUB_WORKSPACE && python tests/get_coverage.py+ - name: cli testrun: |- cd $GITHUB_WORKSPACE && pytest -s -v tests/test_cli/test_bench.py+ cd $GITHUB_WORKSPACE && pytest -s -v tests/test_cli/test_cli_sdk.pynotify_to_feishu:if: ${{ always() && !cancelled() && contains(needs.*.result, 'failure') && (github.ref_name == 'master') }}- needs: [cli-test]- runs-on: ubuntu-latest+ needs: cli-test+ runs-on: pdfsteps:- name: get_actorrun: |@@ -67,9 +66,5 @@ jobs:- name: notifyrun: |- curl ${{ secrets.WEBHOOK_URL }} -H 'Content-Type: application/json' -d '{- "msgtype": "text",- "text": {- "mentioned_list": ["${{ env.METIONS }}"] , "content": "'${{ github.repository }}' GitHubAction Failed!\n 细节请查看:https://github.com/'${{ github.repository }}'/actions/runs/'${GITHUB_RUN_ID}'"- }- }'\ No newline at end of file+ echo ${{ secrets.USER_ID }}+ curl -X POST -H "Content-Type: application/json" -d '{"msg_type":"post","content":{"post":{"zh_cn":{"title":"'${{ github.repository }}' GitHubAction Failed","content":[[{"tag":"text","text":""},{"tag":"a","text":"Please click here for details ","href":"https://github.com/'${{ github.repository }}'/actions/runs/'${GITHUB_RUN_ID}'"},{"tag":"at","user_id":"'${{ secrets.USER_ID }}'"}]]}}}}' ${{ secrets.WEBHOOK_URL }}diff --git a/.gitignore b/.gitignoreindex d90d0c33..fda7b648 100644--- a/.gitignore+++ b/.gitignore@@ -30,10 +30,10 @@ tmp/tmp.vscode.vscode/-/tests/ocr_demo/app/common/__init__.py/magic_pdf/config/__init__.pysource.dev.env+tmpdiff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 6f29f089..b86d6f8b 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -3,6 +3,7 @@ repos:rev: 5.0.4hooks:- id: flake8+ args: ["--max-line-length=120", "--ignore=E131,E125,W503,W504,E203"]- repo: https://github.com/PyCQA/isortrev: 5.11.5hooks:@@ -11,6 +12,7 @@ repos:rev: v0.32.0hooks:- id: yapf+ args: ["--style={based_on_style: google, column_limit: 120, indent_width: 4}"]- repo: https://github.com/codespell-project/codespellrev: v2.2.1hooks:@@ -41,4 +43,4 @@ repos:rev: v1.3.1hooks:- id: docformatter- args: ["--in-place", "--wrap-descriptions", "79"]+ args: ["--in-place", "--wrap-descriptions", "119"]diff --git a/Dockerfile b/Dockerfileindex b858d4dc..786bab7e 100644--- a/Dockerfile+++ b/Dockerfile@@ -1,5 +1,5 @@# Use the official Ubuntu base image-FROM ubuntu:latest+FROM ubuntu:22.04# Set environment variables to non-interactive to avoid prompts during installationENV DEBIAN_FRONTEND=noninteractive@@ -29,17 +29,23 @@ RUN python3 -m venv /opt/mineru_venv# Activate the virtual environment and install necessary Python packagesRUN /bin/bash -c "source /opt/mineru_venv/bin/activate && \- pip install --upgrade pip && \- pip install magic-pdf[full-cpu] detectron2 --extra-index-url https://myhloli.github.io/wheels/"--# Copy the configuration file template and set up the model directory-COPY magic-pdf.template.json /root/magic-pdf.json--# Set the models directory in the configuration file (adjust the path as needed)-RUN sed -i 's|/tmp/models|/opt/models|g' /root/magic-pdf.json--# Create the models directory-RUN mkdir -p /opt/models+ pip3 install --upgrade pip && \+ wget https://gitee.com/myhloli/MinerU/raw/master/requirements-docker.txt && \+ pip3 install -r requirements-docker.txt --extra-index-url https://wheels.myhloli.com -i https://pypi.tuna.tsinghua.edu.cn/simple && \+ pip3 install paddlepaddle-gpu==3.0.0b1 -i https://www.paddlepaddle.org.cn/packages/stable/cu118/"++# Copy the configuration file template and install magic-pdf latest+RUN /bin/bash -c "wget https://gitee.com/myhloli/MinerU/raw/master/magic-pdf.template.json && \+ cp magic-pdf.template.json /root/magic-pdf.json && \+ source /opt/mineru_venv/bin/activate && \+ pip3 install -U magic-pdf"++# Download models and update the configuration file+RUN /bin/bash -c "pip3 install modelscope && \+ wget https://gitee.com/myhloli/MinerU/raw/master/docs/download_models.py && \+ python3 download_models.py && \+ sed -i 's|/tmp/models|/root/.cache/modelscope/hub/opendatalab/PDF-Extract-Kit/models|g' /root/magic-pdf.json && \+ sed -i 's|cpu|cuda|g' /root/magic-pdf.json"# Set the entry point to activate the virtual environment and run the command line toolENTRYPOINT ["/bin/bash", "-c", "source /opt/mineru_venv/bin/activate && exec \"$@\"", "--"]diff --git a/README.md b/README.mdindex cf6fdfd0..ebc862a8 100644--- a/README.md+++ b/README.md@@ -5,6 +5,7 @@</p><!-- icon -->+[](https://github.com/opendatalab/MinerU)[](https://github.com/opendatalab/MinerU)[](https://github.com/opendatalab/MinerU/issues)@@ -12,17 +13,26 @@[](https://badge.fury.io/py/magic-pdf)[](https://pepy.tech/project/magic-pdf)[](https://pepy.tech/project/magic-pdf)++[](https://huggingface.co/spaces/opendatalab/MinerU)+[](https://www.modelscope.cn/studios/OpenDataLab/MinerU)+[](https://colab.research.google.com/gist/papayalove/b5f4913389e7ff9883c6b687de156e78/mineru_demo.ipynb)+[](#)+<a href="https://trendshift.io/repositories/11174" target="_blank"><img src="https://trendshift.io/api/badge/repositories/11174" alt="opendatalab%2FMinerU | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a><!-- language -->+[English](README.md) | [简体中文](README_zh-CN.md)<!-- hot link -->+<p align="center"><a href="https://github.com/opendatalab/PDF-Extract-Kit">PDF-Extract-Kit: High-Quality PDF Extraction Toolkit</a>🔥🔥🔥</p><!-- join us -->+<p align="center">👋 join us on <a href="https://discord.gg/Tdedn9GTXq" target="_blank">Discord</a> and <a href="https://cdn.vansin.top/internlm/mineru.jpg" target="_blank">WeChat</a></p>@@ -30,12 +40,14 @@</div># Changelog+- 2024/09/09: Version 0.8.0 released, supporting fast deployment with Dockerfile, and launching demos on Huggingface and Modelscope.- 2024/08/30: Version 0.7.1 released, add paddle tablemaster table recognition option- 2024/08/09: Version 0.7.0b1 released, simplified installation process, added table recognition functionality- 2024/08/01: Version 0.6.2b1 released, optimized dependency conflict issues and installation documentation- 2024/07/05: Initial open-source release<!-- TABLE OF CONTENT -->+<details open="open"><summary><h2 style="display: inline-block">Table of Contents</h2></summary><ol>@@ -74,10 +86,10 @@</ol></details>--# MinerU+## Project Introduction+MinerU is a tool that converts PDFs into machine-readable formats (e.g., markdown, JSON), allowing for easy extraction into any format.MinerU was born during the pre-training process of [InternLM](https://github.com/InternLM/InternLM). We focus on solving symbol conversion issues in scientific literature and hope to contribute to technological development in the era of large models.Compared to well-known commercial products, MinerU is still young. If you encounter any issues or if the results are not as expected, please submit an issue on [issue](https://github.com/opendatalab/MinerU/issues) and **attach the relevant PDF**.@@ -101,6 +113,7 @@ https://github.com/user-attachments/assets/4bea02c9-6d54-4cd6-97ed-dff14340982cIf you encounter any installation issues, please first consult the <a href="#faq">FAQ</a>. </br>If the parsing results are not as expected, refer to the <a href="#known-issues">Known Issues</a>. </br>There are three different ways to experience MinerU:+- [Online Demo (No Installation Required)](#online-demo)- [Quick CPU Demo (Windows, Linux, Mac)](#quick-cpu-demo)- [Linux/Windows + CUDA](#Using-GPU)@@ -171,33 +184,41 @@ In non-mainline environments, due to the diversity of hardware and software conf### Quick CPU Demo#### 1. Install magic-pdf+```bashconda create -n MinerU python=3.10conda activate MinerUpip install -U magic-pdf[full] --extra-index-url https://wheels.myhloli.com```+#### 2. Download model weight filesRefer to [How to Download Model Files](docs/how_to_download_models_en.md) for detailed instructions.+> ❗️After downloading the models, please make sure to verify the completeness of the model files.->+>> Check if the model file sizes match the description on the webpage. If possible, use sha256 to verify the integrity of the files.#### 3. Copy and configure the template file+You can find the `magic-pdf.template.json` template configuration file in the root directory of the repository.+> ❗️Make sure to execute the following command to copy the configuration file to your **user directory**; otherwise, the program will not run.->+>> The user directory for Windows is `C:\Users\YourUsername`, for Linux it is `/home/YourUsername`, and for macOS it is `/Users/YourUsername`.+```bashcp magic-pdf.template.json ~/magic-pdf.json```Find the `magic-pdf.json` file in your user directory and configure the "models-dir" path to point to the directory where the model weight files were downloaded in [Step 2](#2-download-model-weight-files).+> ❗️Make sure to correctly configure the **absolute path** to the model weight files directory, otherwise the program will not run because it can't find the model files.>> On Windows, this path should include the drive letter and all backslashes (`\`) in the path should be replaced with forward slashes (`/`) to avoid syntax errors in the JSON file due to escape sequences.->+>> For example: If the models are stored in the "models" directory at the root of the D drive, the "model-dir" value should be `D:/models`.+```json{// other config@@ -210,13 +231,26 @@ Find the `magic-pdf.json` file in your user directory and configure the "models-}```-### Using GPU+If your device supports CUDA and meets the GPU requirements of the mainline environment, you can use GPU acceleration. Please select the appropriate guide based on your system:- [Ubuntu 22.04 LTS + GPU](docs/README_Ubuntu_CUDA_Acceleration_en_US.md)- [Windows 10/11 + GPU](docs/README_Windows_CUDA_Acceleration_en_US.md)-+- Quick Deployment with Docker+ > Docker requires a GPU with at least 16GB of VRAM, and all acceleration features are enabled by default.+ >+ > Before running this Docker, you can use the following command to check if your device supports CUDA acceleration on Docker.+ >+ > ```bash+ > docker run --rm --gpus=all nvidia/cuda:12.1.0-base-ubuntu22.04 nvidia-smi+ > ```+ ```bash+ wget https://github.com/opendatalab/MinerU/raw/master/Dockerfile+ docker build -t mineru:latest .+ docker run --rm -it --gpus=all mineru:latest /bin/bash+ magic-pdf --help+ ```## Usage@@ -230,12 +264,12 @@ Options:-v, --version display the version and exit-p, --path PATH local pdf filepath or directory [required]-o, --output-dir TEXT output local directory- -m, --method [ocr|txt|auto] the method for parsing pdf.+ -m, --method [ocr|txt|auto] the method for parsing pdf.ocr: using ocr technique to extract information from pdf,txt: suitable for the text-based pdf only and outperform ocr,auto: automatically choose the best method for parsing pdffrom ocr and txt.- without method specified, auto will be used by default.+ without method specified, auto will be used by default.--help Show this message and exit.@@ -250,13 +284,13 @@ magic-pdf -p {some_pdf} -o {some_output_dir} -m autoThe results will be saved in the `{some_output_dir}` directory. The output file list is as follows:```text-├── some_pdf.md # markdown file-├── images # directory for storing images-├── layout.pdf # layout diagram-├── middle.json # MinerU intermediate processing result-├── model.json # model inference result-├── origin.pdf # original PDF file-└── spans.pdf # smallest granularity bbox position information diagram+├── some_pdf.md # markdown file+├── images # directory for storing images+├── some_pdf_layout.pdf # layout diagram+├── some_pdf_middle.json # MinerU intermediate processing result+├── some_pdf_model.json # model inference result+├── some_pdf_origin.pdf # original PDF file+└── some_pdf_spans.pdf # smallest granularity bbox position information diagram```For more information about the output files, please refer to the [Output File Description](docs/output_file_en_us.md).@@ -264,6 +298,7 @@ For more information about the output files, please refer to the [Output File De### APIProcessing files from local disk+```pythonimage_writer = DiskReaderWriter(local_image_dir)image_dir = str(os.path.basename(local_image_dir))@@ -276,6 +311,7 @@ md_content = pipe.pipe_mk_markdown(image_dir, drop_mode="none")```Processing files from object storage+```pythons3pdf_cli = S3ReaderWriter(pdf_ak, pdf_sk, pdf_endpoint)image_dir = "s3://img_bucket/"@@ -290,10 +326,10 @@ md_content = pipe.pipe_mk_markdown(image_dir, drop_mode="none")```For detailed implementation, refer to:+- [demo.py Simplest Processing Method](demo/demo.py)- [magic_pdf_parse_main.py More Detailed Processing Workflow](demo/magic_pdf_parse_main.py)-### Development GuideTODO@@ -305,10 +341,11 @@ TODO- [ ] Code block recognition within the text- [ ] Table of contents recognition- [x] Table recognition-- [ ] Chemical formula recognition+- [ ] [Chemical formula recognition](docs/chemical_knowledge_introduction/introduction.pdf)- [ ] Geometric shape recognition# Known Issues+- Reading order is segmented based on rules, which can cause disordered sequences in some cases- Vertical text is not supported- Lists, code blocks, and table of contents are not yet supported in the layout model@@ -318,11 +355,11 @@ TODO# FAQ+[FAQ in Chinese](docs/FAQ_zh_cn.md)[FAQ in English](docs/FAQ_en_us.md)-# All Thanks To Our Contributors<a href="https://github.com/opendatalab/MinerU/graphs/contributors">@@ -335,8 +372,8 @@ TODOThis project currently uses PyMuPDF to achieve advanced functionality. However, since it adheres to the AGPL license, it may impose restrictions on certain usage scenarios. In future iterations, we plan to explore and replace it with a more permissive PDF processing library to enhance user-friendliness and flexibility.-# Acknowledgments+- [PDF-Extract-Kit](https://github.com/opendatalab/PDF-Extract-Kit)- [StructEqTable](https://github.com/UniModal4Reasoning/StructEqTable-Deploy)- [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR)@@ -373,9 +410,11 @@ This project currently uses PyMuPDF to achieve advanced functionality. However,</a># Magic-doc+[Magic-Doc](https://github.com/InternLM/magic-doc) Fast speed ppt/pptx/doc/docx/pdf extraction tool# Magic-html+[Magic-HTML](https://github.com/opendatalab/magic-html) Mixed web page extraction tool# Linksdiff --git a/README_zh-CN.md b/README_zh-CN.mdindex dff7a2dc..e1c5d8b6 100644--- a/README_zh-CN.md+++ b/README_zh-CN.md@@ -4,8 +4,8 @@<img src="docs/images/MinerU-logo.png" width="300px" style="vertical-align:middle;"></p>-<!-- icon -->+[](https://github.com/opendatalab/MinerU)[](https://github.com/opendatalab/MinerU)[](https://github.com/opendatalab/MinerU/issues)@@ -13,33 +13,41 @@[](https://badge.fury.io/py/magic-pdf)[](https://pepy.tech/project/magic-pdf)[](https://pepy.tech/project/magic-pdf)++[](https://huggingface.co/spaces/opendatalab/MinerU)+[](https://www.modelscope.cn/studios/OpenDataLab/MinerU)+[](https://colab.research.google.com/gist/papayalove/b5f4913389e7ff9883c6b687de156e78/mineru_demo.ipynb)+[](#)+<a href="https://trendshift.io/repositories/11174" target="_blank"><img src="https://trendshift.io/api/badge/repositories/11174" alt="opendatalab%2FMinerU | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a><!-- language -->-[English](README.md) | [简体中文](README_zh-CN.md)+[English](README.md) | [简体中文](README_zh-CN.md)<!-- hot link -->+<p align="center"><a href="https://github.com/opendatalab/PDF-Extract-Kit">PDF-Extract-Kit: 高质量PDF解析工具箱</a>🔥🔥🔥</p><!-- join us -->+<p align="center">👋 join us on <a href="https://discord.gg/Tdedn9GTXq" target="_blank">Discord</a> and <a href="https://cdn.vansin.top/internlm/mineru.jpg" target="_blank">WeChat</a></p></div>-# 更新记录+- 2024/09/09 0.8.0发布,支持Dockerfile快速部署,同时上线了huggingface、modelscope demo- 2024/08/30 0.7.1发布,集成了paddle tablemaster表格识别功能- 2024/08/09 0.7.0b1发布,简化安装步骤提升易用性,加入表格识别功能- 2024/08/01 0.6.2b1发布,优化了依赖冲突问题和安装文档- 2024/07/05 首次开源-<!-- TABLE OF CONTENT -->+<details open="open"><summary><h2 style="display: inline-block">文档目录</h2></summary><ol>@@ -78,10 +86,10 @@</ol></details>--# MinerU+## 项目简介+MinerU是一款将PDF转化为机器可读格式的工具(如markdown、json),可以很方便地抽取为任意格式。MinerU诞生于[书生-浦语](https://github.com/InternLM/InternLM)的预训练过程中,我们将会集中精力解决科技文献中的符号转化问题,希望在大模型时代为科技发展做出贡献。相比国内外知名商用产品MinerU还很年轻,如果遇到问题或者结果不及预期请到[issue](https://github.com/opendatalab/MinerU/issues)提交问题,同时**附上相关PDF**。@@ -100,17 +108,16 @@ https://github.com/user-attachments/assets/4bea02c9-6d54-4cd6-97ed-dff14340982c- 支持CPU和GPU环境- 支持windows/linux/mac平台-## 快速开始如果遇到任何安装问题,请先查询 <a href="#faq">FAQ</a> </br>如果遇到解析效果不及预期,参考 <a href="#known-issues">Known Issues</a></br>有3种不同方式可以体验MinerU的效果:+- [在线体验(无需任何安装)](#在线体验)- [使用CPU快速体验(Windows,Linux,Mac)](#使用cpu快速体验)- [Linux/Windows + CUDA](#使用gpu)-**⚠️安装前必看——软硬件环境支持说明**为了确保项目的稳定性和可靠性,我们在开发过程中仅对特定的软硬件环境进行优化和测试。这样当用户在推荐的系统配置上部署和运行项目时,能够获得最佳的性能表现和最少的兼容性问题。@@ -174,38 +181,47 @@ https://github.com/user-attachments/assets/4bea02c9-6d54-4cd6-97ed-dff14340982c[在线体验点击这里](https://opendatalab.com/OpenSourceTools/Extractor/PDF)-### 使用CPU快速体验#### 1. 安装magic-pdf+最新版本国内镜像源同步可能会有延迟,请耐心等待+```bashconda create -n MinerU python=3.10conda activate MinerUpip install -U magic-pdf[full] --extra-index-url https://wheels.myhloli.com -i https://pypi.tuna.tsinghua.edu.cn/simple```+#### 2. 下载模型权重文件详细参考 [如何下载模型文件](docs/how_to_download_models_zh_cn.md)+> ❗️模型下载后请务必检查模型文件是否下载完整->+>> 请检查目录下的模型文件大小与网页上描述是否一致,如果可以的话,最好通过sha256校验模型是否下载完整#### 3. 拷贝配置文件并进行配置+在仓库根目录可以获得 [magic-pdf.template.json](magic-pdf.template.json) 配置模版文件+> ❗️务必执行以下命令将配置文件拷贝到【用户目录】下,否则程序将无法运行->-> windows的用户目录为 "C:\Users\用户名", linux用户目录为 "/home/用户名", macOS用户目录为 "/Users/用户名"+>+> windows的用户目录为 "C:\\Users\\用户名", linux用户目录为 "/home/用户名", macOS用户目录为 "/Users/用户名"+```bashcp magic-pdf.template.json ~/magic-pdf.json```在用户目录中找到magic-pdf.json文件并配置"models-dir"为[2. 下载模型权重文件](#2-下载模型权重文件)中下载的模型权重文件所在目录+> ❗️务必正确配置模型权重文件所在目录的【绝对路径】,否则会因为找不到模型文件而导致程序无法运行>> windows系统中此路径应包含盘符,且需把路径中所有的`"\"`替换为`"/"`,否则会因为转义原因导致json文件语法错误。>+> 例如:模型放在D盘根目录的models目录,则model-dir的值应为"D:/models"+```json{// other config@@ -218,13 +234,27 @@ cp magic-pdf.template.json ~/magic-pdf.json}```-### 使用GPU+如果您的设备支持CUDA,且满足主线环境中的显卡要求,则可以使用GPU加速,请根据自己的系统选择适合的教程:- [Ubuntu22.04LTS + GPU](docs/README_Ubuntu_CUDA_Acceleration_zh_CN.md)- [Windows10/11 + GPU](docs/README_Windows_CUDA_Acceleration_zh_CN.md)-+- 使用Docker快速部署+ > Docker 需设备gpu显存大于等于16GB,默认开启所有加速功能+ >+ > 运行本docker前可以通过以下命令检测自己的设备是否支持在docker上使用CUDA加速+ >+ > ```bash+ > docker run --rm --gpus=all nvidia/cuda:12.1.0-base-ubuntu22.04 nvidia-smi+ > ```+ ```bash+ wget https://github.com/opendatalab/MinerU/raw/master/Dockerfile+ docker build -t mineru:latest .+ docker run --rm -it --gpus=all mineru:latest /bin/bash+ magic-pdf --help+ ```+## 使用@@ -238,12 +268,12 @@ Options:-v, --version display the version and exit-p, --path PATH local pdf filepath or directory [required]-o, --output-dir TEXT output local directory- -m, --method [ocr|txt|auto] the method for parsing pdf.+ -m, --method [ocr|txt|auto] the method for parsing pdf.ocr: using ocr technique to extract information from pdf,txt: suitable for the text-based pdf only and outperform ocr,auto: automatically choose the best method for parsing pdffrom ocr and txt.- without method specified, auto will be used by default.+ without method specified, auto will be used by default.--help Show this message and exit.@@ -258,21 +288,21 @@ magic-pdf -p {some_pdf} -o {some_output_dir} -m auto运行完命令后输出的结果会保存在`{some_output_dir}`目录下, 输出的文件列表如下```text-├── some_pdf.md # markdown 文件-├── images # 存放图片目录-├── layout.pdf # layout 绘图-├── middle.json # minerU 中间处理结果-├── model.json # 模型推理结果-├── origin.pdf # 原 pdf 文件-└── spans.pdf # 最小粒度的bbox位置信息绘图+├── some_pdf.md # markdown 文件+├── images # 存放图片目录+├── some_pdf_layout.pdf # layout 绘图+├── some_pdf_middle.json # minerU 中间处理结果+├── some_pdf_model.json # 模型推理结果+├── some_pdf_origin.pdf # 原 pdf 文件+└── some_pdf_spans.pdf # 最小粒度的bbox位置信息绘图```更多有关输出文件的信息,请参考[输出文件说明](docs/output_file_zh_cn.md)-### API处理本地磁盘上的文件+```pythonimage_writer = DiskReaderWriter(local_image_dir)image_dir = str(os.path.basename(local_image_dir))@@ -285,6 +315,7 @@ md_content = pipe.pipe_mk_markdown(image_dir, drop_mode="none")```处理对象存储上的文件+```pythons3pdf_cli = S3ReaderWriter(pdf_ak, pdf_sk, pdf_endpoint)image_dir = "s3://img_bucket/"@@ -298,11 +329,11 @@ pipe.pipe_parse()md_content = pipe.pipe_mk_markdown(image_dir, drop_mode="none")```-详细实现可参考+详细实现可参考+- [demo.py 最简单的处理方式](demo/demo.py)- [magic_pdf_parse_main.py 能够更清晰看到处理流程](demo/magic_pdf_parse_main.py)-### 二次开发TODO@@ -314,11 +345,11 @@ TODO- [ ] 正文中代码块识别- [ ] 目录识别- [x] 表格识别-- [ ] 化学式识别+- [ ] [化学式识别](docs/chemical_knowledge_introduction/introduction.pdf)- [ ] 几何图形识别-# Known Issues+- 阅读顺序基于规则的分割,在一些情况下会乱序- 不支持竖排文字- 列表、代码块、目录在layout模型里还没有支持@@ -328,10 +359,11 @@ TODO# FAQ+[常见问题](docs/FAQ_zh_cn.md)-[FAQ](docs/FAQ_en_us.md)+[FAQ](docs/FAQ_en_us.md)# All Thanks To Our Contributors@@ -346,6 +378,7 @@ TODO本项目目前采用PyMuPDF以实现高级功能,但因其遵循AGPL协议,可能对某些使用场景构成限制。未来版本迭代中,我们计划探索并替换为许可条款更为宽松的PDF处理库,以提升用户友好度及灵活性。# Acknowledgments+- [PDF-Extract-Kit](https://github.com/opendatalab/PDF-Extract-Kit)- [StructEqTable](https://github.com/UniModal4Reasoning/StructEqTable-Deploy)- [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR)@@ -382,9 +415,11 @@ TODO</a># Magic-doc+[Magic-Doc](https://github.com/InternLM/magic-doc) Fast speed ppt/pptx/doc/docx/pdf extraction tool# Magic-html+[Magic-HTML](https://github.com/opendatalab/magic-html) Mixed web page extraction tool# Linksdiff --git a/README_zh-CN.md.bak b/README_zh-CN.md.bakindex 708c140f..22e7ef58 100644--- a/README_zh-CN.md.bak+++ b/README_zh-CN.md.bak@@ -1,9 +1,10 @@-<div id="top">+<div align="center" xmlns="http://www.w3.org/1999/html">+<!-- logo --><p align="center">- <img src="docs/images/MinerU-logo.png" width="160px" style="vertical-align:middle;">+ <img src="docs/images/MinerU-logo.png" width="300px" style="vertical-align:middle;"></p>-</div>-<div align="center">++<!-- icon -->[](https://github.com/opendatalab/MinerU)[](https://github.com/opendatalab/MinerU)@@ -14,289 +15,382 @@[](https://pepy.tech/project/magic-pdf)<a href="https://trendshift.io/repositories/11174" target="_blank"><img src="https://trendshift.io/api/badge/repositories/11174" alt="opendatalab%2FMinerU | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>-[English](README.md) | [简体中文](README_zh-CN.md) | [日本語](README_ja-JP.md)+<!-- language -->-</div>+[English](README.md) | [简体中文](README_zh-CN.md)++<!-- hot link -->-<div align="center"><p align="center">-<a href="https://github.com/opendatalab/MinerU">MinerU: 端到端的PDF解析工具(基于PDF-Extract-Kit)支持PDF转Markdown</a>🚀🚀🚀<br><a href="https://github.com/opendatalab/PDF-Extract-Kit">PDF-Extract-Kit: 高质量PDF解析工具箱</a>🔥🔥🔥</p>+<!-- join us -->+<p align="center">- 👋 join us on <a href="https://discord.gg/gPxmVeGC" target="_blank">Discord</a> and <a href="https://cdn.vansin.top/internlm/mineru.jpg" target="_blank">WeChat</a>+ 👋 join us on <a href="https://discord.gg/Tdedn9GTXq" target="_blank">Discord</a> and <a href="https://cdn.vansin.top/internlm/mineru.jpg" target="_blank">WeChat</a></p>-</div>--# MinerU---## 简介--MinerU 是一款一站式、开源、高质量的数据提取工具,主要包含以下功能:--- [Magic-PDF](#Magic-PDF) PDF文档提取-- [Magic-Doc](#Magic-Doc) 网页与电子书提取--# Magic-PDF+</div>-## 简介--Magic-PDF 是一款将 PDF 转化为 markdown 格式的工具。支持转换本地文档或者位于支持S3协议对象存储上的文件。--主要功能包含--- 支持多种前端模型输入-- 删除页眉、页脚、脚注、页码等元素-- 符合人类阅读顺序的排版格式-- 保留原文档的结构和格式,包括标题、段落、列表等-- 提取图像和表格并在markdown中展示-- 将公式转换成latex-- 乱码PDF自动识别并转换-- 支持cpu和gpu环境-- 支持windows/linux/mac平台-+# 更新记录++- 2024/08/09 0.7.0b1发布,简化安装步骤提升易用性,加入表格识别功能+- 2024/08/01 0.6.2b1发布,优化了依赖冲突问题和安装文档+- 2024/07/05 首次开源++<!-- TABLE OF CONTENT -->++<details open="open">+ <summary><h2 style="display: inline-block">文档目录</h2></summary>+ <ol>+ <li>+ <a href="#mineru">MinerU</a>+ <ul>+ <li><a href="#项目简介">项目简介</a></li>+ <li><a href="#主要功能">主要功能</a></li>+ <li><a href="#快速开始">快速开始</a>+ <ul>+ <li><a href="#在线体验">在线体验</a></li>+ <li><a href="#使用CPU快速体验">使用CPU快速体验</a></li>+ <li><a href="#使用GPU">使用GPU</a></li>+ </ul>+ </li>+ <li><a href="#使用">使用方式</a>+ <ul>+ <li><a href="#命令行">命令行</a></li>+ <li><a href="#api">API</a></li>+ <li><a href="#二次开发">二次开发</a></li>+ </ul>+ </li>+ </ul>+ </li>+ <li><a href="#todo">TODO</a></li>+ <li><a href="#known-issues">Known Issues</a></li>+ <li><a href="#faq">FAQ</a></li>+ <li><a href="#all-thanks-to-our-contributors">Contributors</a></li>+ <li><a href="#license-information">License Information</a></li>+ <li><a href="#acknowledgments">Acknowledgements</a></li>+ <li><a href="#citation">Citation</a></li>+ <li><a href="#star-history">Star History</a></li>+ <li><a href="#magic-doc">magic-doc快速提取PPT/DOC/PDF</a></li>+ <li><a href="#magic-html">magic-html提取混合网页内容</a></li>+ <li><a href="#links">Links</a></li>+ </ol>+</details>++# MinerU++## 项目简介++MinerU是一款将PDF转化为机器可读格式的工具(如markdown、json),可以很方便地抽取为任意格式。+MinerU诞生于[书生-浦语](https://github.com/InternLM/InternLM)的预训练过程中,我们将会集中精力解决科技文献中的符号转化问题,希望在大模型时代为科技发展做出贡献。+相比国内外知名商用产品MinerU还很年轻,如果遇到问题或者结果不及预期请到[issue](https://github.com/opendatalab/MinerU/issues)提交问题,同时**附上相关PDF**。https://github.com/user-attachments/assets/4bea02c9-6d54-4cd6-97ed-dff14340982c+## 主要功能+- 删除页眉、页脚、脚注、页码等元素,保持语义连贯+- 对多栏输出符合人类阅读顺序的文本+- 保留原文档的结构,包括标题、段落、列表等+- 提取图像、图片标题、表格、表格标题+- 自动识别文档中的公式并将公式转换成latex+- 自动识别文档中的表格并将表格转换成latex+- 乱码PDF自动检测并启用OCR+- 支持CPU和GPU环境+- 支持windows/linux/mac平台-## 项目全景----## 流程图----### 子模块仓库--- [PDF-Extract-Kit](https://github.com/opendatalab/PDF-Extract-Kit)- - 高质量的PDF内容提取工具包--## 上手指南--### 配置要求--python >= 3.9+## 快速开始++如果遇到任何安装问题,请先查询 <a href="#faq">FAQ</a> </br>+如果遇到解析效果不及预期,参考 <a href="#known-issues">Known Issues</a></br>+有3种不同方式可以体验MinerU的效果:++- [在线体验(无需任何安装)](#在线体验)+- [使用CPU快速体验(Windows,Linux,Mac)](#使用cpu快速体验)+- [Linux/Windows + CUDA](#使用gpu)++**⚠️安装前必看——软硬件环境支持说明**++为了确保项目的稳定性和可靠性,我们在开发过程中仅对特定的软硬件环境进行优化和测试。这样当用户在推荐的系统配置上部署和运行项目时,能够获得最佳的性能表现和最少的兼容性问题。++通过集中资源和精力于主线环境,我们团队能够更高效地解决潜在的BUG,及时开发新功能。++在非主线环境中,由于硬件、软件配置的多样性,以及第三方依赖项的兼容性问题,我们无法100%保证项目的完全可用性。因此,对于希望在非推荐环境中使用本项目的用户,我们建议先仔细阅读文档以及FAQ,大多数问题已经在FAQ中有对应的解决方案,除此之外我们鼓励社区反馈问题,以便我们能够逐步扩大支持范围。++<table>+ <tr>+ <td colspan="3" rowspan="2">操作系统</td>+ </tr>+ <tr>+ <td>Ubuntu 22.04 LTS</td>+ <td>Windows 10 / 11</td>+ <td>macOS 11+</td>+ </tr>+ <tr>+ <td colspan="3">CPU</td>+ <td>x86_64</td>+ <td>x86_64</td>+ <td>x86_64 / arm64</td>+ </tr>+ <tr>+ <td colspan="3">内存</td>+ <td colspan="3">大于等于16GB,推荐32G以上</td>+ </tr>+ <tr>+ <td colspan="3">python版本</td>+ <td colspan="3">3.10</td>+ </tr>+ <tr>+ <td colspan="3">Nvidia Driver 版本</td>+ <td>latest(专有驱动)</td>+ <td>latest</td>+ <td>None</td>+ </tr>+ <tr>+ <td colspan="3">CUDA环境</td>+ <td>自动安装[12.1(pytorch)+11.8(paddle)]</td>+ <td>11.8(手动安装)+cuDNN v8.7.0(手动安装)</td>+ <td>None</td>+ </tr>+ <tr>+ <td rowspan="2">GPU硬件支持列表</td>+ <td colspan="2">最低要求 8G+显存</td>+ <td colspan="2">3060ti/3070/3080/3080ti/4060/4070/4070ti<br>+ 8G显存仅可开启lavout和公式识别加速</td>+ <td rowspan="2">None</td>+ </tr>+ <tr>+ <td colspan="2">推荐配置 16G+显存</td>+ <td colspan="2">3090/3090ti/4070tisuper/4080/4090<br>+ 16G及以上可以同时开启layout,公式识别和ocr加速</td>+ </tr>+</table>++### 在线体验++[在线体验点击这里](https://opendatalab.com/OpenSourceTools/Extractor/PDF)++### 使用CPU快速体验++#### 1. 安装magic-pdf++最新版本国内镜像源同步可能会有延迟,请耐心等待-推荐使用虚拟环境,以避免可能发生的依赖冲突,venv和conda均可使用。-例如:```bashconda create -n MinerU python=3.10conda activate MinerU+pip install magic-pdf[full]==0.7.0b1 --extra-index-url https://wheels.myhloli.com -i https://pypi.tuna.tsinghua.edu.cn/simple```-开发基于python 3.10,如果在其他版本python出现问题请切换至3.10。--### 安装配置--#### 1. 安装Magic-PDF--**1.安装依赖**--完整功能包依赖detectron2,该库需要编译安装,如需自行编译,请参考 https://github.com/facebookresearch/detectron2/issues/5114-或是直接使用我们预编译的whl包:-> ❗️预编译版本仅支持64位系统(windows/linux/macOS)+pyton 3.10平台;不支持任何32位系统和非mac的arm平台,如系统不支持请自行编译安装。-```bash-pip install detectron2 --extra-index-url https://wheels.myhloli.com -i https://pypi.tuna.tsinghua.edu.cn/simple-```--**2.使用pip安装完整功能包**-> 受pypi限制,pip安装的完整功能包仅支持cpu推理,建议只用于快速测试解析能力。->-> 如需在生产环境使用CUDA/MPS加速请参考[使用CUDA或MPS加速推理](#4-使用CUDA或MPS加速推理)-```bash-pip install magic-pdf[full]==0.6.2b1 -i https://pypi.tuna.tsinghua.edu.cn/simple-```-> ❗️❗️❗️-> 我们预发布了0.6.2beta版本,该版本解决了很多issue中提出的问题,同时提高了安装成功率。但是该版本未经过完整的QA测试,不代表最终正式发布的质量水平。如果你遇到任何问题,请通过提交issue的方式及时向我们反馈,或者回退到使用0.6.1版本。-> ```bash-> pip install magic-pdf[full-cpu]==0.6.1-> ```--#### 2. 下载模型权重文件-详细参考 [如何下载模型文件](docs/how_to_download_models_zh_cn.md)+详细参考 [如何下载模型文件](docs/how_to_download_models_zh_cn.md)+> ❗️模型下载后请务必检查模型文件是否下载完整->+>> 请检查目录下的模型文件大小与网页上描述是否一致,如果可以的话,最好通过sha256校验模型是否下载完整#### 3. 拷贝配置文件并进行配置+在仓库根目录可以获得 [magic-pdf.template.json](magic-pdf.template.json) 配置模版文件+> ❗️务必执行以下命令将配置文件拷贝到【用户目录】下,否则程序将无法运行->-> windows的用户目录为 "C:\Users\用户名", linux用户目录为 "/home/用户名", macOS用户目录为 "/Users/用户名"+>+> windows的用户目录为 "C:\\Users\\用户名", linux用户目录为 "/home/用户名", macOS用户目录为 "/Users/用户名"+```bashcp magic-pdf.template.json ~/magic-pdf.json```在用户目录中找到magic-pdf.json文件并配置"models-dir"为[2. 下载模型权重文件](#2-下载模型权重文件)中下载的模型权重文件所在目录+> ❗️务必正确配置模型权重文件所在目录的【绝对路径】,否则会因为找不到模型文件而导致程序无法运行+>+> windows系统中此路径应包含盘符,且需把路径中所有的`"\"`替换为`"/"`,否则会因为转义原因导致json文件语法错误。>-> windows系统中此路径应包含盘符,且需把路径中所有的"\"替换为"/",否则会因为转义原因导致json文件语法错误。->-> 例如:模型放在D盘根目录的models目录,则model-dir的值应为"D:/models"-```json-{- "models-dir": "/tmp/models"-}-```-#### 4. 使用CUDA或MPS加速推理-如您有可用的Nvidia显卡或在使用Apple Silicon的Mac,可以使用CUDA或MPS进行加速-##### CUDA+> 例如:模型放在D盘根目录的models目录,则model-dir的值应为"D:/models"-需要根据自己的CUDA版本安装对应的pytorch版本-以下是对应CUDA 11.8版本的安装命令,更多信息请参考 https://pytorch.org/get-started/locally/-```bash-pip install --force-reinstall torch==2.3.1 torchvision==0.18.1 --index-url https://download.pytorch.org/whl/cu118-```-> ❗️务必在命令中指定以下版本-> ```bash-> torch==2.3.1 torchvision==0.18.1-> ```-> 这是我们支持的最高版本,如果不指定版本会自动安装更高版本导致程序无法运行---同时需要修改【用户目录】中配置文件magic-pdf.json中"device-mode"的值```json{- "device-mode":"cuda"+ // other config+ "models-dir": "D:/models",+ "table-config": {+ "is_table_recog_enable": false, // 表格识别功能默认是关闭的,如果需要修改此处的值+ "max_time": 400+ }}```-##### MPS-使用macOS(M系列芯片设备)可以使用MPS进行推理加速-需要修改配置文件magic-pdf.json中"device-mode"的值-```json-{- "device-mode":"mps"-}-```+### 使用GPU+如果您的设备支持CUDA,且满足主线环境中的显卡要求,则可以使用GPU加速,请根据自己的系统选择适合的教程:-### 使用说明+- [Ubuntu22.04LTS + GPU](docs/README_Ubuntu_CUDA_Acceleration_zh_CN.md)+- [Windows10/11 + GPU](docs/README_Windows_CUDA_Acceleration_zh_CN.md)+- 使用Docker快速部署+ > Docker 需设备gpu显存大于等于16GB,默认开启所有加速功能+ ```bash+ wget https://github.com/opendatalab/MinerU/raw/master/Dockerfile+ docker build -t mineru:0.7.0b1 .+ docker run --rm -it --gpus=all mineru:0.7.0b1 /bin/bash+ magic-pdf --help+ ```+-#### 1. 通过命令行使用+## 使用-###### 直接使用+### 命令行```bash-magic-pdf pdf-command --pdf "pdf_path" --inside_model true-```-程序运行完成后,你可以在"/tmp/magic-pdf"目录下看到生成的markdown文件,markdown目录中可以找到对应的xxx_model.json文件-如果您有意对后处理pipeline进行二次开发,可以使用命令-```bash-magic-pdf pdf-command --pdf "pdf_path" --model "model_json_path"+magic-pdf --help+Usage: magic-pdf [OPTIONS]++Options:+ -v, --version display the version and exit+ -p, --path PATH local pdf filepath or directory [required]+ -o, --output-dir TEXT output local directory+ -m, --method [ocr|txt|auto] the method for parsing pdf.+ ocr: using ocr technique to extract information from pdf,+ txt: suitable for the text-based pdf only and outperform ocr,+ auto: automatically choose the best method for parsing pdf+ from ocr and txt.+ without method specified, auto will be used by default.+ --help Show this message and exit.+++## show version+magic-pdf -v++## command line example+magic-pdf -p {some_pdf} -o {some_output_dir} -m auto```-这样就不需要重跑模型数据,调试起来更方便--###### 更多用法-```bash-magic-pdf --help+其中 `{some_pdf}` 可以是单个pdf文件,也可以是一个包含多个pdf文件的目录。+运行完命令后输出的结果会保存在`{some_output_dir}`目录下, 输出的文件列表如下++```text+├── some_pdf.md # markdown 文件+├── images # 存放图片目录+├── some_pdf_layout.pdf # layout 绘图+├── some_pdf_middle.json # minerU 中间处理结果+├── some_pdf_model.json # 模型推理结果+├── some_pdf_origin.pdf # 原 pdf 文件+└── some_pdf_spans.pdf # 最小粒度的bbox位置信息绘图```+更多有关输出文件的信息,请参考[输出文件说明](docs/output_file_zh_cn.md)-#### 2. 通过接口调用+### API++处理本地磁盘上的文件-###### 本地使用```pythonimage_writer = DiskReaderWriter(local_image_dir)image_dir = str(os.path.basename(local_image_dir))-jso_useful_key = {"_pdf_type": "", "model_list": model_json}+jso_useful_key = {"_pdf_type": "", "model_list": []}pipe = UNIPipe(pdf_bytes, jso_useful_key, image_writer)pipe.pipe_classify()+pipe.pipe_analyze()pipe.pipe_parse()md_content = pipe.pipe_mk_markdown(image_dir, drop_mode="none")```-###### 在对象存储上使用+处理对象存储上的文件+```pythons3pdf_cli = S3ReaderWriter(pdf_ak, pdf_sk, pdf_endpoint)image_dir = "s3://img_bucket/"s3image_cli = S3ReaderWriter(img_ak, img_sk, img_endpoint, parent_path=image_dir)pdf_bytes = s3pdf_cli.read(s3_pdf_path, mode=s3pdf_cli.MODE_BIN)-jso_useful_key = {"_pdf_type": "", "model_list": model_json}+jso_useful_key = {"_pdf_type": "", "model_list": []}pipe = UNIPipe(pdf_bytes, jso_useful_key, s3image_cli)pipe.pipe_classify()+pipe.pipe_analyze()pipe.pipe_parse()md_content = pipe.pipe_mk_markdown(image_dir, drop_mode="none")```-详细实现可参考 [demo.py](demo/demo.py)---### 常见问题处理解答--参考 [FAQ](docs/FAQ_zh_cn.md)---# Magic-Doc---## 简介--Magic-Doc 是一款支持将网页或多格式电子书转换为 markdown 格式的工具。--主要功能包含--- Web网页提取- - 跨模态精准解析图文、表格、公式信息+详细实现可参考-- 电子书文献提取- - 支持 epub,mobi等多格式文献,文本图片全适配+- [demo.py 最简单的处理方式](demo/demo.py)+- [magic_pdf_parse_main.py 能够更清晰看到处理流程](demo/magic_pdf_parse_main.py)-- 语言类型鉴定- - 支持176种语言的准确识别+### 二次开发-https://github.com/opendatalab/MinerU/assets/11393164/a5a650e9-f4c0-463e-acc3-960967f1a1ca+TODO+# TODO+- [ ] 基于语义的阅读顺序+- [ ] 正文中列表识别+- [ ] 正文中代码块识别+- [ ] 目录识别+- [x] 表格识别+- [ ] [化学式识别](docs/chemical_knowledge_introduction/introduction.pdf)+- [ ] 几何图形识别-https://github.com/opendatalab/MinerU/assets/11393164/0f4a6fe9-6cca-4113-9fdc-a537749d764d+# Known Issues+- 阅读顺序基于规则的分割,在一些情况下会乱序+- 不支持竖排文字+- 列表、代码块、目录在layout模型里还没有支持+- 漫画书、艺术图册、小学教材、习题尚不能很好解析+- 在一些公式密集的PDF上强制启用OCR效果会更好+- 如果您要处理包含大量公式的pdf,强烈建议开启OCR功能。使用pymuPDF提取文字的时候会出现文本行互相重叠的情况导致公式插入位置不准确。+- **表格识别**目前处于测试阶段,识别速度较慢,识别准确度有待提升。以下是我们在Ubuntu 22.04 LTS + Intel(R) Xeon(R) Platinum 8352V CPU @ 2.10GHz + NVIDIA GeForce RTX 4090环境下的一些性能测试结果,可供参考。+| 表格大小 | 解析耗时 |+| ------------ | -------- |+| 6\*5 55kb | 37s |+| 16\*12 284kb | 3m18s |+| 44\*7 559kb | 4m12s |-https://github.com/opendatalab/MinerU/assets/11393164/20438a02-ce6c-4af8-9dde-d722a4e825b2+# FAQ+[常见问题](docs/FAQ_zh_cn.md)+<<<<<<< HEAD+=======+[FAQ](docs/FAQ_en_us.md)+>>>>>>> 7f0fe20004af7416db886f4b75c116bcc1c986b4-## 项目仓库+[FAQ](docs/FAQ_en_us.md)-- [Magic-Doc](https://github.com/InternLM/magic-doc)- 优秀的网页与电子书提取工具---## 感谢我们的贡献者+# All Thanks To Our Contributors<a href="https://github.com/opendatalab/MinerU/graphs/contributors"><img src="https://contrib.rocks/image?repo=opendatalab/MinerU" /></a>--## 版权说明+# License Information[LICENSE.md](LICENSE.md)本项目目前采用PyMuPDF以实现高级功能,但因其遵循AGPL协议,可能对某些使用场景构成限制。未来版本迭代中,我们计划探索并替换为许可条款更为宽松的PDF处理库,以提升用户友好度及灵活性。+# Acknowledgments-## 致谢+- [PDF-Extract-Kit](https://github.com/opendatalab/PDF-Extract-Kit)+- [StructEqTable](https://github.com/UniModal4Reasoning/StructEqTable-Deploy)- [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR)- [PyMuPDF](https://github.com/pymupdf/PyMuPDF)- [fast-langdetect](https://github.com/LlmKira/fast-langdetect)- [pdfminer.six](https://github.com/pdfminer/pdfminer.six)--# 引用+# Citation```bibtex+@article{he2024opendatalab,+ title={Opendatalab: Empowering general artificial intelligence with open datasets},+ author={He, Conghui and Li, Wei and Jin, Zhenjiang and Xu, Chao and Wang, Bin and Lin, Dahua},+ journal={arXiv preprint arXiv:2407.13773},+ year={2024}+}+@misc{2024mineru,title={MinerU: A One-stop, Open-source, High-quality Data Extraction Tool},author={MinerU Contributors},@@ -305,7 +399,6 @@ https://github.com/opendatalab/MinerU/assets/11393164/20438a02-ce6c-4af8-9dde-d7}```-# Star History<a>@@ -316,7 +409,16 @@ https://github.com/opendatalab/MinerU/assets/11393164/20438a02-ce6c-4af8-9dde-d7</picture></a>-## 友情链接-- [LabelU (轻量级多模态标注工具)](https://github.com/opendatalab/labelU)-- [LabelLLM (开源LLM对话标注平台)](https://github.com/opendatalab/LabelLLM)-- [PDF-Extract-Kit (用于高质量PDF内容提取的综合工具包)](https://github.com/opendatalab/PDF-Extract-Kit))+# Magic-doc++[Magic-Doc](https://github.com/InternLM/magic-doc) Fast speed ppt/pptx/doc/docx/pdf extraction tool++# Magic-html++[Magic-HTML](https://github.com/opendatalab/magic-html) Mixed web page extraction tool++# Links++- [LabelU (A Lightweight Multi-modal Data Annotation Tool)](https://github.com/opendatalab/labelU)+- [LabelLLM (An Open-source LLM Dialogue Annotation Platform)](https://github.com/opendatalab/LabelLLM)+- [PDF-Extract-Kit (A Comprehensive Toolkit for High-Quality PDF Content Extraction)](https://github.com/opendatalab/PDF-Extract-Kit)diff --git a/app.py b/app.pynew file mode 100644index 00000000..ec14972f--- /dev/null+++ b/app.py@@ -0,0 +1,167 @@+# Copyright (c) Opendatalab. All rights reserved.++import base64+import os+import time+import zipfile+from pathlib import Path+import re++from loguru import logger++from magic_pdf.libs.hash_utils import compute_sha256+from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter+from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter+from magic_pdf.tools.common import do_parse, prepare_env++os.system("pip install gradio")+os.system("pip install gradio-pdf")+import gradio as gr+from gradio_pdf import PDF+++def read_fn(path):+ disk_rw = DiskReaderWriter(os.path.dirname(path))+ return disk_rw.read(os.path.basename(path), AbsReaderWriter.MODE_BIN)+++def parse_pdf(doc_path, output_dir, end_page_id):+ os.makedirs(output_dir, exist_ok=True)++ try:+ file_name = f"{str(Path(doc_path).stem)}_{time.time()}"+ pdf_data = read_fn(doc_path)+ parse_method = "auto"+ local_image_dir, local_md_dir = prepare_env(output_dir, file_name, parse_method)+ do_parse(+ output_dir,+ file_name,+ pdf_data,+ [],+ parse_method,+ False,+ end_page_id=end_page_id,+ )+ return local_md_dir, file_name+ except Exception as e:+ logger.exception(e)+++def compress_directory_to_zip(directory_path, output_zip_path):+ """+ 压缩指定目录到一个 ZIP 文件。++ :param directory_path: 要压缩的目录路径+ :param output_zip_path: 输出的 ZIP 文件路径+ """+ try:+ with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:++ # 遍历目录中的所有文件和子目录+ for root, dirs, files in os.walk(directory_path):+ for file in files:+ # 构建完整的文件路径+ file_path = os.path.join(root, file)+ # 计算相对路径+ arcname = os.path.relpath(file_path, directory_path)+ # 添加文件到 ZIP 文件+ zipf.write(file_path, arcname)+ return 0+ except Exception as e:+ logger.exception(e)+ return -1+++def image_to_base64(image_path):+ with open(image_path, "rb") as image_file:+ return base64.b64encode(image_file.read()).decode('utf-8')+++def replace_image_with_base64(markdown_text, image_dir_path):+ # 匹配Markdown中的图片标签+ pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)'++ # 替换图片链接+ def replace(match):+ relative_path = match.group(1)+ full_path = os.path.join(image_dir_path, relative_path)+ base64_image = image_to_base64(full_path)+ return f""++ # 应用替换+ return re.sub(pattern, replace, markdown_text)+++def to_markdown(file_path, end_pages):+ # 获取识别的md文件以及压缩包文件路径+ local_md_dir, file_name = parse_pdf(file_path, './output', end_pages - 1)+ archive_zip_path = os.path.join("./output", compute_sha256(local_md_dir) + ".zip")+ zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)+ if zip_archive_success == 0:+ logger.info("压缩成功")+ else:+ logger.error("压缩失败")+ md_path = os.path.join(local_md_dir, file_name + ".md")+ with open(md_path, 'r', encoding='utf-8') as f:+ txt_content = f.read()+ md_content = replace_image_with_base64(txt_content, local_md_dir)+ # 返回转换后的PDF路径+ new_pdf_path = os.path.join(local_md_dir, file_name + "_layout.pdf")++ return md_content, txt_content, archive_zip_path, new_pdf_path+++# def show_pdf(file_path):+# with open(file_path, "rb") as f:+# base64_pdf = base64.b64encode(f.read()).decode('utf-8')+# pdf_display = f'<embed src="data:application/pdf;base64,{base64_pdf}" ' \+# f'width="100%" height="1000" type="application/pdf">'+# return pdf_display+++latex_delimiters = [{"left": "$$", "right": "$$", "display": True},+ {"left": '$', "right": '$', "display": False}]+++def init_model():+ from magic_pdf.model.doc_analyze_by_custom_model import ModelSingleton+ try:+ model_manager = ModelSingleton()+ txt_model = model_manager.get_model(False, False)+ logger.info(f"txt_model init final")+ ocr_model = model_manager.get_model(True, False)+ logger.info(f"ocr_model init final")+ return 0+ except Exception as e:+ logger.exception(e)+ return -1+++model_init = init_model()+logger.info(f"model_init: {model_init}")+++if __name__ == "__main__":+ with gr.Blocks() as demo:+ with gr.Row():+ with gr.Column(variant='panel', scale=5):+ pdf_show = gr.Markdown()+ max_pages = gr.Slider(1, 10, 5, step=1, label="Max convert pages")+ with gr.Row() as bu_flow:+ change_bu = gr.Button("Convert")+ clear_bu = gr.ClearButton([pdf_show], value="Clear")+ pdf_show = PDF(label="Please upload pdf", interactive=True, height=800)++ with gr.Column(variant='panel', scale=5):+ output_file = gr.File(label="convert result", interactive=False)+ with gr.Tabs():+ with gr.Tab("Markdown rendering"):+ md = gr.Markdown(label="Markdown rendering", height=900, show_copy_button=True,+ latex_delimiters=latex_delimiters, line_breaks=True)+ with gr.Tab("Markdown text"):+ md_text = gr.TextArea(lines=45, show_copy_button=True)+ change_bu.click(fn=to_markdown, inputs=[pdf_show, max_pages], outputs=[md, md_text, output_file, pdf_show])+ clear_bu.add([md, pdf_show, md_text, output_file])++ demo.launch()+diff --git a/docs/chemical_knowledge_introduction/introduction.pdf b/docs/chemical_knowledge_introduction/introduction.pdfnew file mode 100644index 00000000..9ececd8fBinary files /dev/null and b/docs/chemical_knowledge_introduction/introduction.pdf differdiff --git a/docs/chemical_knowledge_introduction/introduction.xmind b/docs/chemical_knowledge_introduction/introduction.xmindnew file mode 100644index 00000000..a73d2c15Binary files /dev/null and b/docs/chemical_knowledge_introduction/introduction.xmind differdiff --git a/docs/output_file_en_us.md b/docs/output_file_en_us.mdindex bf8f5f4f..1fe9a127 100644--- a/docs/output_file_en_us.md+++ b/docs/output_file_en_us.md@@ -1,24 +1,23 @@--## Overview+After executing the `magic-pdf` command, in addition to outputting files related to markdown, several other files unrelated to markdown will also be generated. These files will be introduced one by one.+### some_pdf_layout.pdf-### layout.pdfEach page layout consists of one or more boxes. The number at the top left of each box indicates its sequence number. Additionally, in `layout.pdf`, different content blocks are highlighted with different background colors.+### some_pdf_spans.pdf-### spans.pdfAll spans on the page are drawn with different colored line frames according to the span type. This file can be used for quality control, allowing for quick identification of issues such as missing text or unrecognized inline formulas.--### model.json+### some_pdf_model.json#### Structure Definition+```pythonfrom pydantic import BaseModel, Fieldfrom enum import IntEnum@@ -34,12 +33,12 @@ class CategoryType(IntEnum):table_footnote = 7 # Table footnoteisolate_formula = 8 # Block formulaformula_caption = 9 # Formula label-+embedding = 13 # Inline formulaisolated = 14 # Block formulatext = 15 # OCR recognition result--++class PageInfo(BaseModel):page_no: int = Field(description="Page number, the first page is 0", ge=0)height: int = Field(description="Page height", gt=0)@@ -51,22 +50,20 @@ class ObjectInferenceResult(BaseModel):score: float = Field(description="Confidence of the inference result")latex: str | None = Field(description="LaTeX parsing result", default=None)html: str | None = Field(description="HTML parsing result", default=None)-+class PageInferenceResults(BaseModel):layout_dets: list[ObjectInferenceResult] = Field(description="Page recognition results", ge=0)page_info: PageInfo = Field(description="Page metadata")--++# The inference results of all pages, ordered by page number, are stored in a list as the inference results of MinerUinference_result: list[PageInferenceResults] = []```-The format of the poly coordinates is [x0, y0, x1, y1, x2, y2, x3, y3], representing the coordinates of the top-left, top-right, bottom-right, and bottom-left points respectively.+The format of the poly coordinates is \[x0, y0, x1, y1, x2, y2, x3, y3\], representing the coordinates of the top-left, top-right, bottom-right, and bottom-left points respectively.--#### example```json@@ -120,15 +117,13 @@ The format of the poly coordinates is [x0, y0, x1, y1, x2, y2, x3, y3], represen]```+### some_pdf_middle.json-### middle.json--| Field Name | Description |-| :-----|:------------------------------------------|-|pdf_info | list, each element is a dict representing the parsing result of each PDF page, see the table below for details |-|_parse_type | ocr \| txt, used to indicate the mode used in this intermediate parsing state |-|_version_name | string, indicates the version of magic-pdf used in this parsing |-+| Field Name | Description |+| :------------- | :------------------------------------------------------------------------------------------------------------- |+| pdf_info | list, each element is a dict representing the parsing result of each PDF page, see the table below for details |+| \_parse_type | ocr \| txt, used to indicate the mode used in this intermediate parsing state |+| \_version_name | string, indicates the version of magic-pdf used in this parsing |<br>@@ -136,18 +131,18 @@ The format of the poly coordinates is [x0, y0, x1, y1, x2, y2, x3, y3], represenField structure description-| Field Name | Description |-| :-----| :---- |-| preproc_blocks | Intermediate result after PDF preprocessing, not yet segmented |-| layout_bboxes | Layout segmentation results, containing layout direction (vertical, horizontal), and bbox, sorted by reading order |-| page_idx | Page number, starting from 0 |-| page_size | Page width and height |-| _layout_tree | Layout tree structure |-| images | list, each element is a dict representing an img_block |-| tables | list, each element is a dict representing a table_block |-| interline_equations | list, each element is a dict representing an interline_equation_block |-| discarded_blocks | List, block information returned by the model that needs to be dropped |-| para_blocks | Result after segmenting preproc_blocks |+| Field Name | Description |+| :------------------ | :----------------------------------------------------------------------------------------------------------------- |+| preproc_blocks | Intermediate result after PDF preprocessing, not yet segmented |+| layout_bboxes | Layout segmentation results, containing layout direction (vertical, horizontal), and bbox, sorted by reading order |+| page_idx | Page number, starting from 0 |+| page_size | Page width and height |+| \_layout_tree | Layout tree structure |+| images | list, each element is a dict representing an img_block |+| tables | list, each element is a dict representing a table_block |+| interline_equations | list, each element is a dict representing an interline_equation_block |+| discarded_blocks | List, block information returned by the model that needs to be dropped |+| para_blocks | Result after segmenting preproc_blocks |In the above table, `para_blocks` is an array of dicts, each dict representing a block structure. A block can support up to one level of nesting.@@ -157,35 +152,35 @@ In the above table, `para_blocks` is an array of dicts, each dict representing aThe outer block is referred to as a first-level block, and the fields in the first-level block include:-| Field Name | Description |-| :-----| :---- |-| type | Block type (table\|image)|-|bbox | Block bounding box coordinates |-|blocks |list, each element is a dict representing a second-level block |+| Field Name | Description |+| :--------- | :------------------------------------------------------------- |+| type | Block type (table\|image) |+| bbox | Block bounding box coordinates |+| blocks | list, each element is a dict representing a second-level block |<br>There are only two types of first-level blocks: "table" and "image". All other blocks are second-level blocks.The fields in a second-level block include:-| Field Name | Description |-| :-----| :---- |-| type | Block type |-| bbox | Block bounding box coordinates |-| lines | list, each element is a dict representing a line, used to describe the composition of a line of information|+| Field Name | Description |+| :--------- | :---------------------------------------------------------------------------------------------------------- |+| type | Block type |+| bbox | Block bounding box coordinates |+| lines | list, each element is a dict representing a line, used to describe the composition of a line of information |Detailed explanation of second-level block types-| type | Description |-|:-------------------| :---- |+| type | Description |+| :----------------- | :--------------------- || image_body | Main body of the image || image_caption | Image description text || table_body | Main body of the table || table_caption | Table description text |-| table_footnote | Table footnote |-| text | Text block |-| title | Title block |-| interline_equation | Block formula|+| table_footnote | Table footnote |+| text | Text block |+| title | Title block |+| interline_equation | Block formula |<br>@@ -193,31 +188,30 @@ Detailed explanation of second-level block typesThe field format of a line is as follows:-| Field Name | Description |-| :-----| :---- |-| bbox | Bounding box coordinates of the line |-| spans | list, each element is a dict representing a span, used to describe the composition of the smallest unit |-+| Field Name | Description |+| :--------- | :------------------------------------------------------------------------------------------------------ |+| bbox | Bounding box coordinates of the line |+| spans | list, each element is a dict representing a span, used to describe the composition of the smallest unit |<br>**span**-| Field Name | Description |-| :-----| :---- |-| bbox | Bounding box coordinates of the span |-| type | Type of the span |+| Field Name | Description |+| :------------------ | :------------------------------------------------------------------------------------------------------- |+| bbox | Bounding box coordinates of the span |+| type | Type of the span || content \| img_path | Text spans use content, chart spans use img_path to store the actual text or screenshot path information |The types of spans are as follows:-| type | Description |-| :-----| :---- |-| image | Image |-| table | Table |-| text | Text |-| inline_equation | Inline formula |-| interline_equation | Block formula |+| type | Description |+| :----------------- | :------------- |+| image | Image |+| table | Table |+| text | Text |+| inline_equation | Inline formula |+| interline_equation | Block formula |**Summary**@@ -229,7 +223,6 @@ The block structure is as follows:First-level block (if any) -> Second-level block -> Line -> Span-#### example```jsondiff --git a/docs/output_file_zh_cn.md b/docs/output_file_zh_cn.mdindex 393e8e0d..dd921da9 100644--- a/docs/output_file_zh_cn.md+++ b/docs/output_file_zh_cn.md@@ -1,24 +1,23 @@--## 概览+`magic-pdf` 命令执行后除了输出和 markdown 有关的文件以外,还会生成若干个和 markdown 无关的文件。现在将一一介绍这些文件+### some_pdf_layout.pdf-### layout.pdf每一页的 layout 均由一个或多个框组成。 每个框左上脚的数字表明它们的序号。此外 layout.pdf 框内用不同的背景色块圈定不同的内容块。+### some_pdf_spans.pdf-### spans.pdf根据 span 类型的不同,采用不同颜色线框绘制页面上所有 span。该文件可以用于质检,可以快速排查出文本丢失、行间公式未识别等问题。--### model.json+### some_pdf_model.json#### 结构定义+```pythonfrom pydantic import BaseModel, Fieldfrom enum import IntEnum@@ -33,13 +32,13 @@ class CategoryType(IntEnum):table_caption = 6 # 表格描述table_footnote = 7 # 表格注释isolate_formula = 8 # 行间公式- formula_caption = 9 # 行间公式的标号-+ formula_caption = 9 # 行间公式的标号+embedding = 13 # 行内公式isolated = 14 # 行间公式text = 15 # ocr 识别结果--++class PageInfo(BaseModel):page_no: int = Field(description="页码序号,第一页的序号是 0", ge=0)height: int = Field(description="页面高度", gt=0)@@ -51,21 +50,20 @@ class ObjectInferenceResult(BaseModel):score: float = Field(description="推理结果的置信度")latex: str | None = Field(description="latex 解析结果", default=None)html: str | None = Field(description="html 解析结果", default=None)-+class PageInferenceResults(BaseModel):layout_dets: list[ObjectInferenceResult] = Field(description="页面识别结果", ge=0)page_info: PageInfo = Field(description="页面元信息")--++# 所有页面的推理结果按照页码顺序依次放到列表中即为 minerU 推理结果inference_result: list[PageInferenceResults] = []```-poly 坐标的格式 [x0, y0, x1, y1, x2, y2, x3, y3], 分别表示左上、右上、右下、左下四点的坐标+poly 坐标的格式 \[x0, y0, x1, y1, x2, y2, x3, y3\], 分别表示左上、右上、右下、左下四点的坐标-#### 示例数据```json@@ -119,32 +117,31 @@ poly 坐标的格式 [x0, y0, x1, y1, x2, y2, x3, y3], 分别表示左上、右]```+### some_pdf_middle.json-### middle.json--| 字段名 | 解释 |-| :-----|:------------------------------------------|-|pdf_info | list,每个元素都是一个dict,这个dict是每一页pdf的解析结果,详见下表 |-|_parse_type | ocr \| txt,用来标识本次解析的中间态使用的模式 |-|_version_name | string, 表示本次解析使用的 magic-pdf 的版本号 |+| 字段名 | 解释 |+| :------------- | :----------------------------------------------------------------- |+| pdf_info | list,每个元素都是一个dict,这个dict是每一页pdf的解析结果,详见下表 |+| \_parse_type | ocr \| txt,用来标识本次解析的中间态使用的模式 |+| \_version_name | string, 表示本次解析使用的 magic-pdf 的版本号 |<br>**pdf_info**字段结构说明-| 字段名 | 解释 |-| :-----| :---- |-| preproc_blocks | pdf预处理后,未分段的中间结果 |-| layout_bboxes | 布局分割的结果,含有布局的方向(垂直、水平),和bbox,按阅读顺序排序 |-| page_idx | 页码,从0开始 |-| page_size | 页面的宽度和高度 |-| _layout_tree | 布局树状结构 |-| images | list,每个元素是一个dict,每个dict表示一个img_block |-| tables | list,每个元素是一个dict,每个dict表示一个table_block |-| interline_equations | list,每个元素是一个dict,每个dict表示一个interline_equation_block |-| discarded_blocks | List, 模型返回的需要drop的block信息 |-| para_blocks | 将preproc_blocks进行分段之后的结果 |+| 字段名 | 解释 |+| :------------------ | :------------------------------------------------------------------- |+| preproc_blocks | pdf预处理后,未分段的中间结果 |+| layout_bboxes | 布局分割的结果,含有布局的方向(垂直、水平),和bbox,按阅读顺序排序 |+| page_idx | 页码,从0开始 |+| page_size | 页面的宽度和高度 |+| \_layout_tree | 布局树状结构 |+| images | list,每个元素是一个dict,每个dict表示一个img_block |+| tables | list,每个元素是一个dict,每个dict表示一个table_block |+| interline_equations | list,每个元素是一个dict,每个dict表示一个interline_equation_block |+| discarded_blocks | List, 模型返回的需要drop的block信息 |+| para_blocks | 将preproc_blocks进行分段之后的结果 |上表中 `para_blocks` 是个dict的数组,每个dict是一个block结构,block最多支持一次嵌套@@ -154,35 +151,35 @@ poly 坐标的格式 [x0, y0, x1, y1, x2, y2, x3, y3], 分别表示左上、右外层block被称为一级block,一级block中的字段包括-| 字段名 | 解释 |-| :-----| :---- |-| type | block类型(table\|image)|-|bbox | block矩形框坐标 |-|blocks |list,里面的每个元素都是一个dict格式的二级block |+| 字段名 | 解释 |+| :----- | :---------------------------------------------- |+| type | block类型(table\|image) |+| bbox | block矩形框坐标 |+| blocks | list,里面的每个元素都是一个dict格式的二级block |<br>一级block只有"table"和"image"两种类型,其余block均为二级block二级block中的字段包括-| 字段名 | 解释 |-| :-----| :---- |-| type | block类型 |-| bbox | block矩形框坐标 |-| lines | list,每个元素都是一个dict表示的line,用来描述一行信息的构成|+| 字段名 | 解释 |+| :----- | :----------------------------------------------------------- |+| type | block类型 |+| bbox | block矩形框坐标 |+| lines | list,每个元素都是一个dict表示的line,用来描述一行信息的构成 |二级block的类型详解-| type | desc |-|:-------------------| :---- |-| image_body | 图像的本体 |+| type | desc |+| :----------------- | :------------- |+| image_body | 图像的本体 || image_caption | 图像的描述文本 |-| table_body | 表格本体 |+| table_body | 表格本体 || table_caption | 表格的描述文本 |-| table_footnote | 表格的脚注 |-| text | 文本块 |-| title | 标题块 |-| interline_equation | 行间公式块|+| table_footnote | 表格的脚注 |+| text | 文本块 |+| title | 标题块 |+| interline_equation | 行间公式块 |<br>@@ -190,33 +187,31 @@ poly 坐标的格式 [x0, y0, x1, y1, x2, y2, x3, y3], 分别表示左上、右line 的 字段格式如下-| 字段名 | 解释 |-| :-----| :---- |-| bbox | line的矩形框坐标 |-| spans | list,每个元素都是一个dict表示的span,用来描述一个最小组成单元的构成 |-+| 字段名 | 解释 |+| :----- | :------------------------------------------------------------------- |+| bbox | line的矩形框坐标 |+| spans | list,每个元素都是一个dict表示的span,用来描述一个最小组成单元的构成 |<br>**span**-| 字段名 | 解释 |-| :-----| :---- |-| bbox | span的矩形框坐标 |-| type | span的类型 |+| 字段名 | 解释 |+| :------------------ | :------------------------------------------------------------------------------- |+| bbox | span的矩形框坐标 |+| type | span的类型 || content \| img_path | 文本类型的span使用content,图表类使用img_path 用来存储实际的文本或者截图路径信息 |span 的类型有如下几种-| type | desc |-| :-----| :---- |-| image | 图片 |-| table | 表格 |-| text | 文本 |-| inline_equation | 行内公式 |+| type | desc |+| :----------------- | :------- |+| image | 图片 |+| table | 表格 |+| text | 文本 |+| inline_equation | 行内公式 || interline_equation | 行间公式 |-**总结**span是所有元素的最小存储单元@@ -227,7 +222,6 @@ para_blocks内存储的元素为区块信息一级block(如有)->二级block->line->span-#### 示例数据```json@@ -329,4 +323,4 @@ para_blocks内存储的元素为区块信息"_parse_type": "txt","_version_name": "0.6.1"}-```\ No newline at end of file+```diff --git a/magic_pdf/dict2md/ocr_mkcontent.py b/magic_pdf/dict2md/ocr_mkcontent.pyindex ec5ded1c..418c2aad 100644--- a/magic_pdf/dict2md/ocr_mkcontent.py+++ b/magic_pdf/dict2md/ocr_mkcontent.py@@ -1,12 +1,27 @@+import re++import wordninjafrom loguru import logger-from magic_pdf.libs.MakeContentConfig import DropMode, MakeModefrom magic_pdf.libs.commons import join_pathfrom magic_pdf.libs.language import detect_lang+from magic_pdf.libs.MakeContentConfig import DropMode, MakeModefrom magic_pdf.libs.markdown_utils import ocr_escape_special_markdown_char-from magic_pdf.libs.ocr_content_type import ContentType, BlockType-import wordninja-import re+from magic_pdf.libs.ocr_content_type import BlockType, ContentType+++def __is_hyphen_at_line_end(line):+ """+ Check if a line ends with one or more letters followed by a hyphen.++ Args:+ line (str): The line of text to check.++ Returns:+ bool: True if the line ends with one or more letters followed by a hyphen, False otherwise.+ """+ # Use regex to check if the line ends with one or more letters followed by a hyphen+ return bool(re.search(r'[A-Za-z]+-\s*$', line))def split_long_words(text):@@ -14,7 +29,7 @@ def split_long_words(text):for i in range(len(segments)):words = re.findall(r'\w+|[^\w]', segments[i], re.UNICODE)for j in range(len(words)):- if len(words[j]) > 15:+ if len(words[j]) > 10:words[j] = ' '.join(wordninja.split(words[j]))segments[i] = ''.join(words)return ' '.join(segments)@@ -23,8 +38,9 @@ def split_long_words(text):def ocr_mk_mm_markdown_with_para(pdf_info_list: list, img_buket_path):markdown = []for page_info in pdf_info_list:- paras_of_layout = page_info.get("para_blocks")- page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "mm", img_buket_path)+ paras_of_layout = page_info.get('para_blocks')+ page_markdown = ocr_mk_markdown_with_para_core_v2(+ paras_of_layout, 'mm', img_buket_path)markdown.extend(page_markdown)return '\n\n'.join(markdown)@@ -32,29 +48,34 @@ def ocr_mk_mm_markdown_with_para(pdf_info_list: list, img_buket_path):def ocr_mk_nlp_markdown_with_para(pdf_info_dict: list):markdown = []for page_info in pdf_info_dict:- paras_of_layout = page_info.get("para_blocks")- page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "nlp")+ paras_of_layout = page_info.get('para_blocks')+ page_markdown = ocr_mk_markdown_with_para_core_v2(+ paras_of_layout, 'nlp')markdown.extend(page_markdown)return '\n\n'.join(markdown)-def ocr_mk_mm_markdown_with_para_and_pagination(pdf_info_dict: list, img_buket_path):+def ocr_mk_mm_markdown_with_para_and_pagination(pdf_info_dict: list,+ img_buket_path):markdown_with_para_and_pagination = []page_no = 0for page_info in pdf_info_dict:- paras_of_layout = page_info.get("para_blocks")+ paras_of_layout = page_info.get('para_blocks')if not paras_of_layout:continue- page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "mm", img_buket_path)+ page_markdown = ocr_mk_markdown_with_para_core_v2(+ paras_of_layout, 'mm', img_buket_path)markdown_with_para_and_pagination.append({- 'page_no': page_no,- 'md_content': '\n\n'.join(page_markdown)+ 'page_no':+ page_no,+ 'md_content':+ '\n\n'.join(page_markdown)})page_no += 1return markdown_with_para_and_pagination-def ocr_mk_markdown_with_para_core(paras_of_layout, mode, img_buket_path=""):+def ocr_mk_markdown_with_para_core(paras_of_layout, mode, img_buket_path=''):page_markdown = []for paras in paras_of_layout:for para in paras:@@ -67,8 +88,9 @@ def ocr_mk_markdown_with_para_core(paras_of_layout, mode, img_buket_path=""):if span_type == ContentType.Text:content = span['content']language = detect_lang(content)- if language == 'en': # 只对英文长词进行分词处理,中文分词会丢失文本- content = ocr_escape_special_markdown_char(split_long_words(content))+ if (language == 'en'): # 只对英文长词进行分词处理,中文分词会丢失文本+ content = ocr_escape_special_markdown_char(+ split_long_words(content))else:content = ocr_escape_special_markdown_char(content)elif span_type == ContentType.InlineEquation:@@ -92,7 +114,9 @@ def ocr_mk_markdown_with_para_core(paras_of_layout, mode, img_buket_path=""):return page_markdown-def ocr_mk_markdown_with_para_core_v2(paras_of_layout, mode, img_buket_path=""):+def ocr_mk_markdown_with_para_core_v2(paras_of_layout,+ mode,+ img_buket_path=''):page_markdown = []for para_block in paras_of_layout:para_text = ''@@ -100,7 +124,7 @@ def ocr_mk_markdown_with_para_core_v2(paras_of_layout, mode, img_buket_path=""):if para_type == BlockType.Text:para_text = merge_para_with_text(para_block)elif para_type == BlockType.Title:- para_text = f"# {merge_para_with_text(para_block)}"+ para_text = f'# {merge_para_with_text(para_block)}'elif para_type == BlockType.InterlineEquation:para_text = merge_para_with_text(para_block)elif para_type == BlockType.Image:@@ -116,14 +140,16 @@ def ocr_mk_markdown_with_para_core_v2(paras_of_layout, mode, img_buket_path=""):for block in para_block['blocks']: # 2nd.拼image_captionif block['type'] == BlockType.ImageCaption:para_text += merge_para_with_text(block)+ for block in para_block['blocks']: # 2nd.拼image_caption+ if block['type'] == BlockType.ImageFootnote:+ para_text += merge_para_with_text(block)elif para_type == BlockType.Table:if mode == 'nlp':continueelif mode == 'mm':- table_caption = ''for block in para_block['blocks']: # 1st.拼table_captionif block['type'] == BlockType.TableCaption:- table_caption = merge_para_with_text(block)+ para_text += merge_para_with_text(block)for block in para_block['blocks']: # 2nd.拼table_bodyif block['type'] == BlockType.TableBody:for line in block['lines']:@@ -135,7 +161,7 @@ def ocr_mk_markdown_with_para_core_v2(paras_of_layout, mode, img_buket_path=""):elif span.get('html', ''):para_text += f"\n\n{span['html']}\n\n"else:- para_text += f"\n}) \n"+ para_text += f"\n}) \n"for block in para_block['blocks']: # 3rd.拼table_footnoteif block['type'] == BlockType.TableFootnote:para_text += merge_para_with_text(block)@@ -149,24 +175,39 @@ def ocr_mk_markdown_with_para_core_v2(paras_of_layout, mode, img_buket_path=""):def merge_para_with_text(para_block):++ def detect_language(text):+ en_pattern = r'[a-zA-Z]+'+ en_matches = re.findall(en_pattern, text)+ en_length = sum(len(match) for match in en_matches)+ if len(text) > 0:+ if en_length / len(text) >= 0.5:+ return 'en'+ else:+ return 'unknown'+ else:+ return 'empty'+para_text = ''for line in para_block['lines']:- line_text = ""- line_lang = ""+ line_text = ''+ line_lang = ''for span in line['spans']:span_type = span['type']if span_type == ContentType.Text:line_text += span['content'].strip()- if line_text != "":+ if line_text != '':line_lang = detect_lang(line_text)for span in line['spans']:span_type = span['type']content = ''if span_type == ContentType.Text:content = span['content']- language = detect_lang(content)+ # language = detect_lang(content)+ language = detect_language(content)if language == 'en': # 只对英文长词进行分词处理,中文分词会丢失文本- content = ocr_escape_special_markdown_char(split_long_words(content))+ content = ocr_escape_special_markdown_char(+ split_long_words(content))else:content = ocr_escape_special_markdown_char(content)elif span_type == ContentType.InlineEquation:@@ -175,10 +216,17 @@ def merge_para_with_text(para_block):content = f"\n$$\n{span['content']}\n$$\n"if content != '':- if 'zh' in line_lang: # 遇到一些一个字一个span的文档,这种单字语言判断不准,需要用整行文本判断- para_text += content # 中文语境下,content间不需要空格分隔+ langs = ['zh', 'ja', 'ko']+ if line_lang in langs: # 遇到一些一个字一个span的文档,这种单字语言判断不准,需要用整行文本判断+ para_text += content # 中文/日语/韩文语境下,content间不需要空格分隔+ elif line_lang == 'en':+ # 如果是前一行带有-连字符,那么末尾不应该加空格+ if __is_hyphen_at_line_end(content):+ para_text += content[:-1]+ else:+ para_text += content + ' 'else:- para_text += content + ' ' # 英文语境下 content间需要空格分隔+ para_text += content + ' ' # 西方文本语境下 content间需要空格分隔return para_text@@ -193,18 +241,18 @@ def para_to_standard_format(para, img_buket_path):for span in line['spans']:language = ''span_type = span.get('type')- content = ""+ content = ''if span_type == ContentType.Text:content = span['content']language = detect_lang(content)if language == 'en': # 只对英文长词进行分词处理,中文分词会丢失文本- content = ocr_escape_special_markdown_char(split_long_words(content))+ content = ocr_escape_special_markdown_char(+ split_long_words(content))else:content = ocr_escape_special_markdown_char(content)elif span_type == ContentType.InlineEquation:content = f"${span['content']}$"inline_equation_num += 1-if language == 'en': # 英文语境下 content间需要空格分隔para_text += content + ' 'else: # 中文语境下,content间不需要空格分隔@@ -212,7 +260,7 @@ def para_to_standard_format(para, img_buket_path):para_content = {'type': 'text','text': para_text,- 'inline_equation_num': inline_equation_num+ 'inline_equation_num': inline_equation_num,}return para_content@@ -223,37 +271,35 @@ def para_to_standard_format_v2(para_block, img_buket_path, page_idx):para_content = {'type': 'text','text': merge_para_with_text(para_block),- 'page_idx': page_idx+ 'page_idx': page_idx,}elif para_type == BlockType.Title:para_content = {'type': 'text','text': merge_para_with_text(para_block),'text_level': 1,- 'page_idx': page_idx+ 'page_idx': page_idx,}elif para_type == BlockType.InterlineEquation:para_content = {'type': 'equation','text': merge_para_with_text(para_block),- 'text_format': "latex",- 'page_idx': page_idx+ 'text_format': 'latex',+ 'page_idx': page_idx,}elif para_type == BlockType.Image:- para_content = {- 'type': 'image',- 'page_idx': page_idx- }+ para_content = {'type': 'image', 'page_idx': page_idx}for block in para_block['blocks']:if block['type'] == BlockType.ImageBody:- para_content['img_path'] = join_path(img_buket_path, block["lines"][0]["spans"][0]['image_path'])+ para_content['img_path'] = join_path(+ img_buket_path,+ block['lines'][0]['spans'][0]['image_path'])if block['type'] == BlockType.ImageCaption:para_content['img_caption'] = merge_para_with_text(block)+ if block['type'] == BlockType.ImageFootnote:+ para_content['img_footnote'] = merge_para_with_text(block)elif para_type == BlockType.Table:- para_content = {- 'type': 'table',- 'page_idx': page_idx- }+ para_content = {'type': 'table', 'page_idx': page_idx}for block in para_block['blocks']:if block['type'] == BlockType.TableBody:if block["lines"][0]["spans"][0].get('latex', ''):@@ -272,17 +318,18 @@ def para_to_standard_format_v2(para_block, img_buket_path, page_idx):def make_standard_format_with_para(pdf_info_dict: list, img_buket_path: str):content_list = []for page_info in pdf_info_dict:- paras_of_layout = page_info.get("para_blocks")+ paras_of_layout = page_info.get('para_blocks')if not paras_of_layout:continuefor para_block in paras_of_layout:- para_content = para_to_standard_format_v2(para_block, img_buket_path)+ para_content = para_to_standard_format_v2(para_block,+ img_buket_path)content_list.append(para_content)return content_listdef line_to_standard_format(line, img_buket_path):- line_text = ""+ line_text = ''inline_equation_num = 0for span in line['spans']:if not span.get('content'):@@ -292,13 +339,15 @@ def line_to_standard_format(line, img_buket_path):if span['type'] == ContentType.Image:content = {'type': 'image',- 'img_path': join_path(img_buket_path, span['image_path'])+ 'img_path': join_path(img_buket_path,+ span['image_path']),}return contentelif span['type'] == ContentType.Table:content = {'type': 'table',- 'img_path': join_path(img_buket_path, span['image_path'])+ 'img_path': join_path(img_buket_path,+ span['image_path']),}return contentelse:@@ -306,36 +355,33 @@ def line_to_standard_format(line, img_buket_path):interline_equation = span['content']content = {'type': 'equation',- 'latex': f"$$\n{interline_equation}\n$$"+ 'latex': f'$$\n{interline_equation}\n$$'}return contentelif span['type'] == ContentType.InlineEquation:inline_equation = span['content']- line_text += f"${inline_equation}$"+ line_text += f'${inline_equation}$'inline_equation_num += 1elif span['type'] == ContentType.Text:- text_content = ocr_escape_special_markdown_char(span['content']) # 转义特殊符号+ text_content = ocr_escape_special_markdown_char(+ span['content']) # 转义特殊符号line_text += text_contentcontent = {'type': 'text','text': line_text,- 'inline_equation_num': inline_equation_num+ 'inline_equation_num': inline_equation_num,}return contentdef ocr_mk_mm_standard_format(pdf_info_dict: list):- """- content_list- type string image/text/table/equation(行间的单独拿出来,行内的和text合并)- latex string latex文本字段。- text string 纯文本格式的文本数据。- md string markdown格式的文本数据。- img_path string s3://full/path/to/img.jpg- """+ """content_list type string+ image/text/table/equation(行间的单独拿出来,行内的和text合并) latex string+ latex文本字段。 text string 纯文本格式的文本数据。 md string+ markdown格式的文本数据。 img_path string s3://full/path/to/img.jpg."""content_list = []for page_info in pdf_info_dict:- blocks = page_info.get("preproc_blocks")+ blocks = page_info.get('preproc_blocks')if not blocks:continuefor block in blocks:@@ -345,34 +391,42 @@ def ocr_mk_mm_standard_format(pdf_info_dict: list):return content_list-def union_make(pdf_info_dict: list, make_mode: str, drop_mode: str, img_buket_path: str = ""):+def union_make(pdf_info_dict: list,+ make_mode: str,+ drop_mode: str,+ img_buket_path: str = ''):output_content = []for page_info in pdf_info_dict:- if page_info.get("need_drop", False):- drop_reason = page_info.get("drop_reason")+ if page_info.get('need_drop', False):+ drop_reason = page_info.get('drop_reason')if drop_mode == DropMode.NONE:passelif drop_mode == DropMode.WHOLE_PDF:- raise Exception(f"drop_mode is {DropMode.WHOLE_PDF} , drop_reason is {drop_reason}")+ raise Exception((f'drop_mode is {DropMode.WHOLE_PDF} ,'+ f'drop_reason is {drop_reason}'))elif drop_mode == DropMode.SINGLE_PAGE:- logger.warning(f"drop_mode is {DropMode.SINGLE_PAGE} , drop_reason is {drop_reason}")+ logger.warning((f'drop_mode is {DropMode.SINGLE_PAGE} ,'+ f'drop_reason is {drop_reason}'))continueelse:- raise Exception(f"drop_mode can not be null")+ raise Exception('drop_mode can not be null')- paras_of_layout = page_info.get("para_blocks")- page_idx = page_info.get("page_idx")+ paras_of_layout = page_info.get('para_blocks')+ page_idx = page_info.get('page_idx')if not paras_of_layout:continueif make_mode == MakeMode.MM_MD:- page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "mm", img_buket_path)+ page_markdown = ocr_mk_markdown_with_para_core_v2(+ paras_of_layout, 'mm', img_buket_path)output_content.extend(page_markdown)elif make_mode == MakeMode.NLP_MD:- page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "nlp")+ page_markdown = ocr_mk_markdown_with_para_core_v2(+ paras_of_layout, 'nlp')output_content.extend(page_markdown)elif make_mode == MakeMode.STANDARD_FORMAT:for para_block in paras_of_layout:- para_content = para_to_standard_format_v2(para_block, img_buket_path, page_idx)+ para_content = para_to_standard_format_v2(+ para_block, img_buket_path, page_idx)output_content.append(para_content)if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:return '\n\n'.join(output_content)diff --git a/magic_pdf/integrations/__init__.py b/magic_pdf/integrations/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/magic_pdf/integrations/rag/__init__.py b/magic_pdf/integrations/rag/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/magic_pdf/integrations/rag/api.py b/magic_pdf/integrations/rag/api.pynew file mode 100644index 00000000..5c05f911--- /dev/null+++ b/magic_pdf/integrations/rag/api.py@@ -0,0 +1,82 @@+import os+from pathlib import Path++from loguru import logger++from magic_pdf.integrations.rag.type import (ElementRelation, LayoutElements,+ Node)+from magic_pdf.integrations.rag.utils import inference+++class RagPageReader:++ def __init__(self, pagedata: LayoutElements):+ self.o = [+ Node(+ category_type=v.category_type,+ text=v.text,+ image_path=v.image_path,+ anno_id=v.anno_id,+ latex=v.latex,+ html=v.html,+ ) for v in pagedata.layout_dets+ ]++ self.pagedata = pagedata++ def __iter__(self):+ return iter(self.o)++ def get_rel_map(self) -> list[ElementRelation]:+ return self.pagedata.extra.element_relation+++class RagDocumentReader:++ def __init__(self, ragdata: list[LayoutElements]):+ self.o = [RagPageReader(v) for v in ragdata]++ def __iter__(self):+ return iter(self.o)+++class DataReader:++ def __init__(self, path_or_directory: str, method: str, output_dir: str):+ self.path_or_directory = path_or_directory+ self.method = method+ self.output_dir = output_dir+ self.pdfs = []+ if os.path.isdir(path_or_directory):+ for doc_path in Path(path_or_directory).glob('*.pdf'):+ self.pdfs.append(doc_path)+ else:+ assert path_or_directory.endswith('.pdf')+ self.pdfs.append(Path(path_or_directory))++ def get_documents_count(self) -> int:+ """Returns the number of documents in the directory."""+ return len(self.pdfs)++ def get_document_result(self, idx: int) -> RagDocumentReader | None:+ """+ Args:+ idx (int): the index of documents under the+ directory path_or_directory++ Returns:+ RagDocumentReader | None: RagDocumentReader is an iterable object,+ more details @RagDocumentReader+ """+ if idx >= self.get_documents_count() or idx < 0:+ logger.error(f'invalid idx: {idx}')+ return None+ res = inference(str(self.pdfs[idx]), self.output_dir, self.method)+ if res is None:+ logger.warning(f'failed to inference pdf {self.pdfs[idx]}')+ return None+ return RagDocumentReader(res)++ def get_document_filename(self, idx: int) -> Path:+ """get the filename of the document."""+ return self.pdfs[idx]diff --git a/magic_pdf/integrations/rag/type.py b/magic_pdf/integrations/rag/type.pynew file mode 100644index 00000000..11258af3--- /dev/null+++ b/magic_pdf/integrations/rag/type.py@@ -0,0 +1,82 @@+from enum import Enum++from pydantic import BaseModel, Field+++# rag+class CategoryType(Enum): # py310 not support StrEnum+ text = 'text'+ title = 'title'+ interline_equation = 'interline_equation'+ image = 'image'+ image_body = 'image_body'+ image_caption = 'image_caption'+ table = 'table'+ table_body = 'table_body'+ table_caption = 'table_caption'+ table_footnote = 'table_footnote'+++class ElementRelType(Enum):+ sibling = 'sibling'+++class PageInfo(BaseModel):+ page_no: int = Field(description='the index of page, start from zero',+ ge=0)+ height: int = Field(description='the height of page', gt=0)+ width: int = Field(description='the width of page', ge=0)+ image_path: str | None = Field(description='the image of this page',+ default=None)+++class ContentObject(BaseModel):+ category_type: CategoryType = Field(description='类别')+ poly: list[float] = Field(+ description=('Coordinates, need to convert back to PDF coordinates,'+ ' order is top-left, top-right, bottom-right, bottom-left'+ ' x,y coordinates'))+ ignore: bool = Field(description='whether ignore this object',+ default=False)+ text: str | None = Field(description='text content of the object',+ default=None)+ image_path: str | None = Field(description='path of embedded image',+ default=None)+ order: int = Field(description='the order of this object within a page',+ default=-1)+ anno_id: int = Field(description='unique id', default=-1)+ latex: str | None = Field(description='latex result', default=None)+ html: str | None = Field(description='html result', default=None)+++class ElementRelation(BaseModel):+ source_anno_id: int = Field(description='unique id of the source object',+ default=-1)+ target_anno_id: int = Field(description='unique id of the target object',+ default=-1)+ relation: ElementRelType = Field(+ description='the relation between source and target element')+++class LayoutElementsExtra(BaseModel):+ element_relation: list[ElementRelation] = Field(+ description='the relation between source and target element')+++class LayoutElements(BaseModel):+ layout_dets: list[ContentObject] = Field(+ description='layout element details')+ page_info: PageInfo = Field(description='page info')+ extra: LayoutElementsExtra = Field(description='extra information')+++# iter data format+class Node(BaseModel):+ category_type: CategoryType = Field(description='类别')+ text: str | None = Field(description='text content of the object',+ default=None)+ image_path: str | None = Field(description='path of embedded image',+ default=None)+ anno_id: int = Field(description='unique id', default=-1)+ latex: str | None = Field(description='latex result', default=None)+ html: str | None = Field(description='html result', default=None)diff --git a/magic_pdf/integrations/rag/utils.py b/magic_pdf/integrations/rag/utils.pynew file mode 100644index 00000000..ed736ffb--- /dev/null+++ b/magic_pdf/integrations/rag/utils.py@@ -0,0 +1,285 @@+import json+import os+from pathlib import Path++from loguru import logger++import magic_pdf.model as model_config+from magic_pdf.dict2md.ocr_mkcontent import merge_para_with_text+from magic_pdf.integrations.rag.type import (CategoryType, ContentObject,+ ElementRelation, ElementRelType,+ LayoutElements,+ LayoutElementsExtra, PageInfo)+from magic_pdf.libs.ocr_content_type import BlockType, ContentType+from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter+from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter+from magic_pdf.tools.common import do_parse, prepare_env+++def convert_middle_json_to_layout_elements(+ json_data: dict,+ output_dir: str,+) -> list[LayoutElements]:+ uniq_anno_id = 0++ res: list[LayoutElements] = []+ for page_no, page_data in enumerate(json_data['pdf_info']):+ order_id = 0+ page_info = PageInfo(+ height=int(page_data['page_size'][1]),+ width=int(page_data['page_size'][0]),+ page_no=page_no,+ )+ layout_dets: list[ContentObject] = []+ extra_element_relation: list[ElementRelation] = []++ for para_block in page_data['para_blocks']:+ para_text = ''+ para_type = para_block['type']++ if para_type == BlockType.Text:+ para_text = merge_para_with_text(para_block)+ x0, y0, x1, y1 = para_block['bbox']+ content = ContentObject(+ anno_id=uniq_anno_id,+ category_type=CategoryType.text,+ text=para_text,+ order=order_id,+ poly=[x0, y0, x1, y0, x1, y1, x0, y1],+ )+ uniq_anno_id += 1+ order_id += 1+ layout_dets.append(content)++ elif para_type == BlockType.Title:+ para_text = merge_para_with_text(para_block)+ x0, y0, x1, y1 = para_block['bbox']+ content = ContentObject(+ anno_id=uniq_anno_id,+ category_type=CategoryType.title,+ text=para_text,+ order=order_id,+ poly=[x0, y0, x1, y0, x1, y1, x0, y1],+ )+ uniq_anno_id += 1+ order_id += 1+ layout_dets.append(content)++ elif para_type == BlockType.InterlineEquation:+ para_text = merge_para_with_text(para_block)+ x0, y0, x1, y1 = para_block['bbox']+ content = ContentObject(+ anno_id=uniq_anno_id,+ category_type=CategoryType.interline_equation,+ text=para_text,+ order=order_id,+ poly=[x0, y0, x1, y0, x1, y1, x0, y1],+ )+ uniq_anno_id += 1+ order_id += 1+ layout_dets.append(content)++ elif para_type == BlockType.Image:+ body_anno_id = -1+ caption_anno_id = -1++ for block in para_block['blocks']:+ if block['type'] == BlockType.ImageBody:+ for line in block['lines']:+ for span in line['spans']:+ if span['type'] == ContentType.Image:+ x0, y0, x1, y1 = block['bbox']+ content = ContentObject(+ anno_id=uniq_anno_id,+ category_type=CategoryType.image_body,+ image_path=os.path.join(+ output_dir, span['image_path']),+ order=order_id,+ poly=[x0, y0, x1, y0, x1, y1, x0, y1],+ )+ body_anno_id = uniq_anno_id+ uniq_anno_id += 1+ order_id += 1+ layout_dets.append(content)++ for block in para_block['blocks']:+ if block['type'] == BlockType.ImageCaption:+ para_text += merge_para_with_text(block)+ x0, y0, x1, y1 = block['bbox']+ content = ContentObject(+ anno_id=uniq_anno_id,+ category_type=CategoryType.image_caption,+ text=para_text,+ order=order_id,+ poly=[x0, y0, x1, y0, x1, y1, x0, y1],+ )+ caption_anno_id = uniq_anno_id+ uniq_anno_id += 1+ order_id += 1+ layout_dets.append(content)++ if body_anno_id > 0 and caption_anno_id > 0:+ element_relation = ElementRelation(+ relation=ElementRelType.sibling,+ source_anno_id=body_anno_id,+ target_anno_id=caption_anno_id,+ )+ extra_element_relation.append(element_relation)++ elif para_type == BlockType.Table:+ body_anno_id, caption_anno_id, footnote_anno_id = -1, -1, -1++ for block in para_block['blocks']:+ if block['type'] == BlockType.TableCaption:+ para_text += merge_para_with_text(block)+ x0, y0, x1, y1 = block['bbox']+ content = ContentObject(+ anno_id=uniq_anno_id,+ category_type=CategoryType.table_caption,+ text=para_text,+ order=order_id,+ poly=[x0, y0, x1, y0, x1, y1, x0, y1],+ )+ caption_anno_id = uniq_anno_id+ uniq_anno_id += 1+ order_id += 1+ layout_dets.append(content)++ for block in para_block['blocks']:+ if block['type'] == BlockType.TableBody:+ for line in block['lines']:+ for span in line['spans']:+ if span['type'] == ContentType.Table:+ x0, y0, x1, y1 = para_block['bbox']+ content = ContentObject(+ anno_id=uniq_anno_id,+ category_type=CategoryType.table_body,+ order=order_id,+ poly=[x0, y0, x1, y0, x1, y1, x0, y1],+ )+ body_anno_id = uniq_anno_id+ uniq_anno_id += 1+ order_id += 1+ # if processed by table model+ if span.get('latex', ''):+ content.latex = span['latex']+ else:+ content.image_path = os.path.join(+ output_dir, span['image_path'])+ layout_dets.append(content)++ for block in para_block['blocks']:+ if block['type'] == BlockType.TableFootnote:+ para_text += merge_para_with_text(block)+ x0, y0, x1, y1 = block['bbox']+ content = ContentObject(+ anno_id=uniq_anno_id,+ category_type=CategoryType.table_footnote,+ text=para_text,+ order=order_id,+ poly=[x0, y0, x1, y0, x1, y1, x0, y1],+ )+ footnote_anno_id = uniq_anno_id+ uniq_anno_id += 1+ order_id += 1+ layout_dets.append(content)++ if caption_anno_id != -1 and body_anno_id != -1:+ element_relation = ElementRelation(+ relation=ElementRelType.sibling,+ source_anno_id=body_anno_id,+ target_anno_id=caption_anno_id,+ )+ extra_element_relation.append(element_relation)++ if footnote_anno_id != -1 and body_anno_id != -1:+ element_relation = ElementRelation(+ relation=ElementRelType.sibling,+ source_anno_id=body_anno_id,+ target_anno_id=footnote_anno_id,+ )+ extra_element_relation.append(element_relation)++ res.append(+ LayoutElements(+ page_info=page_info,+ layout_dets=layout_dets,+ extra=LayoutElementsExtra(+ element_relation=extra_element_relation),+ ))++ return res+++def inference(path, output_dir, method):+ model_config.__use_inside_model__ = True+ model_config.__model_mode__ = 'full'+ if output_dir == '':+ if os.path.isdir(path):+ output_dir = os.path.join(path, 'output')+ else:+ output_dir = os.path.join(os.path.dirname(path), 'output')++ local_image_dir, local_md_dir = prepare_env(output_dir,+ str(Path(path).stem), method)++ def read_fn(path):+ disk_rw = DiskReaderWriter(os.path.dirname(path))+ return disk_rw.read(os.path.basename(path), AbsReaderWriter.MODE_BIN)++ def parse_doc(doc_path: str):+ try:+ file_name = str(Path(doc_path).stem)+ pdf_data = read_fn(doc_path)+ do_parse(+ output_dir,+ file_name,+ pdf_data,+ [],+ method,+ False,+ f_draw_span_bbox=False,+ f_draw_layout_bbox=False,+ f_dump_md=False,+ f_dump_middle_json=True,+ f_dump_model_json=False,+ f_dump_orig_pdf=False,+ f_dump_content_list=False,+ f_draw_model_bbox=False,+ )++ middle_json_fn = os.path.join(local_md_dir,+ f'{file_name}_middle.json')+ with open(middle_json_fn) as fd:+ jso = json.load(fd)+ os.remove(middle_json_fn)+ return convert_middle_json_to_layout_elements(jso, local_image_dir)++ except Exception as e:+ logger.exception(e)++ return parse_doc(path)+++if __name__ == '__main__':+ import pprint++ base_dir = '/opt/data/pdf/resources/samples/'+ if 0:+ with open(base_dir + 'json_outputs/middle.json') as f:+ d = json.load(f)+ result = convert_middle_json_to_layout_elements(d, '/tmp')+ pprint.pp(result)+ if 0:+ with open(base_dir + 'json_outputs/middle.3.json') as f:+ d = json.load(f)+ result = convert_middle_json_to_layout_elements(d, '/tmp')+ pprint.pp(result)++ if 1:+ res = inference(+ base_dir + 'samples/pdf/one_page_with_table_image.pdf',+ '/tmp/output',+ 'ocr',+ )+ pprint.pp(res)diff --git a/magic_pdf/layout/layout_sort.py b/magic_pdf/layout/layout_sort.pyindex 6b387d4c..383ea5bf 100644--- a/magic_pdf/layout/layout_sort.py+++ b/magic_pdf/layout/layout_sort.py@@ -1,60 +1,66 @@-"""-对pdf上的box进行layout识别,并对内部组成的box进行排序-"""+"""对pdf上的box进行layout识别,并对内部组成的box进行排序."""from loguru import logger-from magic_pdf.layout.bbox_sort import CONTENT_IDX, CONTENT_TYPE_IDX, X0_EXT_IDX, X0_IDX, X1_EXT_IDX, X1_IDX, Y0_EXT_IDX, Y0_IDX, Y1_EXT_IDX, Y1_IDX, paper_bbox_sort-from magic_pdf.layout.layout_det_utils import find_all_left_bbox_direct, find_all_right_bbox_direct, find_bottom_bbox_direct_from_left_edge, find_bottom_bbox_direct_from_right_edge, find_top_bbox_direct_from_left_edge, find_top_bbox_direct_from_right_edge, find_all_top_bbox_direct, find_all_bottom_bbox_direct, get_left_edge_bboxes, get_right_edge_bboxes-from magic_pdf.libs.boxbase import get_bbox_in_boundry+from magic_pdf.layout.bbox_sort import (CONTENT_IDX, CONTENT_TYPE_IDX,+ X0_EXT_IDX, X0_IDX, X1_EXT_IDX, X1_IDX,+ Y0_EXT_IDX, Y0_IDX, Y1_EXT_IDX, Y1_IDX,+ paper_bbox_sort)+from magic_pdf.layout.layout_det_utils import (+ find_all_bottom_bbox_direct, find_all_left_bbox_direct,+ find_all_right_bbox_direct, find_all_top_bbox_direct,+ find_bottom_bbox_direct_from_left_edge,+ find_bottom_bbox_direct_from_right_edge,+ find_top_bbox_direct_from_left_edge, find_top_bbox_direct_from_right_edge,+ get_left_edge_bboxes, get_right_edge_bboxes)+from magic_pdf.libs.boxbase import get_bbox_in_boundary++LAYOUT_V = 'V'+LAYOUT_H = 'H'+LAYOUT_UNPROC = 'U'+LAYOUT_BAD = 'B'-LAYOUT_V = "V"-LAYOUT_H = "H"-LAYOUT_UNPROC = "U"-LAYOUT_BAD = "B"def _is_single_line_text(bbox):- """- 检查bbox里面的文字是否只有一行- """- return True # TODO+ """检查bbox里面的文字是否只有一行."""+ return True # TODObox_type = bbox[CONTENT_TYPE_IDX]if box_type != 'text':return False- paras = bbox[CONTENT_IDX]["paras"]- text_content = ""+ paras = bbox[CONTENT_IDX]['paras']+ text_content = ''for para_id, para in paras.items(): # 拼装内部的段落文本is_title = para['is_title']- if is_title!=0:+ if is_title != 0:text_content += f"## {para['text']}"else:- text_content += para["text"]- text_content += "\n\n"-- return bbox[CONTENT_TYPE_IDX] == 'text' and len(text_content.split("\n\n")) <= 1+ text_content += para['text']+ text_content += '\n\n'+ return bbox[CONTENT_TYPE_IDX] == 'text' and len(text_content.split('\n\n')) <= 1-def _horizontal_split(bboxes:list, boundry:tuple, avg_font_size=20)-> list:++def _horizontal_split(bboxes: list, boundary: tuple, avg_font_size=20) -> list:"""对bboxes进行水平切割方法是:找到左侧和右侧都没有被直接遮挡的box,然后进行扩展,之后进行切割return:返回几个大的Layout区域 [[x0, y0, x1, y1, "h|u|v"], ], h代表水平,u代表未探测的,v代表垂直布局"""- sorted_layout_blocks = [] # 这是要最终返回的值-- bound_x0, bound_y0, bound_x1, bound_y1 = boundry- all_bboxes = get_bbox_in_boundry(bboxes, boundry)- #all_bboxes = paper_bbox_sort(all_bboxes, abs(bound_x1-bound_x0), abs(bound_y1-bound_x0)) # 大致拍下序, 这个是基于直接遮挡的。+ sorted_layout_blocks = [] # 这是要最终返回的值++ bound_x0, bound_y0, bound_x1, bound_y1 = boundary+ all_bboxes = get_bbox_in_boundary(bboxes, boundary)+ # all_bboxes = paper_bbox_sort(all_bboxes, abs(bound_x1-bound_x0), abs(bound_y1-bound_x0)) # 大致拍下序, 这个是基于直接遮挡的。"""首先在水平方向上扩展独占一行的bbox-+"""- last_h_split_line_y1 = bound_y0 #记录下上次的水平分割线+ last_h_split_line_y1 = bound_y0 # 记录下上次的水平分割线for i, bbox in enumerate(all_bboxes):- left_nearest_bbox = find_all_left_bbox_direct(bbox, all_bboxes) # 非扩展线+ left_nearest_bbox = find_all_left_bbox_direct(bbox, all_bboxes) # 非扩展线right_nearest_bbox = find_all_right_bbox_direct(bbox, all_bboxes)- if left_nearest_bbox is None and right_nearest_bbox is None: # 独占一行+ if left_nearest_bbox is None and right_nearest_bbox is None: # 独占一行"""然而,如果只是孤立的一行文字,那么就还要满足以下几个条件才可以:1. bbox和中心线相交。或者@@ -62,16 +68,20 @@ def _horizontal_split(bboxes:list, boundry:tuple, avg_font_size=20)-> list:3. TODO 加强条件:这个bbox上方和下方是同一列column,那么就不能算作独占一行"""# 先检查这个bbox里是否只包含一行文字- is_single_line = _is_single_line_text(bbox)+ # is_single_line = _is_single_line_text(bbox)"""- 这里有个点需要注意,当页面内容不是居中的时候,第一次调用传递的是page的boundry,这个时候mid_x就不是中心线了.- 所以这里计算出最紧致的boundry,然后再计算mid_x+ 这里有个点需要注意,当页面内容不是居中的时候,第一次调用传递的是page的boundary,这个时候mid_x就不是中心线了.+ 所以这里计算出最紧致的boundary,然后再计算mid_x"""- boundry_real_x0, boundry_real_x1 = min([bbox[X0_IDX] for bbox in all_bboxes]), max([bbox[X1_IDX] for bbox in all_bboxes])- mid_x = (boundry_real_x0+boundry_real_x1)/2+ boundary_real_x0, boundary_real_x1 = min(+ [bbox[X0_IDX] for bbox in all_bboxes]+ ), max([bbox[X1_IDX] for bbox in all_bboxes])+ mid_x = (boundary_real_x0 + boundary_real_x1) / 2# 检查这个box是否内容在中心线有交# 必须跨过去2个字符的宽度- is_cross_boundry_mid_line = min(mid_x-bbox[X0_IDX], bbox[X1_IDX]-mid_x) > avg_font_size*2+ is_cross_boundary_mid_line = (+ min(mid_x - bbox[X0_IDX], bbox[X1_IDX] - mid_x) > avg_font_size * 2+ )"""检查条件2"""@@ -84,50 +94,78 @@ def _horizontal_split(bboxes:list, boundry:tuple, avg_font_size=20)-> list:"""以迭代的方式向上找,查找范围是[bound_x0, last_h_sp, bound_x1, bbox[Y0_IDX]]"""- #先确定上方的y0, y0+ # 先确定上方的y0, y0b_y0, b_y1 = last_h_split_line_y1, bbox[Y0_IDX]- #然后从box开始逐个向上找到所有与box在x上有交集的box+ # 然后从box开始逐个向上找到所有与box在x上有交集的boxbox_to_check = [bound_x0, b_y0, bound_x1, b_y1]- bbox_in_bound_check = get_bbox_in_boundry(all_bboxes, box_to_check)-+ bbox_in_bound_check = get_bbox_in_boundary(all_bboxes, box_to_check)+bboxes_on_top = []virtual_box = bboxwhile True:b_on_top = find_all_top_bbox_direct(virtual_box, bbox_in_bound_check)if b_on_top is not None:bboxes_on_top.append(b_on_top)- virtual_box = [min([virtual_box[X0_IDX], b_on_top[X0_IDX]]), min(virtual_box[Y0_IDX], b_on_top[Y0_IDX]), max([virtual_box[X1_IDX], b_on_top[X1_IDX]]), b_y1]+ virtual_box = [+ min([virtual_box[X0_IDX], b_on_top[X0_IDX]]),+ min(virtual_box[Y0_IDX], b_on_top[Y0_IDX]),+ max([virtual_box[X1_IDX], b_on_top[X1_IDX]]),+ b_y1,+ ]else:break# 随后确定这些box的最小x0, 最大x1- if len(bboxes_on_top)>0 and len(bboxes_on_top) != len(bbox_in_bound_check):# virtual_box可能会膨胀到占满整个区域,这实际上就不能属于一个col了。+ if len(bboxes_on_top) > 0 and len(bboxes_on_top) != len(+ bbox_in_bound_check+ ): # virtual_box可能会膨胀到占满整个区域,这实际上就不能属于一个col了。min_x0, max_x1 = virtual_box[X0_IDX], virtual_box[X1_IDX]# 然后采用一种比较粗糙的方法,看min_x0,max_x1是否与位于[bound_x0, last_h_sp, bound_x1, bbox[Y0_IDX]]之间的box有相交-- if not any([b[X0_IDX] <= min_x0-1 <= b[X1_IDX] or b[X0_IDX] <= max_x1+1 <= b[X1_IDX] for b in bbox_in_bound_check]):++ if not any(+ [+ b[X0_IDX] <= min_x0 - 1 <= b[X1_IDX]+ or b[X0_IDX] <= max_x1 + 1 <= b[X1_IDX]+ for b in bbox_in_bound_check+ ]+ ):# 其上,下都不能被扩展成行,暂时只检查一下上方 TODOtop_nearest_bbox = find_all_top_bbox_direct(bbox, bboxes)bottom_nearest_bbox = find_all_bottom_bbox_direct(bbox, bboxes)- if not any([- top_nearest_bbox is not None and (find_all_left_bbox_direct(top_nearest_bbox, bboxes) is None and find_all_right_bbox_direct(top_nearest_bbox, bboxes) is None),- bottom_nearest_bbox is not None and (find_all_left_bbox_direct(bottom_nearest_bbox, bboxes) is None and find_all_right_bbox_direct(bottom_nearest_bbox, bboxes) is None),- top_nearest_bbox is None or bottom_nearest_bbox is None- ]):- is_belong_to_col = True-+ if not any(+ [+ top_nearest_bbox is not None+ and (+ find_all_left_bbox_direct(top_nearest_bbox, bboxes)+ is None+ and find_all_right_bbox_direct(top_nearest_bbox, bboxes)+ is None+ ),+ bottom_nearest_bbox is not None+ and (+ find_all_left_bbox_direct(bottom_nearest_bbox, bboxes)+ is None+ and find_all_right_bbox_direct(+ bottom_nearest_bbox, bboxes+ )+ is None+ ),+ top_nearest_bbox is None or bottom_nearest_bbox is None,+ ]+ ):+ is_belong_to_col = True+# 检查是否能被下方col吸收 TODO-"""- 这里为什么没有is_cross_boundry_mid_line的条件呢?+ 这里为什么没有is_cross_boundary_mid_line的条件呢?确实有些杂志左右两栏宽度不是对称的。"""- if not is_belong_to_col or is_cross_boundry_mid_line:+ if not is_belong_to_col or is_cross_boundary_mid_line:bbox[X0_EXT_IDX] = bound_x0bbox[Y0_EXT_IDX] = bbox[Y0_IDX]bbox[X1_EXT_IDX] = bound_x1bbox[Y1_EXT_IDX] = bbox[Y1_IDX]- last_h_split_line_y1 = bbox[Y1_IDX] # 更新这条线+ last_h_split_line_y1 = bbox[Y1_IDX] # 更新这条线else:continue"""@@ -142,13 +180,12 @@ def _horizontal_split(bboxes:list, boundry:tuple, avg_font_size=20)-> list:if bbox[X0_EXT_IDX] == bound_x0 and bbox[X1_EXT_IDX] == bound_x1:h_bbox_group.append(bbox)else:- if len(h_bbox_group)>0:- h_bboxes.append(h_bbox_group)+ if len(h_bbox_group) > 0:+ h_bboxes.append(h_bbox_group)h_bbox_group = []# 最后一个group- if len(h_bbox_group)>0:+ if len(h_bbox_group) > 0:h_bboxes.append(h_bbox_group)-"""现在h_bboxes里面是所有的group了,每个group都是一个list对h_bboxes里的每个group进行计算放回到sorted_layouts里@@ -157,52 +194,67 @@ def _horizontal_split(bboxes:list, boundry:tuple, avg_font_size=20)-> list:for gp in h_bboxes:gp.sort(key=lambda x: x[Y0_IDX])# 然后计算这个group的layout_bbox,也就是最小的x0,y0, 最大的x1,y1- x0, y0, x1, y1 = gp[0][X0_EXT_IDX], gp[0][Y0_EXT_IDX], gp[-1][X1_EXT_IDX], gp[-1][Y1_EXT_IDX]- h_layouts.append([x0, y0, x1, y1, LAYOUT_H]) # 水平的布局-+ x0, y0, x1, y1 = (+ gp[0][X0_EXT_IDX],+ gp[0][Y0_EXT_IDX],+ gp[-1][X1_EXT_IDX],+ gp[-1][Y1_EXT_IDX],+ )+ h_layouts.append([x0, y0, x1, y1, LAYOUT_H]) # 水平的布局"""接下来利用这些连续的水平bbox的layout_bbox的y0, y1,从水平上切分开其余的为几个部分"""h_split_lines = [bound_y0]- for gp in h_bboxes: # gp是一个list[bbox_list]+ for gp in h_bboxes: # gp是一个list[bbox_list]y0, y1 = gp[0][1], gp[-1][3]h_split_lines.append(y0)h_split_lines.append(y1)h_split_lines.append(bound_y1)-+unsplited_bboxes = []for i in range(0, len(h_split_lines), 2):- start_y0, start_y1 = h_split_lines[i:i+2]+ start_y0, start_y1 = h_split_lines[i : i + 2]# 然后找出[start_y0, start_y1]之间的其他bbox,这些组成一个未分割板块- bboxes_in_block = [bbox for bbox in all_bboxes if bbox[Y0_IDX]>=start_y0 and bbox[Y1_IDX]<=start_y1]+ bboxes_in_block = [+ bbox+ for bbox in all_bboxes+ if bbox[Y0_IDX] >= start_y0 and bbox[Y1_IDX] <= start_y1+ ]unsplited_bboxes.append(bboxes_in_block)# 接着把未处理的加入到h_layouts里for bboxes_in_block in unsplited_bboxes:if len(bboxes_in_block) == 0:continue- x0, y0, x1, y1 = bound_x0, min([bbox[Y0_IDX] for bbox in bboxes_in_block]), bound_x1, max([bbox[Y1_IDX] for bbox in bboxes_in_block])+ x0, y0, x1, y1 = (+ bound_x0,+ min([bbox[Y0_IDX] for bbox in bboxes_in_block]),+ bound_x1,+ max([bbox[Y1_IDX] for bbox in bboxes_in_block]),+ )h_layouts.append([x0, y0, x1, y1, LAYOUT_UNPROC])-- h_layouts.sort(key=lambda x: x[1]) # 按照y0排序, 也就是从上到下的顺序-++ h_layouts.sort(key=lambda x: x[1]) # 按照y0排序, 也就是从上到下的顺序"""转换成如下格式返回"""for layout in h_layouts:- sorted_layout_blocks.append({- "layout_bbox": layout[:4],- "layout_label":layout[4],- "sub_layout":[],- })+ sorted_layout_blocks.append(+ {+ 'layout_bbox': layout[:4],+ 'layout_label': layout[4],+ 'sub_layout': [],+ }+ )return sorted_layout_blocks-++################################################################################################# 垂直方向的处理##-###############################################################################################-def _vertical_align_split_v1(bboxes:list, boundry:tuple)-> list:+###############################################################################################+def _vertical_align_split_v1(bboxes: list, boundary: tuple) -> list:"""计算垂直方向上的对齐, 并分割bboxes成layout。负责对一列多行的进行列维度分割。如果不能完全分割,剩余部分作为layout_lable为u的layout返回@@ -214,85 +266,124 @@ def _vertical_align_split_v1(bboxes:list, boundry:tuple)-> list:-------------------------此函数会将:以上布局将会切分出来2列"""- sorted_layout_blocks = [] # 这是要最终返回的值- new_boundry = [boundry[0], boundry[1], boundry[2], boundry[3]]-+ sorted_layout_blocks = [] # 这是要最终返回的值+ new_boundary = [boundary[0], boundary[1], boundary[2], boundary[3]]+v_blocks = []"""先从左到右切分"""- while True:- all_bboxes = get_bbox_in_boundry(bboxes, new_boundry)+ while True:+ all_bboxes = get_bbox_in_boundary(bboxes, new_boundary)left_edge_bboxes = get_left_edge_bboxes(all_bboxes)if len(left_edge_bboxes) == 0:break- right_split_line_x1 = max([bbox[X1_IDX] for bbox in left_edge_bboxes])+1+ right_split_line_x1 = max([bbox[X1_IDX] for bbox in left_edge_bboxes]) + 1# 然后检查这条线能不与其他bbox的左边界相交或者重合- if any([bbox[X0_IDX] <= right_split_line_x1 <= bbox[X1_IDX] for bbox in all_bboxes]):+ if any(+ [bbox[X0_IDX] <= right_split_line_x1 <= bbox[X1_IDX] for bbox in all_bboxes]+ ):# 垂直切分线与某些box发生相交,说明无法完全垂直方向切分。break- else: # 说明成功分割出一列+ else: # 说明成功分割出一列# 找到左侧边界最靠左的bbox作为layout的x0- layout_x0 = min([bbox[X0_IDX] for bbox in left_edge_bboxes]) # 这里主要是为了画出来有一定间距- v_blocks.append([layout_x0, new_boundry[1], right_split_line_x1, new_boundry[3], LAYOUT_V])- new_boundry[0] = right_split_line_x1 # 更新边界-+ layout_x0 = min(+ [bbox[X0_IDX] for bbox in left_edge_bboxes]+ ) # 这里主要是为了画出来有一定间距+ v_blocks.append(+ [+ layout_x0,+ new_boundary[1],+ right_split_line_x1,+ new_boundary[3],+ LAYOUT_V,+ ]+ )+ new_boundary[0] = right_split_line_x1 # 更新边界"""再从右到左切, 此时如果还是无法完全切分,那么剩余部分作为layout_lable为u的layout返回"""unsplited_block = []while True:- all_bboxes = get_bbox_in_boundry(bboxes, new_boundry)+ all_bboxes = get_bbox_in_boundary(bboxes, new_boundary)right_edge_bboxes = get_right_edge_bboxes(all_bboxes)if len(right_edge_bboxes) == 0:break- left_split_line_x0 = min([bbox[X0_IDX] for bbox in right_edge_bboxes])-1+ left_split_line_x0 = min([bbox[X0_IDX] for bbox in right_edge_bboxes]) - 1# 然后检查这条线能不与其他bbox的左边界相交或者重合- if any([bbox[X0_IDX] <= left_split_line_x0 <= bbox[X1_IDX] for bbox in all_bboxes]):+ if any(+ [bbox[X0_IDX] <= left_split_line_x0 <= bbox[X1_IDX] for bbox in all_bboxes]+ ):# 这里是余下的- unsplited_block.append([new_boundry[0], new_boundry[1], new_boundry[2], new_boundry[3], LAYOUT_UNPROC])+ unsplited_block.append(+ [+ new_boundary[0],+ new_boundary[1],+ new_boundary[2],+ new_boundary[3],+ LAYOUT_UNPROC,+ ]+ )breakelse:# 找到右侧边界最靠右的bbox作为layout的x1layout_x1 = max([bbox[X1_IDX] for bbox in right_edge_bboxes])- v_blocks.append([left_split_line_x0, new_boundry[1], layout_x1, new_boundry[3], LAYOUT_V])- new_boundry[2] = left_split_line_x0 # 更新右边界-+ v_blocks.append(+ [+ left_split_line_x0,+ new_boundary[1],+ layout_x1,+ new_boundary[3],+ LAYOUT_V,+ ]+ )+ new_boundary[2] = left_split_line_x0 # 更新右边界"""最后拼装成layout格式返回"""for block in v_blocks:- sorted_layout_blocks.append({- "layout_bbox": block[:4],- "layout_label":block[4],- "sub_layout":[],- })+ sorted_layout_blocks.append(+ {+ 'layout_bbox': block[:4],+ 'layout_label': block[4],+ 'sub_layout': [],+ }+ )for block in unsplited_block:- sorted_layout_blocks.append({- "layout_bbox": block[:4],- "layout_label":block[4],- "sub_layout":[],- })-+ sorted_layout_blocks.append(+ {+ 'layout_bbox': block[:4],+ 'layout_label': block[4],+ 'sub_layout': [],+ }+ )+# 按照x0排序sorted_layout_blocks.sort(key=lambda x: x['layout_bbox'][0])return sorted_layout_blocks--def _vertical_align_split_v2(bboxes:list, boundry:tuple)-> list:- """- 改进的 _vertical_align_split算法,原算法会因为第二列的box由于左侧没有遮挡被认为是左侧的一部分,导致整个layout多列被识别为一列。- 利用从左上角的box开始向下看的方法,不断扩展w_x0, w_x1,直到不能继续向下扩展,或者到达边界下边界。- """- sorted_layout_blocks = [] # 这是要最终返回的值- new_boundry = [boundry[0], boundry[1], boundry[2], boundry[3]]- bad_boxes = [] # 被割中的box+++def _vertical_align_split_v2(bboxes: list, boundary: tuple) -> list:+ """改进的+ _vertical_align_split算法,原算法会因为第二列的box由于左侧没有遮挡被认为是左侧的一部分,导致整个layout多列被识别为一列。+ 利用从左上角的box开始向下看的方法,不断扩展w_x0, w_x1,直到不能继续向下扩展,或者到达边界下边界。"""+ sorted_layout_blocks = [] # 这是要最终返回的值+ new_boundary = [boundary[0], boundary[1], boundary[2], boundary[3]]+ bad_boxes = [] # 被割中的boxv_blocks = []while True:- all_bboxes = get_bbox_in_boundry(bboxes, new_boundry)+ all_bboxes = get_bbox_in_boundary(bboxes, new_boundary)if len(all_bboxes) == 0:break- left_top_box = min(all_bboxes, key=lambda x: (x[X0_IDX],x[Y0_IDX]))# 这里应该加强,检查一下必须是在第一列的 TODO- start_box = [left_top_box[X0_IDX], left_top_box[Y0_IDX], left_top_box[X1_IDX], left_top_box[Y1_IDX]]+ left_top_box = min(+ all_bboxes, key=lambda x: (x[X0_IDX], x[Y0_IDX])+ ) # 这里应该加强,检查一下必须是在第一列的 TODO+ start_box = [+ left_top_box[X0_IDX],+ left_top_box[Y0_IDX],+ left_top_box[X1_IDX],+ left_top_box[Y1_IDX],+ ]w_x0, w_x1 = left_top_box[X0_IDX], left_top_box[X1_IDX]"""然后沿着这个box线向下找最近的那个box, 然后扩展w_x0, w_x1@@ -301,98 +392,140 @@ def _vertical_align_split_v2(bboxes:list, boundry:tuple)-> list:1. 达到,那么更新左边界继续分下一个列2. 没有达到,那么此时开始从右侧切分进入下面的循环里"""- while left_top_box is not None: # 向下去找+ while left_top_box is not None: # 向下去找virtual_box = [w_x0, left_top_box[Y0_IDX], w_x1, left_top_box[Y1_IDX]]- left_top_box = find_bottom_bbox_direct_from_left_edge(virtual_box, all_bboxes)+ left_top_box = find_bottom_bbox_direct_from_left_edge(+ virtual_box, all_bboxes+ )if left_top_box:- w_x0, w_x1 = min(virtual_box[X0_IDX], left_top_box[X0_IDX]), max([virtual_box[X1_IDX], left_top_box[X1_IDX]])+ w_x0, w_x1 = min(virtual_box[X0_IDX], left_top_box[X0_IDX]), max(+ [virtual_box[X1_IDX], left_top_box[X1_IDX]]+ )# 万一这个初始的box在column中间,那么还要向上看- start_box = [w_x0, start_box[Y0_IDX], w_x1, start_box[Y1_IDX]] # 扩展一下宽度更鲁棒+ start_box = [+ w_x0,+ start_box[Y0_IDX],+ w_x1,+ start_box[Y1_IDX],+ ] # 扩展一下宽度更鲁棒left_top_box = find_top_bbox_direct_from_left_edge(start_box, all_bboxes)- while left_top_box is not None: # 向上去找+ while left_top_box is not None: # 向上去找virtual_box = [w_x0, left_top_box[Y0_IDX], w_x1, left_top_box[Y1_IDX]]left_top_box = find_top_bbox_direct_from_left_edge(virtual_box, all_bboxes)if left_top_box:- w_x0, w_x1 = min(virtual_box[X0_IDX], left_top_box[X0_IDX]), max([virtual_box[X1_IDX], left_top_box[X1_IDX]])-- # 检查相交- if any([bbox[X0_IDX] <= w_x1+1 <= bbox[X1_IDX] for bbox in all_bboxes]):+ w_x0, w_x1 = min(virtual_box[X0_IDX], left_top_box[X0_IDX]), max(+ [virtual_box[X1_IDX], left_top_box[X1_IDX]]+ )++ # 检查相交+ if any([bbox[X0_IDX] <= w_x1 + 1 <= bbox[X1_IDX] for bbox in all_bboxes]):for b in all_bboxes:- if b[X0_IDX] <= w_x1+1 <= b[X1_IDX]:+ if b[X0_IDX] <= w_x1 + 1 <= b[X1_IDX]:bad_boxes.append([b[X0_IDX], b[Y0_IDX], b[X1_IDX], b[Y1_IDX]])break- else: # 说明成功分割出一列- v_blocks.append([w_x0, new_boundry[1], w_x1, new_boundry[3], LAYOUT_V])- new_boundry[0] = w_x1 # 更新边界-+ else: # 说明成功分割出一列+ v_blocks.append([w_x0, new_boundary[1], w_x1, new_boundary[3], LAYOUT_V])+ new_boundary[0] = w_x1 # 更新边界"""接着开始从右上角的box扫描"""- w_x0 , w_x1 = 0, 0+ w_x0, w_x1 = 0, 0unsplited_block = []while True:- all_bboxes = get_bbox_in_boundry(bboxes, new_boundry)+ all_bboxes = get_bbox_in_boundary(bboxes, new_boundary)if len(all_bboxes) == 0:break# 先找到X1最大的- bbox_list_sorted = sorted(all_bboxes, key=lambda bbox: bbox[X1_IDX], reverse=True)+ bbox_list_sorted = sorted(+ all_bboxes, key=lambda bbox: bbox[X1_IDX], reverse=True+ )# Then, find the boxes with the smallest Y0 valuebigest_x1 = bbox_list_sorted[0][X1_IDX]- boxes_with_bigest_x1 = [bbox for bbox in bbox_list_sorted if bbox[X1_IDX] == bigest_x1] # 也就是最靠右的那些- right_top_box = min(boxes_with_bigest_x1, key=lambda bbox: bbox[Y0_IDX]) # y0最小的那个- start_box = [right_top_box[X0_IDX], right_top_box[Y0_IDX], right_top_box[X1_IDX], right_top_box[Y1_IDX]]+ boxes_with_bigest_x1 = [+ bbox for bbox in bbox_list_sorted if bbox[X1_IDX] == bigest_x1+ ] # 也就是最靠右的那些+ right_top_box = min(+ boxes_with_bigest_x1, key=lambda bbox: bbox[Y0_IDX]+ ) # y0最小的那个+ start_box = [+ right_top_box[X0_IDX],+ right_top_box[Y0_IDX],+ right_top_box[X1_IDX],+ right_top_box[Y1_IDX],+ ]w_x0, w_x1 = right_top_box[X0_IDX], right_top_box[X1_IDX]-+while right_top_box is not None:virtual_box = [w_x0, right_top_box[Y0_IDX], w_x1, right_top_box[Y1_IDX]]- right_top_box = find_bottom_bbox_direct_from_right_edge(virtual_box, all_bboxes)+ right_top_box = find_bottom_bbox_direct_from_right_edge(+ virtual_box, all_bboxes+ )if right_top_box:- w_x0, w_x1 = min([w_x0, right_top_box[X0_IDX]]), max([w_x1, right_top_box[X1_IDX]])+ w_x0, w_x1 = min([w_x0, right_top_box[X0_IDX]]), max(+ [w_x1, right_top_box[X1_IDX]]+ )# 在向上扫描- start_box = [w_x0, start_box[Y0_IDX], w_x1, start_box[Y1_IDX]] # 扩展一下宽度更鲁棒+ start_box = [+ w_x0,+ start_box[Y0_IDX],+ w_x1,+ start_box[Y1_IDX],+ ] # 扩展一下宽度更鲁棒right_top_box = find_top_bbox_direct_from_right_edge(start_box, all_bboxes)while right_top_box is not None:virtual_box = [w_x0, right_top_box[Y0_IDX], w_x1, right_top_box[Y1_IDX]]- right_top_box = find_top_bbox_direct_from_right_edge(virtual_box, all_bboxes)+ right_top_box = find_top_bbox_direct_from_right_edge(+ virtual_box, all_bboxes+ )if right_top_box:- w_x0, w_x1 = min([w_x0, right_top_box[X0_IDX]]), max([w_x1, right_top_box[X1_IDX]])-+ w_x0, w_x1 = min([w_x0, right_top_box[X0_IDX]]), max(+ [w_x1, right_top_box[X1_IDX]]+ )+# 检查是否与其他box相交, 垂直切分线与某些box发生相交,说明无法完全垂直方向切分。- if any([bbox[X0_IDX] <= w_x0-1 <= bbox[X1_IDX] for bbox in all_bboxes]):- unsplited_block.append([new_boundry[0], new_boundry[1], new_boundry[2], new_boundry[3], LAYOUT_UNPROC])+ if any([bbox[X0_IDX] <= w_x0 - 1 <= bbox[X1_IDX] for bbox in all_bboxes]):+ unsplited_block.append(+ [+ new_boundary[0],+ new_boundary[1],+ new_boundary[2],+ new_boundary[3],+ LAYOUT_UNPROC,+ ]+ )for b in all_bboxes:- if b[X0_IDX] <= w_x0-1 <= b[X1_IDX]:+ if b[X0_IDX] <= w_x0 - 1 <= b[X1_IDX]:bad_boxes.append([b[X0_IDX], b[Y0_IDX], b[X1_IDX], b[Y1_IDX]])break- else: # 说明成功分割出一列- v_blocks.append([w_x0, new_boundry[1], w_x1, new_boundry[3], LAYOUT_V])- new_boundry[2] = w_x0-+ else: # 说明成功分割出一列+ v_blocks.append([w_x0, new_boundary[1], w_x1, new_boundary[3], LAYOUT_V])+ new_boundary[2] = w_x0"""转换数据结构"""for block in v_blocks:- sorted_layout_blocks.append({- "layout_bbox": block[:4],- "layout_label":block[4],- "sub_layout":[],- })-+ sorted_layout_blocks.append(+ {+ 'layout_bbox': block[:4],+ 'layout_label': block[4],+ 'sub_layout': [],+ }+ )+for block in unsplited_block:- sorted_layout_blocks.append({- "layout_bbox": block[:4],- "layout_label":block[4],- "sub_layout":[],- "bad_boxes": bad_boxes # 记录下来,这个box是被割中的- })--+ sorted_layout_blocks.append(+ {+ 'layout_bbox': block[:4],+ 'layout_label': block[4],+ 'sub_layout': [],+ 'bad_boxes': bad_boxes, # 记录下来,这个box是被割中的+ }+ )+# 按照x0排序sorted_layout_blocks.sort(key=lambda x: x['layout_bbox'][0])return sorted_layout_blocks---def _try_horizontal_mult_column_split(bboxes:list, boundry:tuple)-> list:+def _try_horizontal_mult_column_split(bboxes: list, boundary: tuple) -> list:"""尝试水平切分,如果切分不动,那就当一个BAD_LAYOUT返回------------------@@ -406,51 +539,58 @@ def _try_horizontal_mult_column_split(bboxes:list, boundry:tuple)-> list:pass---def _vertical_split(bboxes:list, boundry:tuple)-> list:+def _vertical_split(bboxes: list, boundary: tuple) -> list:"""从垂直方向进行切割,分block这个版本里,如果垂直切分不动,那就当一个BAD_LAYOUT返回-+--------------------------| | || | || |- 这种列是此函数要切分的 -> | |+ 这种列是此函数要切分的 -> | || || | || | |-------------------------"""- sorted_layout_blocks = [] # 这是要最终返回的值-- bound_x0, bound_y0, bound_x1, bound_y1 = boundry- all_bboxes = get_bbox_in_boundry(bboxes, boundry)+ sorted_layout_blocks = [] # 这是要最终返回的值++ bound_x0, bound_y0, bound_x1, bound_y1 = boundary+ all_bboxes = get_bbox_in_boundary(bboxes, boundary)"""all_bboxes = fix_vertical_bbox_pos(all_bboxes) # 垂直方向解覆盖all_bboxes = fix_hor_bbox_pos(all_bboxes) # 水平解覆盖-+这两行代码目前先不执行,因为公式检测,表格检测还不是很成熟,导致非常多的textblock参与了运算,时间消耗太大。这两行代码的作用是:如果遇到互相重叠的bbox, 那么会把面积较小的box进行压缩,从而避免重叠。对布局切分来说带来正反馈。"""-- #all_bboxes = paper_bbox_sort(all_bboxes, abs(bound_x1-bound_x0), abs(bound_y1-bound_x0)) # 大致拍下序, 这个是基于直接遮挡的。++ # all_bboxes = paper_bbox_sort(all_bboxes, abs(bound_x1-bound_x0), abs(bound_y1-bound_x0)) # 大致拍下序, 这个是基于直接遮挡的。"""首先在垂直方向上扩展独占一行的bbox-+"""for bbox in all_bboxes:- top_nearest_bbox = find_all_top_bbox_direct(bbox, all_bboxes) # 非扩展线+ top_nearest_bbox = find_all_top_bbox_direct(bbox, all_bboxes) # 非扩展线bottom_nearest_bbox = find_all_bottom_bbox_direct(bbox, all_bboxes)- if top_nearest_bbox is None and bottom_nearest_bbox is None and not any([b[X0_IDX]<bbox[X1_IDX]<b[X1_IDX] or b[X0_IDX]<bbox[X0_IDX]<b[X1_IDX] for b in all_bboxes]): # 独占一列, 且不和其他重叠+ if (+ top_nearest_bbox is None+ and bottom_nearest_bbox is None+ and not any(+ [+ b[X0_IDX] < bbox[X1_IDX] < b[X1_IDX]+ or b[X0_IDX] < bbox[X0_IDX] < b[X1_IDX]+ for b in all_bboxes+ ]+ )+ ): # 独占一列, 且不和其他重叠bbox[X0_EXT_IDX] = bbox[X0_IDX]bbox[Y0_EXT_IDX] = bound_y0bbox[X1_EXT_IDX] = bbox[X1_IDX]bbox[Y1_EXT_IDX] = bound_y1-- """+ """此时独占一列的被成功扩展到指定的边界上,这个时候利用边界条件合并连续的bbox,成为一个group然后合并所有连续垂直方向的bbox."""@@ -458,20 +598,23 @@ def _vertical_split(bboxes:list, boundry:tuple)-> list:# fix: 这里水平方向的列不要合并成一个行,因为需要保证返回给下游的最小block,总是可以无脑从上到下阅读文字。v_bboxes = []for box in all_bboxes:- if box[Y0_EXT_IDX] == bound_y0 and box[Y1_EXT_IDX] == bound_y1:+ if box[Y0_EXT_IDX] == bound_y0 and box[Y1_EXT_IDX] == bound_y1:v_bboxes.append(box)-"""现在v_bboxes里面是所有的group了,每个group都是一个list对v_bboxes里的每个group进行计算放回到sorted_layouts里"""v_layouts = []for vbox in v_bboxes:- #gp.sort(key=lambda x: x[X0_IDX])+ # gp.sort(key=lambda x: x[X0_IDX])# 然后计算这个group的layout_bbox,也就是最小的x0,y0, 最大的x1,y1- x0, y0, x1, y1 = vbox[X0_EXT_IDX], vbox[Y0_EXT_IDX], vbox[X1_EXT_IDX], vbox[Y1_EXT_IDX]- v_layouts.append([x0, y0, x1, y1, LAYOUT_V]) # 垂直的布局-+ x0, y0, x1, y1 = (+ vbox[X0_EXT_IDX],+ vbox[Y0_EXT_IDX],+ vbox[X1_EXT_IDX],+ vbox[Y1_EXT_IDX],+ )+ v_layouts.append([x0, y0, x1, y1, LAYOUT_V]) # 垂直的布局"""接下来利用这些连续的垂直bbox的layout_bbox的x0, x1,从垂直上切分开其余的为几个部分"""@@ -481,29 +624,41 @@ def _vertical_split(bboxes:list, boundry:tuple)-> list:v_split_lines.append(x0)v_split_lines.append(x1)v_split_lines.append(bound_x1)-+unsplited_bboxes = []for i in range(0, len(v_split_lines), 2):- start_x0, start_x1 = v_split_lines[i:i+2]+ start_x0, start_x1 = v_split_lines[i : i + 2]# 然后找出[start_x0, start_x1]之间的其他bbox,这些组成一个未分割板块- bboxes_in_block = [bbox for bbox in all_bboxes if bbox[X0_IDX]>=start_x0 and bbox[X1_IDX]<=start_x1]+ bboxes_in_block = [+ bbox+ for bbox in all_bboxes+ if bbox[X0_IDX] >= start_x0 and bbox[X1_IDX] <= start_x1+ ]unsplited_bboxes.append(bboxes_in_block)# 接着把未处理的加入到v_layouts里for bboxes_in_block in unsplited_bboxes:if len(bboxes_in_block) == 0:continue- x0, y0, x1, y1 = min([bbox[X0_IDX] for bbox in bboxes_in_block]), bound_y0, max([bbox[X1_IDX] for bbox in bboxes_in_block]), bound_y1- v_layouts.append([x0, y0, x1, y1, LAYOUT_UNPROC]) # 说明这篇区域未能够分析出可靠的版面-- v_layouts.sort(key=lambda x: x[0]) # 按照x0排序, 也就是从左到右的顺序-+ x0, y0, x1, y1 = (+ min([bbox[X0_IDX] for bbox in bboxes_in_block]),+ bound_y0,+ max([bbox[X1_IDX] for bbox in bboxes_in_block]),+ bound_y1,+ )+ v_layouts.append(+ [x0, y0, x1, y1, LAYOUT_UNPROC]+ ) # 说明这篇区域未能够分析出可靠的版面++ v_layouts.sort(key=lambda x: x[0]) # 按照x0排序, 也就是从左到右的顺序+for layout in v_layouts:- sorted_layout_blocks.append({- "layout_bbox": layout[:4],- "layout_label":layout[4],- "sub_layout":[],- })-+ sorted_layout_blocks.append(+ {+ 'layout_bbox': layout[:4],+ 'layout_label': layout[4],+ 'sub_layout': [],+ }+ )"""至此,垂直方向切成了2种类型,其一是独占一列的,其二是未处理的。下面对这些未处理的进行垂直方向切分,这个切分要切出来类似“吕”这种类型的垂直方向的布局@@ -513,24 +668,32 @@ def _vertical_split(bboxes:list, boundry:tuple)-> list:x0, y0, x1, y1 = layout['layout_bbox']v_split_layouts = _vertical_align_split_v2(bboxes, [x0, y0, x1, y1])sorted_layout_blocks[i] = {- "layout_bbox": [x0, y0, x1, y1],- "layout_label": LAYOUT_H,- "sub_layout": v_split_layouts+ 'layout_bbox': [x0, y0, x1, y1],+ 'layout_label': LAYOUT_H,+ 'sub_layout': v_split_layouts,}- layout['layout_label'] = LAYOUT_H # 被垂线切分成了水平布局-+ layout['layout_label'] = LAYOUT_H # 被垂线切分成了水平布局+return sorted_layout_blocks--def split_layout(bboxes:list, boundry:tuple, page_num:int)-> list:++def split_layout(bboxes: list, boundary: tuple, page_num: int) -> list:"""把bboxes切割成layoutreturn:[{- "layout_bbox": [x0, y0, x1, y1],+ "layout_bbox": [x0,y0,x1,y1],"layout_label":"u|v|h|b", 未处理|垂直|水平|BAD_LAYOUT- "sub_layout": [] #每个元素都是[x0, y0, x1, y1, block_content, idx_x, idx_y, content_type, ext_x0, ext_y0, ext_x1, ext_y1], 并且顺序就是阅读顺序+ "sub_layout":[] #每个元素都是[+ x0,y0,+ x1,y1,+ block_content,+ idx_x,idx_y,+ content_type,+ ext_x0,ext_y0,+ ext_x1,ext_y1+ ], 并且顺序就是阅读顺序}]example:@@ -539,7 +702,7 @@ def split_layout(bboxes:list, boundry:tuple, page_num:int)-> list:"layout_bbox": [0, 0, 100, 100],"layout_label":"u|v|h|b","sub_layout":[-+]},{@@ -559,35 +722,35 @@ def split_layout(bboxes:list, boundry:tuple, page_num:int)-> list:"layout_bbox": [0, 0, 100, 100],"layout_label":"u|v|h|b","sub_layout":[-+]}}- ]+ ]"""- sorted_layouts = [] # 最终返回的结果-- boundry_x0, boundry_y0, boundry_x1, boundry_y1 = boundry- if len(bboxes) <=1:+ sorted_layouts = [] # 最终返回的结果++ boundary_x0, boundary_y0, boundary_x1, boundary_y1 = boundary+ if len(bboxes) <= 1:return [{- "layout_bbox": [boundry_x0, boundry_y0, boundry_x1, boundry_y1],- "layout_label": LAYOUT_V,- "sub_layout":[]+ 'layout_bbox': [boundary_x0, boundary_y0, boundary_x1, boundary_y1],+ 'layout_label': LAYOUT_V,+ 'sub_layout': [],}]-"""接下来按照先水平后垂直的顺序进行切分"""- bboxes = paper_bbox_sort(bboxes, boundry_x1-boundry_x0, boundry_y1-boundry_y0)- sorted_layouts = _horizontal_split(bboxes, boundry) # 通过水平分割出来的layout+ bboxes = paper_bbox_sort(+ bboxes, boundary_x1 - boundary_x0, boundary_y1 - boundary_y0+ )+ sorted_layouts = _horizontal_split(bboxes, boundary) # 通过水平分割出来的layoutfor i, layout in enumerate(sorted_layouts):x0, y0, x1, y1 = layout['layout_bbox']layout_type = layout['layout_label']- if layout_type == LAYOUT_UNPROC: # 说明是非独占单行的,这些需要垂直切分+ if layout_type == LAYOUT_UNPROC: # 说明是非独占单行的,这些需要垂直切分v_split_layouts = _vertical_split(bboxes, [x0, y0, x1, y1])-"""最后这里有个逻辑问题:如果这个函数只分离出来了一个column layout,那么这个layout分割肯定超出了算法能力范围。因为我们假定的是传进来的box已经把行全部剥离了,所以这里必须十多个列才可以。如果只剥离出来一个layout,并且是多个box,那么就说明这个layout是无法分割的,标记为LAYOUT_UNPROC@@ -596,28 +759,26 @@ def split_layout(bboxes:list, boundry:tuple, page_num:int)-> list:if len(v_split_layouts) == 1:if len(v_split_layouts[0]['sub_layout']) == 0:layout_label = LAYOUT_UNPROC- #logger.warning(f"WARNING: pageno={page_num}, 无法分割的layout: ", v_split_layouts)-+ # logger.warning(f"WARNING: pageno={page_num}, 无法分割的layout: ", v_split_layouts)"""组合起来最终的layout"""sorted_layouts[i] = {- "layout_bbox": [x0, y0, x1, y1],- "layout_label": layout_label,- "sub_layout": v_split_layouts+ 'layout_bbox': [x0, y0, x1, y1],+ 'layout_label': layout_label,+ 'sub_layout': v_split_layouts,}layout['layout_label'] = LAYOUT_H-"""水平和垂直方向都切分完毕了。此时还有一些未处理的,这些未处理的可能是因为水平和垂直方向都无法切分。这些最后调用_try_horizontal_mult_block_split做一次水平多个block的联合切分,如果也不能切分最终就当做BAD_LAYOUT返回"""# TODO-+return sorted_layouts-def get_bboxes_layout(all_boxes:list, boundry:tuple, page_id:int):+def get_bboxes_layout(all_boxes: list, boundary: tuple, page_id: int):"""对利用layout排序之后的box,进行排序return:@@ -628,10 +789,10 @@ def get_bboxes_layout(all_boxes:list, boundry:tuple, page_id:int):},]"""+def _preorder_traversal(layout):- """- 对sorted_layouts的叶子节点,也就是len(sub_layout)==0的节点进行排序。排序按照前序遍历的顺序,也就是从上到下,从左到右的顺序- """+ """对sorted_layouts的叶子节点,也就是len(sub_layout)==0的节点进行排序。排序按照前序遍历的顺序,也就是从上到+ 下,从左到右的顺序."""sorted_layout_blocks = []for layout in layout:sub_layout = layout['sub_layout']@@ -641,71 +802,89 @@ def get_bboxes_layout(all_boxes:list, boundry:tuple, page_id:int):s = _preorder_traversal(sub_layout)sorted_layout_blocks.extend(s)return sorted_layout_blocks+# -------------------------------------------------------------------------------------------------------------------------- sorted_layouts = split_layout(all_boxes, boundry, page_id)# 先切分成layout,得到一个Tree- total_sorted_layout_blocks = _preorder_traversal(sorted_layouts)+ sorted_layouts = split_layout(+ all_boxes, boundary, page_id+ ) # 先切分成layout,得到一个Tree+ total_sorted_layout_blocks = _preorder_traversal(sorted_layouts)return total_sorted_layout_blocks, sorted_layoutsdef get_columns_cnt_of_layout(layout_tree):- """- 获取一个layout的宽度- """- max_width_list = [0] # 初始化一个元素,防止max,min函数报错-- for items in layout_tree: # 针对每一层(横切)计算列数,横着的算一列+ """获取一个layout的宽度."""+ max_width_list = [0] # 初始化一个元素,防止max,min函数报错++ for items in layout_tree: # 针对每一层(横切)计算列数,横着的算一列layout_type = items['layout_label']sub_layouts = items['sub_layout']- if len(sub_layouts)==0:+ if len(sub_layouts) == 0:max_width_list.append(1)else:if layout_type == LAYOUT_H:max_width_list.append(1)else:width = 0- for l in sub_layouts:- if len(l['sub_layout']) == 0:+ for sub_layout in sub_layouts:+ if len(sub_layout['sub_layout']) == 0:width += 1else:- for lay in l['sub_layout']:+ for lay in sub_layout['sub_layout']:width += get_columns_cnt_of_layout([lay])max_width_list.append(width)-+return max(max_width_list)---def sort_with_layout(bboxes:list, page_width, page_height) -> (list,list):- """- 输入是一个bbox的list.++def sort_with_layout(bboxes: list, page_width, page_height) -> (list, list):+ """输入是一个bbox的list.+获取到输入之后,先进行layout切分,然后对这些bbox进行排序。返回排序后的bboxes"""new_bboxes = []for box in bboxes:# new_bboxes.append([box[0], box[1], box[2], box[3], None, None, None, 'text', None, None, None, None])- new_bboxes.append([box[0], box[1], box[2], box[3], None, None, None, 'text', None, None, None, None, box[4]])-- layout_bboxes, _ = get_bboxes_layout(new_bboxes, [0, 0, page_width, page_height], 0)- if any([lay['layout_label']==LAYOUT_UNPROC for lay in layout_bboxes]):- logger.warning(f"drop this pdf, reason: 复杂版面")- return None,None-- sorted_bboxes = []+ new_bboxes.append(+ [+ box[0],+ box[1],+ box[2],+ box[3],+ None,+ None,+ None,+ 'text',+ None,+ None,+ None,+ None,+ box[4],+ ]+ )++ layout_bboxes, _ = get_bboxes_layout(+ new_bboxes, tuple([0, 0, page_width, page_height]), 0+ )+ if any([lay['layout_label'] == LAYOUT_UNPROC for lay in layout_bboxes]):+ logger.warning('drop this pdf, reason: 复杂版面')+ return None, None++ sorted_bboxes = []# 利用layout bbox每次框定一些box,然后排序for layout in layout_bboxes:lbox = layout['layout_bbox']- bbox_in_layout = get_bbox_in_boundry(new_bboxes, lbox)- sorted_bbox = paper_bbox_sort(bbox_in_layout, lbox[2]-lbox[0], lbox[3]-lbox[1])+ bbox_in_layout = get_bbox_in_boundary(new_bboxes, lbox)+ sorted_bbox = paper_bbox_sort(+ bbox_in_layout, lbox[2] - lbox[0], lbox[3] - lbox[1]+ )sorted_bboxes.extend(sorted_bbox)-+return sorted_bboxes, layout_bboxesdef sort_text_block(text_block, layout_bboxes):- """- 对一页的text_block进行排序- """+ """对一页的text_block进行排序."""sorted_text_bbox = []all_text_bbox = []# 做一个box=>text的映射@@ -714,19 +893,29 @@ def sort_text_block(text_block, layout_bboxes):box = blk['bbox']box_to_text[(box[0], box[1], box[2], box[3])] = blkall_text_bbox.append(box)-+# text_blocks_to_sort = []# for box in box_to_text.keys():# text_blocks_to_sort.append([box[0], box[1], box[2], box[3], None, None, None, 'text', None, None, None, None])-+# 按照layout_bboxes的顺序,对text_block进行排序for layout in layout_bboxes:layout_box = layout['layout_bbox']- text_bbox_in_layout = get_bbox_in_boundry(all_text_bbox, [layout_box[0]-1, layout_box[1]-1, layout_box[2]+1, layout_box[3]+1])- #sorted_bbox = paper_bbox_sort(text_bbox_in_layout, layout_box[2]-layout_box[0], layout_box[3]-layout_box[1])- text_bbox_in_layout.sort(key = lambda x: x[1]) # 一个layout内部的box,按照y0自上而下排序- #sorted_bbox = [[b] for b in text_blocks_to_sort]+ text_bbox_in_layout = get_bbox_in_boundary(+ all_text_bbox,+ [+ layout_box[0] - 1,+ layout_box[1] - 1,+ layout_box[2] + 1,+ layout_box[3] + 1,+ ],+ )+ # sorted_bbox = paper_bbox_sort(text_bbox_in_layout, layout_box[2]-layout_box[0], layout_box[3]-layout_box[1])+ text_bbox_in_layout.sort(+ key=lambda x: x[1]+ ) # 一个layout内部的box,按照y0自上而下排序+ # sorted_bbox = [[b] for b in text_blocks_to_sort]for sb in text_bbox_in_layout:sorted_text_bbox.append(box_to_text[(sb[0], sb[1], sb[2], sb[3])])-+return sorted_text_bboxdiff --git a/magic_pdf/libs/boxbase.py b/magic_pdf/libs/boxbase.pyindex 1e4e3430..90f46ef2 100644--- a/magic_pdf/libs/boxbase.py+++ b/magic_pdf/libs/boxbase.py@@ -1,168 +1,166 @@---from loguru import loggerimport math+def _is_in_or_part_overlap(box1, box2) -> bool:- """- 两个bbox是否有部分重叠或者包含- """+ """两个bbox是否有部分重叠或者包含."""if box1 is None or box2 is None:return False-+x0_1, y0_1, x1_1, y1_1 = box1x0_2, y0_2, x1_2, y1_2 = box2return not (x1_1 < x0_2 or # box1在box2的左边x0_1 > x1_2 or # box1在box2的右边y1_1 < y0_2 or # box1在box2的上边- y0_1 > y1_2) # box1在box2的下边+ y0_1 > y1_2) # box1在box2的下边-def _is_in_or_part_overlap_with_area_ratio(box1, box2, area_ratio_threshold=0.6):- """- 判断box1是否在box2里面,或者box1和box2有部分重叠,且重叠面积占box1的比例超过area_ratio_threshold-- """++def _is_in_or_part_overlap_with_area_ratio(box1,+ box2,+ area_ratio_threshold=0.6):+ """判断box1是否在box2里面,或者box1和box2有部分重叠,且重叠面积占box1的比例超过area_ratio_threshold."""if box1 is None or box2 is None:return False-+x0_1, y0_1, x1_1, y1_1 = box1x0_2, y0_2, x1_2, y1_2 = box2if not _is_in_or_part_overlap(box1, box2):return False-+# 计算重叠面积x_left = max(x0_1, x0_2)y_top = max(y0_1, y0_2)x_right = min(x1_1, x1_2)y_bottom = min(y1_1, y1_2)overlap_area = (x_right - x_left) * (y_bottom - y_top)-+# 计算box1的面积box1_area = (x1_1 - x0_1) * (y1_1 - y0_1)-+return overlap_area / box1_area > area_ratio_threshold--++def _is_in(box1, box2) -> bool:- """- box1是否完全在box2里面- """+ """box1是否完全在box2里面."""x0_1, y0_1, x1_1, y1_1 = box1x0_2, y0_2, x1_2, y1_2 = box2return (x0_1 >= x0_2 and # box1的左边界不在box2的左边外y0_1 >= y0_2 and # box1的上边界不在box2的上边外x1_1 <= x1_2 and # box1的右边界不在box2的右边外- y1_1 <= y1_2) # box1的下边界不在box2的下边外-+ y1_1 <= y1_2) # box1的下边界不在box2的下边外++def _is_part_overlap(box1, box2) -> bool:- """- 两个bbox是否有部分重叠,但不完全包含- """+ """两个bbox是否有部分重叠,但不完全包含."""if box1 is None or box2 is None:return False-+return _is_in_or_part_overlap(box1, box2) and not _is_in(box1, box2)+def _left_intersect(left_box, right_box):- "检查两个box的左边界是否有交集,也就是left_box的右边界是否在right_box的左边界内"+ """检查两个box的左边界是否有交集,也就是left_box的右边界是否在right_box的左边界内."""if left_box is None or right_box is None:return False-+x0_1, y0_1, x1_1, y1_1 = left_boxx0_2, y0_2, x1_2, y1_2 = right_box-- return x1_1>x0_2 and x0_1<x0_2 and (y0_1<=y0_2<=y1_1 or y0_1<=y1_2<=y1_1)++ return x1_1 > x0_2 and x0_1 < x0_2 and (y0_1 <= y0_2 <= y1_1+ or y0_1 <= y1_2 <= y1_1)+def _right_intersect(left_box, right_box):- """- 检查box是否在右侧边界有交集,也就是left_box的左边界是否在right_box的右边界内- """+ """检查box是否在右侧边界有交集,也就是left_box的左边界是否在right_box的右边界内."""if left_box is None or right_box is None:return False-+x0_1, y0_1, x1_1, y1_1 = left_boxx0_2, y0_2, x1_2, y1_2 = right_box-- return x0_1<x1_2 and x1_1>x1_2 and (y0_1<=y0_2<=y1_1 or y0_1<=y1_2<=y1_1)++ return x0_1 < x1_2 and x1_1 > x1_2 and (y0_1 <= y0_2 <= y1_1+ or y0_1 <= y1_2 <= y1_1)def _is_vertical_full_overlap(box1, box2, x_torlence=2):- """- x方向上:要么box1包含box2, 要么box2包含box1。不能部分包含- y方向上:box1和box2有重叠- """+ """x方向上:要么box1包含box2, 要么box2包含box1。不能部分包含 y方向上:box1和box2有重叠."""# 解析box的坐标x11, y11, x12, y12 = box1 # 左上角和右下角的坐标 (x1, y1, x2, y2)x21, y21, x22, y22 = box2# 在x轴方向上,box1是否包含box2 或 box2包含box1- contains_in_x = (x11-x_torlence <= x21 and x12+x_torlence >= x22) or (x21-x_torlence <= x11 and x22+x_torlence >= x12)+ contains_in_x = (x11 - x_torlence <= x21 and x12 + x_torlence >= x22) or (+ x21 - x_torlence <= x11 and x22 + x_torlence >= x12)# 在y轴方向上,box1和box2是否有重叠overlap_in_y = not (y12 < y21 or y11 > y22)return contains_in_x and overlap_in_y-+def _is_bottom_full_overlap(box1, box2, y_tolerance=2):- """- 检查box1下方和box2的上方有轻微的重叠,轻微程度收到y_tolerance的限制- 这个函数和_is_vertical-full_overlap的区别是,这个函数允许box1和box2在x方向上有轻微的重叠,允许一定的模糊度- """+ """检查box1下方和box2的上方有轻微的重叠,轻微程度收到y_tolerance的限制 这个函数和_is_vertical-+ full_overlap的区别是,这个函数允许box1和box2在x方向上有轻微的重叠,允许一定的模糊度."""if box1 is None or box2 is None:return False-+x0_1, y0_1, x1_1, y1_1 = box1x0_2, y0_2, x1_2, y1_2 = box2tolerance_margin = 2- is_xdir_full_overlap = ((x0_1-tolerance_margin<=x0_2<=x1_1+tolerance_margin and x0_1-tolerance_margin<=x1_2<=x1_1+tolerance_margin) or (x0_2-tolerance_margin<=x0_1<=x1_2+tolerance_margin and x0_2-tolerance_margin<=x1_1<=x1_2+tolerance_margin))-- return y0_2<y1_1 and 0<(y1_1-y0_2)<y_tolerance and is_xdir_full_overlap+ is_xdir_full_overlap = (+ (x0_1 - tolerance_margin <= x0_2 <= x1_1 + tolerance_margin+ and x0_1 - tolerance_margin <= x1_2 <= x1_1 + tolerance_margin)+ or (x0_2 - tolerance_margin <= x0_1 <= x1_2 + tolerance_margin+ and x0_2 - tolerance_margin <= x1_1 <= x1_2 + tolerance_margin))++ return y0_2 < y1_1 and 0 < (y1_1 -+ y0_2) < y_tolerance and is_xdir_full_overlap+++def _is_left_overlap(+ box1,+ box2,+):+ """检查box1的左侧是否和box2有重叠 在Y方向上可以是部分重叠或者是完全重叠。不分box1和box2的上下关系,也就是无论box1在box2下+ 方还是box2在box1下方,都可以检测到重叠。 X方向上."""-def _is_left_overlap(box1, box2,):- """- 检查box1的左侧是否和box2有重叠- 在Y方向上可以是部分重叠或者是完全重叠。不分box1和box2的上下关系,也就是无论box1在box2下方还是box2在box1下方,都可以检测到重叠。- X方向上- """def __overlap_y(Ay1, Ay2, By1, By2):return max(0, min(Ay2, By2) - max(Ay1, By1))-+if box1 is None or box2 is None:return False-+x0_1, y0_1, x1_1, y1_1 = box1x0_2, y0_2, x1_2, y1_2 = box2-+y_overlap_len = __overlap_y(y0_1, y1_1, y0_2, y1_2)- ratio_1 = 1.0 * y_overlap_len / (y1_1 - y0_1) if y1_1-y0_1!=0 else 0- ratio_2 = 1.0 * y_overlap_len / (y1_2 - y0_2) if y1_2-y0_2!=0 else 0+ ratio_1 = 1.0 * y_overlap_len / (y1_1 - y0_1) if y1_1 - y0_1 != 0 else 0+ ratio_2 = 1.0 * y_overlap_len / (y1_2 - y0_2) if y1_2 - y0_2 != 0 else 0vertical_overlap_cond = ratio_1 >= 0.5 or ratio_2 >= 0.5-- #vertical_overlap_cond = y0_1<=y0_2<=y1_1 or y0_1<=y1_2<=y1_1 or y0_2<=y0_1<=y1_2 or y0_2<=y1_1<=y1_2- return x0_1<=x0_2<=x1_1 and vertical_overlap_cond+ # vertical_overlap_cond = y0_1<=y0_2<=y1_1 or y0_1<=y1_2<=y1_1 or y0_2<=y0_1<=y1_2 or y0_2<=y1_1<=y1_2+ return x0_1 <= x0_2 <= x1_1 and vertical_overlap_cond-def __is_overlaps_y_exceeds_threshold(bbox1, bbox2, overlap_ratio_threshold=0.8):++def __is_overlaps_y_exceeds_threshold(bbox1,+ bbox2,+ overlap_ratio_threshold=0.8):"""检查两个bbox在y轴上是否有重叠,并且该重叠区域的高度占两个bbox高度更低的那个超过80%"""_, y0_1, _, y1_1 = bbox1_, y0_2, _, y1_2 = bbox2overlap = max(0, min(y1_1, y1_2) - max(y0_1, y0_2))height1, height2 = y1_1 - y0_1, y1_2 - y0_2- max_height = max(height1, height2)+ # max_height = max(height1, height2)min_height = min(height1, height2)return (overlap / min_height) > overlap_ratio_threshold-def calculate_iou(bbox1, bbox2):- """- 计算两个边界框的交并比(IOU)。+ """计算两个边界框的交并比(IOU)。Args:bbox1 (list[float]): 第一个边界框的坐标,格式为 [x1, y1, x2, y2],其中 (x1, y1) 为左上角坐标,(x2, y2) 为右下角坐标。@@ -170,7 +168,6 @@ def calculate_iou(bbox1, bbox2):Returns:float: 两个边界框的交并比(IOU),取值范围为 [0, 1]。-"""# Determine the coordinates of the intersection rectanglex_left = max(bbox1[0], bbox2[0])@@ -188,16 +185,15 @@ def calculate_iou(bbox1, bbox2):bbox1_area = (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1])bbox2_area = (bbox2[2] - bbox2[0]) * (bbox2[3] - bbox2[1])- # Compute the intersection over union by taking the intersection area+ # Compute the intersection over union by taking the intersection area# and dividing it by the sum of both areas minus the intersection area- iou = intersection_area / float(bbox1_area + bbox2_area - intersection_area)+ iou = intersection_area / float(bbox1_area + bbox2_area -+ intersection_area)return ioudef calculate_overlap_area_2_minbox_area_ratio(bbox1, bbox2):- """- 计算box1和box2的重叠面积占最小面积的box的比例- """+ """计算box1和box2的重叠面积占最小面积的box的比例."""# Determine the coordinates of the intersection rectanglex_left = max(bbox1[0], bbox2[0])y_top = max(bbox1[1], bbox2[1])@@ -209,16 +205,16 @@ def calculate_overlap_area_2_minbox_area_ratio(bbox1, bbox2):# The area of overlap areaintersection_area = (x_right - x_left) * (y_bottom - y_top)- min_box_area = min([(bbox1[2]-bbox1[0])*(bbox1[3]-bbox1[1]), (bbox2[3]-bbox2[1])*(bbox2[2]-bbox2[0])])- if min_box_area==0:+ min_box_area = min([(bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1]),+ (bbox2[3] - bbox2[1]) * (bbox2[2] - bbox2[0])])+ if min_box_area == 0:return 0else:return intersection_area / min_box_area+def calculate_overlap_area_in_bbox1_area_ratio(bbox1, bbox2):- """- 计算box1和box2的重叠面积占bbox1的比例- """+ """计算box1和box2的重叠面积占bbox1的比例."""# Determine the coordinates of the intersection rectanglex_left = max(bbox1[0], bbox2[0])y_top = max(bbox1[1], bbox2[1])@@ -230,7 +226,7 @@ def calculate_overlap_area_in_bbox1_area_ratio(bbox1, bbox2):# The area of overlap areaintersection_area = (x_right - x_left) * (y_bottom - y_top)- bbox1_area = (bbox1[2]-bbox1[0])*(bbox1[3]-bbox1[1])+ bbox1_area = (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1])if bbox1_area == 0:return 0else:@@ -238,11 +234,8 @@ def calculate_overlap_area_in_bbox1_area_ratio(bbox1, bbox2):def get_minbox_if_overlap_by_ratio(bbox1, bbox2, ratio):- """- 通过calculate_overlap_area_2_minbox_area_ratio计算两个bbox重叠的面积占最小面积的box的比例- 如果比例大于ratio,则返回小的那个bbox,- 否则返回None- """+ """通过calculate_overlap_area_2_minbox_area_ratio计算两个bbox重叠的面积占最小面积的box的比例+ 如果比例大于ratio,则返回小的那个bbox, 否则返回None."""x1_min, y1_min, x1_max, y1_max = bbox1x2_min, y2_min, x2_max, y2_max = bbox2area1 = (x1_max - x1_min) * (y1_max - y1_min)@@ -256,89 +249,118 @@ def get_minbox_if_overlap_by_ratio(bbox1, bbox2, ratio):else:return None-def get_bbox_in_boundry(bboxes:list, boundry:tuple)-> list:- x0, y0, x1, y1 = boundry- new_boxes = [box for box in bboxes if box[0] >= x0 and box[1] >= y0 and box[2] <= x1 and box[3] <= y1]++def get_bbox_in_boundary(bboxes: list, boundary: tuple) -> list:+ x0, y0, x1, y1 = boundary+ new_boxes = [+ box for box in bboxes+ if box[0] >= x0 and box[1] >= y0 and box[2] <= x1 and box[3] <= y1+ ]return new_boxesdef is_vbox_on_side(bbox, width, height, side_threshold=0.2):- """- 判断一个bbox是否在pdf页面的边缘- """+ """判断一个bbox是否在pdf页面的边缘."""x0, x1 = bbox[0], bbox[2]- if x1<=width*side_threshold or x0>=width*(1-side_threshold):+ if x1 <= width * side_threshold or x0 >= width * (1 - side_threshold):return Truereturn False+def find_top_nearest_text_bbox(pymu_blocks, obj_bbox):tolerance_margin = 4- top_boxes = [box for box in pymu_blocks if obj_bbox[1]-box['bbox'][3] >=-tolerance_margin and not _is_in(box['bbox'], obj_bbox)]+ top_boxes = [+ box for box in pymu_blocks+ if obj_bbox[1] - box['bbox'][3] >= -tolerance_margin+ and not _is_in(box['bbox'], obj_bbox)+ ]# 然后找到X方向上有互相重叠的- top_boxes = [box for box in top_boxes if any([obj_bbox[0]-tolerance_margin <=box['bbox'][0]<=obj_bbox[2]+tolerance_margin,- obj_bbox[0]-tolerance_margin <=box['bbox'][2]<=obj_bbox[2]+tolerance_margin,- box['bbox'][0]-tolerance_margin <=obj_bbox[0]<=box['bbox'][2]+tolerance_margin,- box['bbox'][0]-tolerance_margin <=obj_bbox[2]<=box['bbox'][2]+tolerance_margin- ])]-+ top_boxes = [+ box for box in top_boxes if any([+ obj_bbox[0] - tolerance_margin <= box['bbox'][0] <= obj_bbox[2] ++ tolerance_margin, obj_bbox[0] -+ tolerance_margin <= box['bbox'][2] <= obj_bbox[2] ++ tolerance_margin, box['bbox'][0] -+ tolerance_margin <= obj_bbox[0] <= box['bbox'][2] ++ tolerance_margin, box['bbox'][0] -+ tolerance_margin <= obj_bbox[2] <= box['bbox'][2] ++ tolerance_margin+ ])+ ]+# 然后找到y1最大的那个- if len(top_boxes)>0:+ if len(top_boxes) > 0:top_boxes.sort(key=lambda x: x['bbox'][3], reverse=True)return top_boxes[0]else:return None-+def find_bottom_nearest_text_bbox(pymu_blocks, obj_bbox):- bottom_boxes = [box for box in pymu_blocks if box['bbox'][1] - obj_bbox[3]>=-2 and not _is_in(box['bbox'], obj_bbox)]+ bottom_boxes = [+ box for box in pymu_blocks if box['bbox'][1] -+ obj_bbox[3] >= -2 and not _is_in(box['bbox'], obj_bbox)+ ]# 然后找到X方向上有互相重叠的- bottom_boxes = [box for box in bottom_boxes if any([obj_bbox[0]-2 <=box['bbox'][0]<=obj_bbox[2]+2,- obj_bbox[0]-2 <=box['bbox'][2]<=obj_bbox[2]+2,- box['bbox'][0]-2 <=obj_bbox[0]<=box['bbox'][2]+2,- box['bbox'][0]-2 <=obj_bbox[2]<=box['bbox'][2]+2- ])]-+ bottom_boxes = [+ box for box in bottom_boxes if any([+ obj_bbox[0] - 2 <= box['bbox'][0] <= obj_bbox[2] + 2, obj_bbox[0] -+ 2 <= box['bbox'][2] <= obj_bbox[2] + 2, box['bbox'][0] -+ 2 <= obj_bbox[0] <= box['bbox'][2] + 2, box['bbox'][0] -+ 2 <= obj_bbox[2] <= box['bbox'][2] + 2+ ])+ ]+# 然后找到y0最小的那个- if len(bottom_boxes)>0:+ if len(bottom_boxes) > 0:bottom_boxes.sort(key=lambda x: x['bbox'][1], reverse=False)return bottom_boxes[0]else:return None+def find_left_nearest_text_bbox(pymu_blocks, obj_bbox):- """- 寻找左侧最近的文本block- """- left_boxes = [box for box in pymu_blocks if obj_bbox[0]-box['bbox'][2]>=-2 and not _is_in(box['bbox'], obj_bbox)]+ """寻找左侧最近的文本block."""+ left_boxes = [+ box for box in pymu_blocks if obj_bbox[0] -+ box['bbox'][2] >= -2 and not _is_in(box['bbox'], obj_bbox)+ ]# 然后找到X方向上有互相重叠的- left_boxes = [box for box in left_boxes if any([obj_bbox[1]-2 <=box['bbox'][1]<=obj_bbox[3]+2,- obj_bbox[1]-2 <=box['bbox'][3]<=obj_bbox[3]+2,- box['bbox'][1]-2 <=obj_bbox[1]<=box['bbox'][3]+2,- box['bbox'][1]-2 <=obj_bbox[3]<=box['bbox'][3]+2- ])]-+ left_boxes = [+ box for box in left_boxes if any([+ obj_bbox[1] - 2 <= box['bbox'][1] <= obj_bbox[3] + 2, obj_bbox[1] -+ 2 <= box['bbox'][3] <= obj_bbox[3] + 2, box['bbox'][1] -+ 2 <= obj_bbox[1] <= box['bbox'][3] + 2, box['bbox'][1] -+ 2 <= obj_bbox[3] <= box['bbox'][3] + 2+ ])+ ]+# 然后找到x1最大的那个- if len(left_boxes)>0:+ if len(left_boxes) > 0:left_boxes.sort(key=lambda x: x['bbox'][2], reverse=True)return left_boxes[0]else:return None-+def find_right_nearest_text_bbox(pymu_blocks, obj_bbox):- """- 寻找右侧最近的文本block- """- right_boxes = [box for box in pymu_blocks if box['bbox'][0]-obj_bbox[2]>=-2 and not _is_in(box['bbox'], obj_bbox)]+ """寻找右侧最近的文本block."""+ right_boxes = [+ box for box in pymu_blocks if box['bbox'][0] -+ obj_bbox[2] >= -2 and not _is_in(box['bbox'], obj_bbox)+ ]# 然后找到X方向上有互相重叠的- right_boxes = [box for box in right_boxes if any([obj_bbox[1]-2 <=box['bbox'][1]<=obj_bbox[3]+2,- obj_bbox[1]-2 <=box['bbox'][3]<=obj_bbox[3]+2,- box['bbox'][1]-2 <=obj_bbox[1]<=box['bbox'][3]+2,- box['bbox'][1]-2 <=obj_bbox[3]<=box['bbox'][3]+2- ])]-+ right_boxes = [+ box for box in right_boxes if any([+ obj_bbox[1] - 2 <= box['bbox'][1] <= obj_bbox[3] + 2, obj_bbox[1] -+ 2 <= box['bbox'][3] <= obj_bbox[3] + 2, box['bbox'][1] -+ 2 <= obj_bbox[1] <= box['bbox'][3] + 2, box['bbox'][1] -+ 2 <= obj_bbox[3] <= box['bbox'][3] + 2+ ])+ ]+# 然后找到x0最小的那个- if len(right_boxes)>0:+ if len(right_boxes) > 0:right_boxes.sort(key=lambda x: x['bbox'][0], reverse=False)return right_boxes[0]else:@@ -346,8 +368,7 @@ def find_right_nearest_text_bbox(pymu_blocks, obj_bbox):def bbox_relative_pos(bbox1, bbox2):- """- 判断两个矩形框的相对位置关系+ """判断两个矩形框的相对位置关系.Args:bbox1: 一个四元组,表示第一个矩形框的左上角和右下角的坐标,格式为(x1, y1, x1b, y1b)@@ -357,20 +378,19 @@ def bbox_relative_pos(bbox1, bbox2):一个四元组,表示矩形框1相对于矩形框2的位置关系,格式为(left, right, bottom, top)其中,left表示矩形框1是否在矩形框2的左侧,right表示矩形框1是否在矩形框2的右侧,bottom表示矩形框1是否在矩形框2的下方,top表示矩形框1是否在矩形框2的上方-"""x1, y1, x1b, y1b = bbox1x2, y2, x2b, y2b = bbox2-+left = x2b < x1right = x1b < x2bottom = y2b < y1top = y1b < y2return left, right, bottom, top-++def bbox_distance(bbox1, bbox2):- """- 计算两个矩形框的距离。+ """计算两个矩形框的距离。Args:bbox1 (tuple): 第一个矩形框的坐标,格式为 (x1, y1, x2, y2),其中 (x1, y1) 为左上角坐标,(x2, y2) 为右下角坐标。@@ -378,16 +398,17 @@ def bbox_distance(bbox1, bbox2):Returns:float: 矩形框之间的距离。-"""+def dist(point1, point2):- return math.sqrt((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2)-+ return math.sqrt((point1[0] - point2[0])**2 ++ (point1[1] - point2[1])**2)+x1, y1, x1b, y1b = bbox1x2, y2, x2b, y2b = bbox2-+left, right, bottom, top = bbox_relative_pos(bbox1, bbox2)-+if top and left:return dist((x1, y1b), (x2b, y2))elif left and bottom:@@ -404,5 +425,4 @@ def bbox_distance(bbox1, bbox2):return y1 - y2belif top:return y2 - y1b- else: # rectangles intersect- return 0\ No newline at end of file+ return 0.0diff --git a/magic_pdf/libs/draw_bbox.py b/magic_pdf/libs/draw_bbox.pyindex 20e54342..1346c392 100644--- a/magic_pdf/libs/draw_bbox.py+++ b/magic_pdf/libs/draw_bbox.py@@ -1,6 +1,6 @@-from magic_pdf.libs.Constants import CROSS_PAGEfrom magic_pdf.libs.commons import fitz # PyMuPDF-from magic_pdf.libs.ocr_content_type import ContentType, BlockType, CategoryId+from magic_pdf.libs.Constants import CROSS_PAGE+from magic_pdf.libs.ocr_content_type import BlockType, CategoryId, ContentTypefrom magic_pdf.model.magic_model import MagicModel@@ -65,11 +65,13 @@ def draw_bbox_with_number(i, bbox_list, page, rgb_config, fill_config):) # Insert the index in the top left corner of the rectangle-def draw_layout_bbox(pdf_info, pdf_bytes, out_path):+def draw_layout_bbox(pdf_info, pdf_bytes, out_path, filename):layout_bbox_list = []dropped_bbox_list = []- tables_list, tables_body_list, tables_caption_list, tables_footnote_list = [], [], [], []+ tables_list, tables_body_list = [], []+ tables_caption_list, tables_footnote_list = [], []imgs_list, imgs_body_list, imgs_caption_list = [], [], []+ imgs_footnote_list = []titles_list = []texts_list = []interequations_list = []@@ -77,41 +79,43 @@ def draw_layout_bbox(pdf_info, pdf_bytes, out_path):page_layout_list = []page_dropped_list = []tables, tables_body, tables_caption, tables_footnote = [], [], [], []- imgs, imgs_body, imgs_caption = [], [], []+ imgs, imgs_body, imgs_caption, imgs_footnote = [], [], [], []titles = []texts = []interequations = []- for layout in page["layout_bboxes"]:- page_layout_list.append(layout["layout_bbox"])+ for layout in page['layout_bboxes']:+ page_layout_list.append(layout['layout_bbox'])layout_bbox_list.append(page_layout_list)- for dropped_bbox in page["discarded_blocks"]:- page_dropped_list.append(dropped_bbox["bbox"])+ for dropped_bbox in page['discarded_blocks']:+ page_dropped_list.append(dropped_bbox['bbox'])dropped_bbox_list.append(page_dropped_list)- for block in page["para_blocks"]:- bbox = block["bbox"]- if block["type"] == BlockType.Table:+ for block in page['para_blocks']:+ bbox = block['bbox']+ if block['type'] == BlockType.Table:tables.append(bbox)- for nested_block in block["blocks"]:- bbox = nested_block["bbox"]- if nested_block["type"] == BlockType.TableBody:+ for nested_block in block['blocks']:+ bbox = nested_block['bbox']+ if nested_block['type'] == BlockType.TableBody:tables_body.append(bbox)- elif nested_block["type"] == BlockType.TableCaption:+ elif nested_block['type'] == BlockType.TableCaption:tables_caption.append(bbox)- elif nested_block["type"] == BlockType.TableFootnote:+ elif nested_block['type'] == BlockType.TableFootnote:tables_footnote.append(bbox)- elif block["type"] == BlockType.Image:+ elif block['type'] == BlockType.Image:imgs.append(bbox)- for nested_block in block["blocks"]:- bbox = nested_block["bbox"]- if nested_block["type"] == BlockType.ImageBody:+ for nested_block in block['blocks']:+ bbox = nested_block['bbox']+ if nested_block['type'] == BlockType.ImageBody:imgs_body.append(bbox)- elif nested_block["type"] == BlockType.ImageCaption:+ elif nested_block['type'] == BlockType.ImageCaption:imgs_caption.append(bbox)- elif block["type"] == BlockType.Title:+ elif nested_block['type'] == BlockType.ImageFootnote:+ imgs_footnote.append(bbox)+ elif block['type'] == BlockType.Title:titles.append(bbox)- elif block["type"] == BlockType.Text:+ elif block['type'] == BlockType.Text:texts.append(bbox)- elif block["type"] == BlockType.InterlineEquation:+ elif block['type'] == BlockType.InterlineEquation:interequations.append(bbox)tables_list.append(tables)tables_body_list.append(tables_body)@@ -120,30 +124,40 @@ def draw_layout_bbox(pdf_info, pdf_bytes, out_path):imgs_list.append(imgs)imgs_body_list.append(imgs_body)imgs_caption_list.append(imgs_caption)+ imgs_footnote_list.append(imgs_footnote)titles_list.append(titles)texts_list.append(texts)interequations_list.append(interequations)- pdf_docs = fitz.open("pdf", pdf_bytes)+ pdf_docs = fitz.open('pdf', pdf_bytes)for i, page in enumerate(pdf_docs):draw_bbox_with_number(i, layout_bbox_list, page, [255, 0, 0], False)- draw_bbox_without_number(i, dropped_bbox_list, page, [158, 158, 158], True)- draw_bbox_without_number(i, tables_list, page, [153, 153, 0], True) # color !- draw_bbox_without_number(i, tables_body_list, page, [204, 204, 0], True)- draw_bbox_without_number(i, tables_caption_list, page, [255, 255, 102], True)- draw_bbox_without_number(i, tables_footnote_list, page, [229, 255, 204], True)+ draw_bbox_without_number(i, dropped_bbox_list, page, [158, 158, 158],+ True)+ draw_bbox_without_number(i, tables_list, page, [153, 153, 0],+ True) # color !+ draw_bbox_without_number(i, tables_body_list, page, [204, 204, 0],+ True)+ draw_bbox_without_number(i, tables_caption_list, page, [255, 255, 102],+ True)+ draw_bbox_without_number(i, tables_footnote_list, page,+ [229, 255, 204], True)draw_bbox_without_number(i, imgs_list, page, [51, 102, 0], True)draw_bbox_without_number(i, imgs_body_list, page, [153, 255, 51], True)- draw_bbox_without_number(i, imgs_caption_list, page, [102, 178, 255], True)+ draw_bbox_without_number(i, imgs_caption_list, page, [102, 178, 255],+ True)+ draw_bbox_with_number(i, imgs_footnote_list, page, [255, 178, 102],+ True),draw_bbox_without_number(i, titles_list, page, [102, 102, 255], True)draw_bbox_without_number(i, texts_list, page, [153, 0, 76], True)- draw_bbox_without_number(i, interequations_list, page, [0, 255, 0], True)+ draw_bbox_without_number(i, interequations_list, page, [0, 255, 0],+ True)# Save the PDF- pdf_docs.save(f"{out_path}/layout.pdf")+ pdf_docs.save(f'{out_path}/{filename}_layout.pdf')-def draw_span_bbox(pdf_info, pdf_bytes, out_path):+def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):text_list = []inline_equation_list = []interline_equation_list = []@@ -154,22 +168,22 @@ def draw_span_bbox(pdf_info, pdf_bytes, out_path):next_page_inline_equation_list = []def get_span_info(span):- if span["type"] == ContentType.Text:+ if span['type'] == ContentType.Text:if span.get(CROSS_PAGE, False):- next_page_text_list.append(span["bbox"])+ next_page_text_list.append(span['bbox'])else:- page_text_list.append(span["bbox"])- elif span["type"] == ContentType.InlineEquation:+ page_text_list.append(span['bbox'])+ elif span['type'] == ContentType.InlineEquation:if span.get(CROSS_PAGE, False):- next_page_inline_equation_list.append(span["bbox"])+ next_page_inline_equation_list.append(span['bbox'])else:- page_inline_equation_list.append(span["bbox"])- elif span["type"] == ContentType.InterlineEquation:- page_interline_equation_list.append(span["bbox"])- elif span["type"] == ContentType.Image:- page_image_list.append(span["bbox"])- elif span["type"] == ContentType.Table:- page_table_list.append(span["bbox"])+ page_inline_equation_list.append(span['bbox'])+ elif span['type'] == ContentType.InterlineEquation:+ page_interline_equation_list.append(span['bbox'])+ elif span['type'] == ContentType.Image:+ page_image_list.append(span['bbox'])+ elif span['type'] == ContentType.Table:+ page_table_list.append(span['bbox'])for page in pdf_info:page_text_list = []@@ -188,84 +202,89 @@ def draw_span_bbox(pdf_info, pdf_bytes, out_path):next_page_inline_equation_list.clear()# 构造dropped_list- for block in page["discarded_blocks"]:- if block["type"] == BlockType.Discarded:- for line in block["lines"]:- for span in line["spans"]:- page_dropped_list.append(span["bbox"])+ for block in page['discarded_blocks']:+ if block['type'] == BlockType.Discarded:+ for line in block['lines']:+ for span in line['spans']:+ page_dropped_list.append(span['bbox'])dropped_list.append(page_dropped_list)# 构造其余useful_list- for block in page["para_blocks"]:- if block["type"] in [- BlockType.Text,- BlockType.Title,- BlockType.InterlineEquation,+ for block in page['para_blocks']:+ if block['type'] in [+ BlockType.Text,+ BlockType.Title,+ BlockType.InterlineEquation,]:- for line in block["lines"]:- for span in line["spans"]:+ for line in block['lines']:+ for span in line['spans']:get_span_info(span)- elif block["type"] in [BlockType.Image, BlockType.Table]:- for sub_block in block["blocks"]:- for line in sub_block["lines"]:- for span in line["spans"]:+ elif block['type'] in [BlockType.Image, BlockType.Table]:+ for sub_block in block['blocks']:+ for line in sub_block['lines']:+ for span in line['spans']:get_span_info(span)text_list.append(page_text_list)inline_equation_list.append(page_inline_equation_list)interline_equation_list.append(page_interline_equation_list)image_list.append(page_image_list)table_list.append(page_table_list)- pdf_docs = fitz.open("pdf", pdf_bytes)+ pdf_docs = fitz.open('pdf', pdf_bytes)for i, page in enumerate(pdf_docs):# 获取当前页面的数据draw_bbox_without_number(i, text_list, page, [255, 0, 0], False)- draw_bbox_without_number(i, inline_equation_list, page, [0, 255, 0], False)- draw_bbox_without_number(i, interline_equation_list, page, [0, 0, 255], False)+ draw_bbox_without_number(i, inline_equation_list, page, [0, 255, 0],+ False)+ draw_bbox_without_number(i, interline_equation_list, page, [0, 0, 255],+ False)draw_bbox_without_number(i, image_list, page, [255, 204, 0], False)draw_bbox_without_number(i, table_list, page, [204, 0, 255], False)draw_bbox_without_number(i, dropped_list, page, [158, 158, 158], False)# Save the PDF- pdf_docs.save(f"{out_path}/spans.pdf")+ pdf_docs.save(f'{out_path}/{filename}_spans.pdf')-def drow_model_bbox(model_list: list, pdf_bytes, out_path):+def drow_model_bbox(model_list: list, pdf_bytes, out_path, filename):dropped_bbox_list = []tables_body_list, tables_caption_list, tables_footnote_list = [], [], []- imgs_body_list, imgs_caption_list = [], []+ imgs_body_list, imgs_caption_list, imgs_footnote_list = [], [], []titles_list = []texts_list = []interequations_list = []- pdf_docs = fitz.open("pdf", pdf_bytes)+ pdf_docs = fitz.open('pdf', pdf_bytes)magic_model = MagicModel(model_list, pdf_docs)for i in range(len(model_list)):page_dropped_list = []tables_body, tables_caption, tables_footnote = [], [], []- imgs_body, imgs_caption = [], []+ imgs_body, imgs_caption, imgs_footnote = [], [], []titles = []texts = []interequations = []page_info = magic_model.get_model_list(i)- layout_dets = page_info["layout_dets"]+ layout_dets = page_info['layout_dets']for layout_det in layout_dets:- bbox = layout_det["bbox"]- if layout_det["category_id"] == CategoryId.Text:+ bbox = layout_det['bbox']+ if layout_det['category_id'] == CategoryId.Text:texts.append(bbox)- elif layout_det["category_id"] == CategoryId.Title:+ elif layout_det['category_id'] == CategoryId.Title:titles.append(bbox)- elif layout_det["category_id"] == CategoryId.TableBody:+ elif layout_det['category_id'] == CategoryId.TableBody:tables_body.append(bbox)- elif layout_det["category_id"] == CategoryId.TableCaption:+ elif layout_det['category_id'] == CategoryId.TableCaption:tables_caption.append(bbox)- elif layout_det["category_id"] == CategoryId.TableFootnote:+ elif layout_det['category_id'] == CategoryId.TableFootnote:tables_footnote.append(bbox)- elif layout_det["category_id"] == CategoryId.ImageBody:+ elif layout_det['category_id'] == CategoryId.ImageBody:imgs_body.append(bbox)- elif layout_det["category_id"] == CategoryId.ImageCaption:+ elif layout_det['category_id'] == CategoryId.ImageCaption:imgs_caption.append(bbox)- elif layout_det["category_id"] == CategoryId.InterlineEquation_YOLO:+ elif layout_det[+ 'category_id'] == CategoryId.InterlineEquation_YOLO:interequations.append(bbox)- elif layout_det["category_id"] == CategoryId.Abandon:+ elif layout_det['category_id'] == CategoryId.Abandon:page_dropped_list.append(bbox)+ elif layout_det['category_id'] == CategoryId.ImageFootnote:+ imgs_footnote.append(bbox)tables_body_list.append(tables_body)tables_caption_list.append(tables_caption)@@ -276,17 +295,24 @@ def drow_model_bbox(model_list: list, pdf_bytes, out_path):texts_list.append(texts)interequations_list.append(interequations)dropped_bbox_list.append(page_dropped_list)+ imgs_footnote_list.append(imgs_footnote)for i, page in enumerate(pdf_docs):- draw_bbox_with_number(i, dropped_bbox_list, page, [158, 158, 158], True) # color !+ draw_bbox_with_number(i, dropped_bbox_list, page, [158, 158, 158],+ True) # color !draw_bbox_with_number(i, tables_body_list, page, [204, 204, 0], True)- draw_bbox_with_number(i, tables_caption_list, page, [255, 255, 102], True)- draw_bbox_with_number(i, tables_footnote_list, page, [229, 255, 204], True)+ draw_bbox_with_number(i, tables_caption_list, page, [255, 255, 102],+ True)+ draw_bbox_with_number(i, tables_footnote_list, page, [229, 255, 204],+ True)draw_bbox_with_number(i, imgs_body_list, page, [153, 255, 51], True)- draw_bbox_with_number(i, imgs_caption_list, page, [102, 178, 255], True)+ draw_bbox_with_number(i, imgs_caption_list, page, [102, 178, 255],+ True)+ draw_bbox_with_number(i, imgs_footnote_list, page, [255, 178, 102],+ True)draw_bbox_with_number(i, titles_list, page, [102, 102, 255], True)draw_bbox_with_number(i, texts_list, page, [153, 0, 76], True)draw_bbox_with_number(i, interequations_list, page, [0, 255, 0], True)# Save the PDF- pdf_docs.save(f"{out_path}/model.pdf")\ No newline at end of file+ pdf_docs.save(f'{out_path}/{filename}_model.pdf')diff --git a/magic_pdf/libs/ocr_content_type.py b/magic_pdf/libs/ocr_content_type.pyindex bb7e7752..749c16f9 100644--- a/magic_pdf/libs/ocr_content_type.py+++ b/magic_pdf/libs/ocr_content_type.py@@ -1,23 +1,25 @@class ContentType:- Image = "image"- Table = "table"- Text = "text"- InlineEquation = "inline_equation"- InterlineEquation = "interline_equation"-+ Image = 'image'+ Table = 'table'+ Text = 'text'+ InlineEquation = 'inline_equation'+ InterlineEquation = 'interline_equation'++class BlockType:- Image = "image"- ImageBody = "image_body"- ImageCaption = "image_caption"- Table = "table"- TableBody = "table_body"- TableCaption = "table_caption"- TableFootnote = "table_footnote"- Text = "text"- Title = "title"- InterlineEquation = "interline_equation"- Footnote = "footnote"- Discarded = "discarded"+ Image = 'image'+ ImageBody = 'image_body'+ ImageCaption = 'image_caption'+ ImageFootnote = 'image_footnote'+ Table = 'table'+ TableBody = 'table_body'+ TableCaption = 'table_caption'+ TableFootnote = 'table_footnote'+ Text = 'text'+ Title = 'title'+ InterlineEquation = 'interline_equation'+ Footnote = 'footnote'+ Discarded = 'discarded'class CategoryId:@@ -33,3 +35,4 @@ class CategoryId:InlineEquation = 13InterlineEquation_YOLO = 14OcrText = 15+ ImageFootnote = 101diff --git a/magic_pdf/model/doc_analyze_by_custom_model.py b/magic_pdf/model/doc_analyze_by_custom_model.pyindex 209b07b7..48539275 100644--- a/magic_pdf/model/doc_analyze_by_custom_model.py+++ b/magic_pdf/model/doc_analyze_by_custom_model.py@@ -103,20 +103,32 @@ def custom_model_init(ocr: bool = False, show_log: bool = False):return custom_model-def doc_analyze(pdf_bytes: bytes, ocr: bool = False, show_log: bool = False):+def doc_analyze(pdf_bytes: bytes, ocr: bool = False, show_log: bool = False,+ start_page_id=0, end_page_id=None):model_manager = ModelSingleton()custom_model = model_manager.get_model(ocr, show_log)images = load_images_from_pdf(pdf_bytes)+ # end_page_id = end_page_id if end_page_id else len(images) - 1+ end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else len(images) - 1++ if end_page_id > len(images) - 1:+ logger.warning("end_page_id is out of range, use images length")+ end_page_id = len(images) - 1+model_json = []doc_analyze_start = time.time()+for index, img_dict in enumerate(images):img = img_dict["img"]page_width = img_dict["width"]page_height = img_dict["height"]- result = custom_model(img)+ if start_page_id <= index <= end_page_id:+ result = custom_model(img)+ else:+ result = []page_info = {"page_no": index, "height": page_height, "width": page_width}page_dict = {"layout_dets": result, "page_info": page_info}model_json.append(page_dict)diff --git a/magic_pdf/model/magic_model.py b/magic_pdf/model/magic_model.pyindex ce070321..61dc3a43 100644--- a/magic_pdf/model/magic_model.py+++ b/magic_pdf/model/magic_model.py@@ -1,50 +1,38 @@import json-import math-from magic_pdf.libs.commons import fitz-from loguru import logger--from magic_pdf.libs.commons import join_path+from magic_pdf.libs.boxbase import (_is_in, _is_part_overlap, bbox_distance,+ bbox_relative_pos, calculate_iou,+ calculate_overlap_area_in_bbox1_area_ratio)+from magic_pdf.libs.commons import fitz, join_pathfrom magic_pdf.libs.coordinate_transform import get_scale_ratio-from magic_pdf.libs.ocr_content_type import ContentType-from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter-from magic_pdf.rw.DiskReaderWriter import DiskReaderWriterfrom magic_pdf.libs.local_math import float_gt-from magic_pdf.libs.boxbase import (- _is_in,- bbox_relative_pos,- bbox_distance,- _is_part_overlap,- calculate_overlap_area_in_bbox1_area_ratio,- calculate_iou,-)from magic_pdf.libs.ModelBlockTypeEnum import ModelBlockTypeEnum+from magic_pdf.libs.ocr_content_type import CategoryId, ContentType+from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter+from magic_pdf.rw.DiskReaderWriter import DiskReaderWriterCAPATION_OVERLAP_AREA_RATIO = 0.6class MagicModel:- """- 每个函数没有得到元素的时候返回空list-- """+ """每个函数没有得到元素的时候返回空list."""def __fix_axis(self):for model_page_info in self.__model_list:need_remove_list = []- page_no = model_page_info["page_info"]["page_no"]+ page_no = model_page_info['page_info']['page_no']horizontal_scale_ratio, vertical_scale_ratio = get_scale_ratio(model_page_info, self.__docs[page_no])- layout_dets = model_page_info["layout_dets"]+ layout_dets = model_page_info['layout_dets']for layout_det in layout_dets:- if layout_det.get("bbox") is not None:+ if layout_det.get('bbox') is not None:# 兼容直接输出bbox的模型数据,如paddle- x0, y0, x1, y1 = layout_det["bbox"]+ x0, y0, x1, y1 = layout_det['bbox']else:# 兼容直接输出poly的模型数据,如xxx- x0, y0, _, _, x1, y1, _, _ = layout_det["poly"]+ x0, y0, _, _, x1, y1, _, _ = layout_det['poly']bbox = [int(x0 / horizontal_scale_ratio),@@ -52,7 +40,7 @@ class MagicModel:int(x1 / horizontal_scale_ratio),int(y1 / vertical_scale_ratio),]- layout_det["bbox"] = bbox+ layout_det['bbox'] = bbox# 删除高度或者宽度小于等于0的spansif bbox[2] - bbox[0] <= 0 or bbox[3] - bbox[1] <= 0:need_remove_list.append(layout_det)@@ -62,9 +50,9 @@ class MagicModel:def __fix_by_remove_low_confidence(self):for model_page_info in self.__model_list:need_remove_list = []- layout_dets = model_page_info["layout_dets"]+ layout_dets = model_page_info['layout_dets']for layout_det in layout_dets:- if layout_det["score"] <= 0.05:+ if layout_det['score'] <= 0.05:need_remove_list.append(layout_det)else:continue@@ -74,12 +62,12 @@ class MagicModel:def __fix_by_remove_high_iou_and_low_confidence(self):for model_page_info in self.__model_list:need_remove_list = []- layout_dets = model_page_info["layout_dets"]+ layout_dets = model_page_info['layout_dets']for layout_det1 in layout_dets:for layout_det2 in layout_dets:if layout_det1 == layout_det2:continue- if layout_det1["category_id"] in [+ if layout_det1['category_id'] in [0,1,2,@@ -90,12 +78,12 @@ class MagicModel:7,8,9,- ] and layout_det2["category_id"] in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:+ ] and layout_det2['category_id'] in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:if (- calculate_iou(layout_det1["bbox"], layout_det2["bbox"])+ calculate_iou(layout_det1['bbox'], layout_det2['bbox'])> 0.9):- if layout_det1["score"] < layout_det2["score"]:+ if layout_det1['score'] < layout_det2['score']:layout_det_need_remove = layout_det1else:layout_det_need_remove = layout_det2@@ -118,6 +106,67 @@ class MagicModel:self.__fix_by_remove_low_confidence()"""删除高iou(>0.9)数据中置信度较低的那个"""self.__fix_by_remove_high_iou_and_low_confidence()+ self.__fix_footnote()++ def __fix_footnote(self):+ # 3: figure, 5: table, 7: footnote+ for model_page_info in self.__model_list:+ footnotes = []+ figures = []+ tables = []++ for obj in model_page_info['layout_dets']:+ if obj['category_id'] == 7:+ footnotes.append(obj)+ elif obj['category_id'] == 3:+ figures.append(obj)+ elif obj['category_id'] == 5:+ tables.append(obj)+ if len(footnotes) * len(figures) == 0:+ continue+ dis_figure_footnote = {}+ dis_table_footnote = {}++ for i in range(len(footnotes)):+ for j in range(len(figures)):+ pos_flag_count = sum(+ list(+ map(+ lambda x: 1 if x else 0,+ bbox_relative_pos(+ footnotes[i]['bbox'], figures[j]['bbox']+ ),+ )+ )+ )+ if pos_flag_count > 1:+ continue+ dis_figure_footnote[i] = min(+ bbox_distance(figures[j]['bbox'], footnotes[i]['bbox']),+ dis_figure_footnote.get(i, float('inf')),+ )+ for i in range(len(footnotes)):+ for j in range(len(tables)):+ pos_flag_count = sum(+ list(+ map(+ lambda x: 1 if x else 0,+ bbox_relative_pos(+ footnotes[i]['bbox'], tables[j]['bbox']+ ),+ )+ )+ )+ if pos_flag_count > 1:+ continue++ dis_table_footnote[i] = min(+ bbox_distance(tables[j]['bbox'], footnotes[i]['bbox']),+ dis_table_footnote.get(i, float('inf')),+ )+ for i in range(len(footnotes)):+ if dis_table_footnote.get(i, float('inf')) > dis_figure_footnote[i]:+ footnotes[i]['category_id'] = CategoryId.ImageFootnotedef __reduct_overlap(self, bboxes):N = len(bboxes)@@ -126,76 +175,77 @@ class MagicModel:for j in range(N):if i == j:continue- if _is_in(bboxes[i]["bbox"], bboxes[j]["bbox"]):+ if _is_in(bboxes[i]['bbox'], bboxes[j]['bbox']):keep[i] = False-return [bboxes[i] for i in range(N) if keep[i]]def __tie_up_category_by_distance(self, page_no, subject_category_id, object_category_id):- """- 假定每个 subject 最多有一个 object (可以有多个相邻的 object 合并为单个 object),每个 object 只能属于一个 subject- """+ """假定每个 subject 最多有一个 object (可以有多个相邻的 object 合并为单个 object),每个 object+ 只能属于一个 subject."""ret = []MAX_DIS_OF_POINT = 10**9 + 7+ """+ subject 和 object 的 bbox 会合并成一个大的 bbox (named: merged bbox)。+ 筛选出所有和 merged bbox 有 overlap 且 overlap 面积大于 object 的面积的 subjects。+ 再求出筛选出的 subjects 和 object 的最短距离+ """- # subject 和 object 的 bbox 会合并成一个大的 bbox (named: merged bbox)。 筛选出所有和 merged bbox 有 overlap 且 overlap 面积大于 object 的面积的 subjects。- # 再求出筛选出的 subjects 和 object 的最短距离!def may_find_other_nearest_bbox(subject_idx, object_idx):- ret = float("inf")+ ret = float('inf')x0 = min(- all_bboxes[subject_idx]["bbox"][0], all_bboxes[object_idx]["bbox"][0]+ all_bboxes[subject_idx]['bbox'][0], all_bboxes[object_idx]['bbox'][0])y0 = min(- all_bboxes[subject_idx]["bbox"][1], all_bboxes[object_idx]["bbox"][1]+ all_bboxes[subject_idx]['bbox'][1], all_bboxes[object_idx]['bbox'][1])x1 = max(- all_bboxes[subject_idx]["bbox"][2], all_bboxes[object_idx]["bbox"][2]+ all_bboxes[subject_idx]['bbox'][2], all_bboxes[object_idx]['bbox'][2])y1 = max(- all_bboxes[subject_idx]["bbox"][3], all_bboxes[object_idx]["bbox"][3]+ all_bboxes[subject_idx]['bbox'][3], all_bboxes[object_idx]['bbox'][3])object_area = abs(- all_bboxes[object_idx]["bbox"][2] - all_bboxes[object_idx]["bbox"][0]+ all_bboxes[object_idx]['bbox'][2] - all_bboxes[object_idx]['bbox'][0]) * abs(- all_bboxes[object_idx]["bbox"][3] - all_bboxes[object_idx]["bbox"][1]+ all_bboxes[object_idx]['bbox'][3] - all_bboxes[object_idx]['bbox'][1])for i in range(len(all_bboxes)):if (i == subject_idx- or all_bboxes[i]["category_id"] != subject_category_id+ or all_bboxes[i]['category_id'] != subject_category_id):continue- if _is_part_overlap([x0, y0, x1, y1], all_bboxes[i]["bbox"]) or _is_in(- all_bboxes[i]["bbox"], [x0, y0, x1, y1]+ if _is_part_overlap([x0, y0, x1, y1], all_bboxes[i]['bbox']) or _is_in(+ all_bboxes[i]['bbox'], [x0, y0, x1, y1]):i_area = abs(- all_bboxes[i]["bbox"][2] - all_bboxes[i]["bbox"][0]- ) * abs(all_bboxes[i]["bbox"][3] - all_bboxes[i]["bbox"][1])+ all_bboxes[i]['bbox'][2] - all_bboxes[i]['bbox'][0]+ ) * abs(all_bboxes[i]['bbox'][3] - all_bboxes[i]['bbox'][1])if i_area >= object_area:- ret = min(float("inf"), dis[i][object_idx])+ ret = min(float('inf'), dis[i][object_idx])return retdef expand_bbbox(idxes):- x0s = [all_bboxes[idx]["bbox"][0] for idx in idxes]- y0s = [all_bboxes[idx]["bbox"][1] for idx in idxes]- x1s = [all_bboxes[idx]["bbox"][2] for idx in idxes]- y1s = [all_bboxes[idx]["bbox"][3] for idx in idxes]+ x0s = [all_bboxes[idx]['bbox'][0] for idx in idxes]+ y0s = [all_bboxes[idx]['bbox'][1] for idx in idxes]+ x1s = [all_bboxes[idx]['bbox'][2] for idx in idxes]+ y1s = [all_bboxes[idx]['bbox'][3] for idx in idxes]return min(x0s), min(y0s), max(x1s), max(y1s)subjects = self.__reduct_overlap(list(map(- lambda x: {"bbox": x["bbox"], "score": x["score"]},+ lambda x: {'bbox': x['bbox'], 'score': x['score']},filter(- lambda x: x["category_id"] == subject_category_id,- self.__model_list[page_no]["layout_dets"],+ lambda x: x['category_id'] == subject_category_id,+ self.__model_list[page_no]['layout_dets'],),))@@ -204,10 +254,10 @@ class MagicModel:objects = self.__reduct_overlap(list(map(- lambda x: {"bbox": x["bbox"], "score": x["score"]},+ lambda x: {'bbox': x['bbox'], 'score': x['score']},filter(- lambda x: x["category_id"] == object_category_id,- self.__model_list[page_no]["layout_dets"],+ lambda x: x['category_id'] == object_category_id,+ self.__model_list[page_no]['layout_dets'],),))@@ -215,7 +265,7 @@ class MagicModel:subject_object_relation_map = {}subjects.sort(- key=lambda x: x["bbox"][0] ** 2 + x["bbox"][1] ** 2+ key=lambda x: x['bbox'][0] ** 2 + x['bbox'][1] ** 2) # get the distance !all_bboxes = []@@ -223,18 +273,18 @@ class MagicModel:for v in subjects:all_bboxes.append({- "category_id": subject_category_id,- "bbox": v["bbox"],- "score": v["score"],+ 'category_id': subject_category_id,+ 'bbox': v['bbox'],+ 'score': v['score'],})for v in objects:all_bboxes.append({- "category_id": object_category_id,- "bbox": v["bbox"],- "score": v["score"],+ 'category_id': object_category_id,+ 'bbox': v['bbox'],+ 'score': v['score'],})@@ -244,18 +294,18 @@ class MagicModel:for i in range(N):for j in range(i):if (- all_bboxes[i]["category_id"] == subject_category_id- and all_bboxes[j]["category_id"] == subject_category_id+ all_bboxes[i]['category_id'] == subject_category_id+ and all_bboxes[j]['category_id'] == subject_category_id):continue- dis[i][j] = bbox_distance(all_bboxes[i]["bbox"], all_bboxes[j]["bbox"])+ dis[i][j] = bbox_distance(all_bboxes[i]['bbox'], all_bboxes[j]['bbox'])dis[j][i] = dis[i][j]used = set()for i in range(N):# 求第 i 个 subject 所关联的 object- if all_bboxes[i]["category_id"] != subject_category_id:+ if all_bboxes[i]['category_id'] != subject_category_id:continueseen = set()candidates = []@@ -267,7 +317,7 @@ class MagicModel:map(lambda x: 1 if x else 0,bbox_relative_pos(- all_bboxes[i]["bbox"], all_bboxes[j]["bbox"]+ all_bboxes[i]['bbox'], all_bboxes[j]['bbox']),))@@ -275,25 +325,28 @@ class MagicModel:if pos_flag_count > 1:continueif (- all_bboxes[j]["category_id"] != object_category_id+ all_bboxes[j]['category_id'] != object_category_idor j in usedor dis[i][j] == MAX_DIS_OF_POINT):continueleft, right, _, _ = bbox_relative_pos(- all_bboxes[i]["bbox"], all_bboxes[j]["bbox"]+ all_bboxes[i]['bbox'], all_bboxes[j]['bbox']) # 由 pos_flag_count 相关逻辑保证本段逻辑准确性if left or right:- one_way_dis = all_bboxes[i]["bbox"][2] - all_bboxes[i]["bbox"][0]+ one_way_dis = all_bboxes[i]['bbox'][2] - all_bboxes[i]['bbox'][0]else:- one_way_dis = all_bboxes[i]["bbox"][3] - all_bboxes[i]["bbox"][1]+ one_way_dis = all_bboxes[i]['bbox'][3] - all_bboxes[i]['bbox'][1]if dis[i][j] > one_way_dis:continuearr.append((dis[i][j], j))arr.sort(key=lambda x: x[0])if len(arr) > 0:- # bug: 离该subject 最近的 object 可能跨越了其它的 subject 。比如 [this subect] [some sbuject] [the nearest objec of subject]+ """+ bug: 离该subject 最近的 object 可能跨越了其它的 subject。+ 比如 [this subect] [some sbuject] [the nearest object of subject]+ """if may_find_other_nearest_bbox(i, arr[0][1]) >= arr[0][0]:candidates.append(arr[0][1])@@ -308,7 +361,7 @@ class MagicModel:map(lambda x: 1 if x else 0,bbox_relative_pos(- all_bboxes[j]["bbox"], all_bboxes[k]["bbox"]+ all_bboxes[j]['bbox'], all_bboxes[k]['bbox']),))@@ -318,7 +371,7 @@ class MagicModel:continueif (- all_bboxes[k]["category_id"] != object_category_id+ all_bboxes[k]['category_id'] != object_category_idor k in usedor k in seenor dis[j][k] == MAX_DIS_OF_POINT@@ -327,17 +380,19 @@ class MagicModel:continueis_nearest = True- for l in range(i + 1, N):- if l in (j, k) or l in used or l in seen:+ for ni in range(i + 1, N):+ if ni in (j, k) or ni in used or ni in seen:continue- if not float_gt(dis[l][k], dis[j][k]):+ if not float_gt(dis[ni][k], dis[j][k]):is_nearest = Falsebreakif is_nearest:nx0, ny0, nx1, ny1 = expand_bbbox(list(seen) + [k])- n_dis = bbox_distance(all_bboxes[i]["bbox"], [nx0, ny0, nx1, ny1])+ n_dis = bbox_distance(+ all_bboxes[i]['bbox'], [nx0, ny0, nx1, ny1]+ )if float_gt(dis[i][j], n_dis):continuetmp.append(k)@@ -350,7 +405,7 @@ class MagicModel:# 已经获取到某个 figure 下所有的最靠近的 captions,以及最靠近这些 captions 的 captions 。# 先扩一下 bbox,ox0, oy0, ox1, oy1 = expand_bbbox(list(seen) + [i])- ix0, iy0, ix1, iy1 = all_bboxes[i]["bbox"]+ ix0, iy0, ix1, iy1 = all_bboxes[i]['bbox']# 分成了 4 个截取空间,需要计算落在每个截取空间下 objects 合并后占据的矩形面积caption_poses = [@@ -366,17 +421,17 @@ class MagicModel:for idx in seen:if (calculate_overlap_area_in_bbox1_area_ratio(- all_bboxes[idx]["bbox"], bbox+ all_bboxes[idx]['bbox'], bbox)> CAPATION_OVERLAP_AREA_RATIO):embed_arr.append(idx)if len(embed_arr) > 0:- embed_x0 = min([all_bboxes[idx]["bbox"][0] for idx in embed_arr])- embed_y0 = min([all_bboxes[idx]["bbox"][1] for idx in embed_arr])- embed_x1 = max([all_bboxes[idx]["bbox"][2] for idx in embed_arr])- embed_y1 = max([all_bboxes[idx]["bbox"][3] for idx in embed_arr])+ embed_x0 = min([all_bboxes[idx]['bbox'][0] for idx in embed_arr])+ embed_y0 = min([all_bboxes[idx]['bbox'][1] for idx in embed_arr])+ embed_x1 = max([all_bboxes[idx]['bbox'][2] for idx in embed_arr])+ embed_y1 = max([all_bboxes[idx]['bbox'][3] for idx in embed_arr])caption_areas.append(int(abs(embed_x1 - embed_x0) * abs(embed_y1 - embed_y0)))@@ -391,7 +446,7 @@ class MagicModel:for j in seen:if (calculate_overlap_area_in_bbox1_area_ratio(- all_bboxes[j]["bbox"], caption_bbox+ all_bboxes[j]['bbox'], caption_bbox)> CAPATION_OVERLAP_AREA_RATIO):@@ -400,30 +455,30 @@ class MagicModel:for i in sorted(subject_object_relation_map.keys()):result = {- "subject_body": all_bboxes[i]["bbox"],- "all": all_bboxes[i]["bbox"],- "score": all_bboxes[i]["score"],+ 'subject_body': all_bboxes[i]['bbox'],+ 'all': all_bboxes[i]['bbox'],+ 'score': all_bboxes[i]['score'],}if len(subject_object_relation_map[i]) > 0:x0 = min(- [all_bboxes[j]["bbox"][0] for j in subject_object_relation_map[i]]+ [all_bboxes[j]['bbox'][0] for j in subject_object_relation_map[i]])y0 = min(- [all_bboxes[j]["bbox"][1] for j in subject_object_relation_map[i]]+ [all_bboxes[j]['bbox'][1] for j in subject_object_relation_map[i]])x1 = max(- [all_bboxes[j]["bbox"][2] for j in subject_object_relation_map[i]]+ [all_bboxes[j]['bbox'][2] for j in subject_object_relation_map[i]])y1 = max(- [all_bboxes[j]["bbox"][3] for j in subject_object_relation_map[i]]+ [all_bboxes[j]['bbox'][3] for j in subject_object_relation_map[i]])- result["object_body"] = [x0, y0, x1, y1]- result["all"] = [- min(x0, all_bboxes[i]["bbox"][0]),- min(y0, all_bboxes[i]["bbox"][1]),- max(x1, all_bboxes[i]["bbox"][2]),- max(y1, all_bboxes[i]["bbox"][3]),+ result['object_body'] = [x0, y0, x1, y1]+ result['all'] = [+ min(x0, all_bboxes[i]['bbox'][0]),+ min(y0, all_bboxes[i]['bbox'][1]),+ max(x1, all_bboxes[i]['bbox'][2]),+ max(y1, all_bboxes[i]['bbox'][3]),]ret.append(result)@@ -432,7 +487,7 @@ class MagicModel:for i in subject_object_relation_map.keys():for j in subject_object_relation_map[i]:total_subject_object_dis += bbox_distance(- all_bboxes[i]["bbox"], all_bboxes[j]["bbox"]+ all_bboxes[i]['bbox'], all_bboxes[j]['bbox'])# 计算未匹配的 subject 和 object 的距离(非精确版)@@ -444,12 +499,12 @@ class MagicModel:])for i in range(N):- if all_bboxes[i]["category_id"] != object_category_id or i in used:+ if all_bboxes[i]['category_id'] != object_category_id or i in used:continuecandidates = []for j in range(N):if (- all_bboxes[j]["category_id"] != subject_category_id+ all_bboxes[j]['category_id'] != subject_category_idor j in with_caption_subject):continue@@ -461,18 +516,28 @@ class MagicModel:return ret, total_subject_object_disdef get_imgs(self, page_no: int):- figure_captions, _ = self.__tie_up_category_by_distance(- page_no, 3, 4+ with_captions, _ = self.__tie_up_category_by_distance(page_no, 3, 4)+ with_footnotes, _ = self.__tie_up_category_by_distance(+ page_no, 3, CategoryId.ImageFootnote)- return [- {- "bbox": record["all"],- "img_body_bbox": record["subject_body"],- "img_caption_bbox": record.get("object_body", None),- "score": record["score"],+ ret = []+ N, M = len(with_captions), len(with_footnotes)+ assert N == M+ for i in range(N):+ record = {+ 'score': with_captions[i]['score'],+ 'img_caption_bbox': with_captions[i].get('object_body', None),+ 'img_body_bbox': with_captions[i]['subject_body'],+ 'img_footnote_bbox': with_footnotes[i].get('object_body', None),}- for record in figure_captions- ]++ x0 = min(with_captions[i]['all'][0], with_footnotes[i]['all'][0])+ y0 = min(with_captions[i]['all'][1], with_footnotes[i]['all'][1])+ x1 = max(with_captions[i]['all'][2], with_footnotes[i]['all'][2])+ y1 = max(with_captions[i]['all'][3], with_footnotes[i]['all'][3])+ record['bbox'] = [x0, y0, x1, y1]+ ret.append(record)+ return retdef get_tables(self, page_no: int@@ -484,26 +549,26 @@ class MagicModel:assert N == Mfor i in range(N):record = {- "score": with_captions[i]["score"],- "table_caption_bbox": with_captions[i].get("object_body", None),- "table_body_bbox": with_captions[i]["subject_body"],- "table_footnote_bbox": with_footnotes[i].get("object_body", None),+ 'score': with_captions[i]['score'],+ 'table_caption_bbox': with_captions[i].get('object_body', None),+ 'table_body_bbox': with_captions[i]['subject_body'],+ 'table_footnote_bbox': with_footnotes[i].get('object_body', None),}- x0 = min(with_captions[i]["all"][0], with_footnotes[i]["all"][0])- y0 = min(with_captions[i]["all"][1], with_footnotes[i]["all"][1])- x1 = max(with_captions[i]["all"][2], with_footnotes[i]["all"][2])- y1 = max(with_captions[i]["all"][3], with_footnotes[i]["all"][3])- record["bbox"] = [x0, y0, x1, y1]+ x0 = min(with_captions[i]['all'][0], with_footnotes[i]['all'][0])+ y0 = min(with_captions[i]['all'][1], with_footnotes[i]['all'][1])+ x1 = max(with_captions[i]['all'][2], with_footnotes[i]['all'][2])+ y1 = max(with_captions[i]['all'][3], with_footnotes[i]['all'][3])+ record['bbox'] = [x0, y0, x1, y1]ret.append(record)return retdef get_equations(self, page_no: int) -> list: # 有坐标,也有字inline_equations = self.__get_blocks_by_type(- ModelBlockTypeEnum.EMBEDDING.value, page_no, ["latex"]+ ModelBlockTypeEnum.EMBEDDING.value, page_no, ['latex'])interline_equations = self.__get_blocks_by_type(- ModelBlockTypeEnum.ISOLATED.value, page_no, ["latex"]+ ModelBlockTypeEnum.ISOLATED.value, page_no, ['latex'])interline_equations_blocks = self.__get_blocks_by_type(ModelBlockTypeEnum.ISOLATE_FORMULA.value, page_no@@ -525,17 +590,18 @@ class MagicModel:def get_ocr_text(self, page_no: int) -> list: # paddle 搞的,有字也有坐标text_spans = []model_page_info = self.__model_list[page_no]- layout_dets = model_page_info["layout_dets"]+ layout_dets = model_page_info['layout_dets']for layout_det in layout_dets:- if layout_det["category_id"] == "15":+ if layout_det['category_id'] == '15':span = {- "bbox": layout_det["bbox"],- "content": layout_det["text"],+ 'bbox': layout_det['bbox'],+ 'content': layout_det['text'],}text_spans.append(span)return text_spansdef get_all_spans(self, page_no: int) -> list:+def remove_duplicate_spans(spans):new_spans = []for span in spans:@@ -545,7 +611,7 @@ class MagicModel:all_spans = []model_page_info = self.__model_list[page_no]- layout_dets = model_page_info["layout_dets"]+ layout_dets = model_page_info['layout_dets']allow_category_id_list = [3, 5, 13, 14, 15]"""当成span拼接的"""# 3: 'image', # 图片@@ -554,11 +620,11 @@ class MagicModel:# 14: 'interline_equation', # 行间公式# 15: 'text', # ocr识别文本for layout_det in layout_dets:- category_id = layout_det["category_id"]+ category_id = layout_det['category_id']if category_id in allow_category_id_list:- span = {"bbox": layout_det["bbox"], "score": layout_det["score"]}+ span = {'bbox': layout_det['bbox'], 'score': layout_det['score']}if category_id == 3:- span["type"] = ContentType.Image+ span['type'] = ContentType.Imageelif category_id == 5:# 获取table模型结果latex = layout_det.get("latex", None)@@ -569,14 +635,14 @@ class MagicModel:span["html"] = htmlspan["type"] = ContentType.Tableelif category_id == 13:- span["content"] = layout_det["latex"]- span["type"] = ContentType.InlineEquation+ span['content'] = layout_det['latex']+ span['type'] = ContentType.InlineEquationelif category_id == 14:- span["content"] = layout_det["latex"]- span["type"] = ContentType.InterlineEquation+ span['content'] = layout_det['latex']+ span['type'] = ContentType.InterlineEquationelif category_id == 15:- span["content"] = layout_det["text"]- span["type"] = ContentType.Text+ span['content'] = layout_det['text']+ span['type'] = ContentType.Textall_spans.append(span)return remove_duplicate_spans(all_spans)@@ -593,19 +659,19 @@ class MagicModel:) -> list:blocks = []for page_dict in self.__model_list:- layout_dets = page_dict.get("layout_dets", [])- page_info = page_dict.get("page_info", {})- page_number = page_info.get("page_no", -1)+ layout_dets = page_dict.get('layout_dets', [])+ page_info = page_dict.get('page_info', {})+ page_number = page_info.get('page_no', -1)if page_no != page_number:continuefor item in layout_dets:- category_id = item.get("category_id", -1)- bbox = item.get("bbox", None)+ category_id = item.get('category_id', -1)+ bbox = item.get('bbox', None)if category_id == type:block = {- "bbox": bbox,- "score": item.get("score"),+ 'bbox': bbox,+ 'score': item.get('score'),}for col in extra_col:block[col] = item.get(col, None)@@ -616,28 +682,28 @@ class MagicModel:return self.__model_list[page_no]-if __name__ == "__main__":- drw = DiskReaderWriter(r"D:/project/20231108code-clean")+if __name__ == '__main__':+ drw = DiskReaderWriter(r'D:/project/20231108code-clean')if 0:- pdf_file_path = r"linshixuqiu\19983-00.pdf"- model_file_path = r"linshixuqiu\19983-00_new.json"+ pdf_file_path = r'linshixuqiu\19983-00.pdf'+ model_file_path = r'linshixuqiu\19983-00_new.json'pdf_bytes = drw.read(pdf_file_path, AbsReaderWriter.MODE_BIN)model_json_txt = drw.read(model_file_path, AbsReaderWriter.MODE_TXT)model_list = json.loads(model_json_txt)- write_path = r"D:\project\20231108code-clean\linshixuqiu\19983-00"- img_bucket_path = "imgs"+ write_path = r'D:\project\20231108code-clean\linshixuqiu\19983-00'+ img_bucket_path = 'imgs'img_writer = DiskReaderWriter(join_path(write_path, img_bucket_path))- pdf_docs = fitz.open("pdf", pdf_bytes)+ pdf_docs = fitz.open('pdf', pdf_bytes)magic_model = MagicModel(model_list, pdf_docs)if 1:model_list = json.loads(- drw.read("/opt/data/pdf/20240418/j.chroma.2009.03.042.json")+ drw.read('/opt/data/pdf/20240418/j.chroma.2009.03.042.json'))pdf_bytes = drw.read(- "/opt/data/pdf/20240418/j.chroma.2009.03.042.pdf", AbsReaderWriter.MODE_BIN+ '/opt/data/pdf/20240418/j.chroma.2009.03.042.pdf', AbsReaderWriter.MODE_BIN)- pdf_docs = fitz.open("pdf", pdf_bytes)+ pdf_docs = fitz.open('pdf', pdf_bytes)magic_model = MagicModel(model_list, pdf_docs)for i in range(7):print(magic_model.get_imgs(i))diff --git a/magic_pdf/model/model_list.py b/magic_pdf/model/model_list.pyindex 1b4c589b..c4bcf021 100644--- a/magic_pdf/model/model_list.py+++ b/magic_pdf/model/model_list.py@@ -1,3 +1,11 @@class MODEL:Paddle = "pp_structure_v2"PEK = "pdf_extract_kit"+++class AtomicModel:+ Layout = "layout"+ MFD = "mfd"+ MFR = "mfr"+ OCR = "ocr"+ Table = "table"diff --git a/magic_pdf/model/pdf_extract_kit.py b/magic_pdf/model/pdf_extract_kit.pyindex f36d3545..8abeab59 100644--- a/magic_pdf/model/pdf_extract_kit.py+++ b/magic_pdf/model/pdf_extract_kit.py@@ -3,6 +3,7 @@ import osimport timefrom magic_pdf.libs.Constants import *+from magic_pdf.model.model_list import AtomicModelos.environ['NO_ALBUMENTATIONS_UPDATE'] = '1' # 禁止albumentations检查更新try:@@ -64,7 +65,8 @@ def mfr_model_init(weight_dir, cfg_path, _device_='cpu'):model = task.build_model(cfg)model = model.to(_device_)vis_processor = load_processor('formula_image_eval', cfg.config.datasets.formula_rec_eval.vis_processor.eval)- return model, vis_processor+ mfr_transform = transforms.Compose([vis_processor, ])+ return [model, mfr_transform]def layout_model_init(weight, config_file, device):@@ -72,6 +74,11 @@ def layout_model_init(weight, config_file, device):return model+def ocr_model_init(show_log: bool = False, det_db_box_thresh=0.3):+ model = ModifiedPaddleOCR(show_log=show_log, det_db_box_thresh=det_db_box_thresh)+ return model++class MathDataset(Dataset):def __init__(self, image_paths, transform=None):self.image_paths = image_paths@@ -91,6 +98,58 @@ class MathDataset(Dataset):return image+class AtomModelSingleton:+ _instance = None+ _models = {}++ def __new__(cls, *args, **kwargs):+ if cls._instance is None:+ cls._instance = super().__new__(cls)+ return cls._instance++ def get_atom_model(self, atom_model_name: str, **kwargs):+ if atom_model_name not in self._models:+ self._models[atom_model_name] = atom_model_init(model_name=atom_model_name, **kwargs)+ return self._models[atom_model_name]+++def atom_model_init(model_name: str, **kwargs):++ if model_name == AtomicModel.Layout:+ atom_model = layout_model_init(+ kwargs.get("layout_weights"),+ kwargs.get("layout_config_file"),+ kwargs.get("device")+ )+ elif model_name == AtomicModel.MFD:+ atom_model = mfd_model_init(+ kwargs.get("mfd_weights")+ )+ elif model_name == AtomicModel.MFR:+ atom_model = mfr_model_init(+ kwargs.get("mfr_weight_dir"),+ kwargs.get("mfr_cfg_path"),+ kwargs.get("device")+ )+ elif model_name == AtomicModel.OCR:+ atom_model = ocr_model_init(+ kwargs.get("ocr_show_log"),+ kwargs.get("det_db_box_thresh")+ )+ elif model_name == AtomicModel.Table:+ atom_model = table_model_init(+ kwargs.get("table_model_type"),+ kwargs.get("table_model_path"),+ kwargs.get("table_max_time"),+ kwargs.get("device")+ )+ else:+ logger.error("model name not allow")+ exit(1)++ return atom_model++class CustomPEKModel:def __init__(self, ocr: bool = False, show_log: bool = False, **kwargs):@@ -130,32 +189,62 @@ class CustomPEKModel:models_dir = kwargs.get("models_dir", os.path.join(root_dir, "resources", "models"))logger.info("using models_dir: {}".format(models_dir))+ atom_model_manager = AtomModelSingleton()+# 初始化公式识别if self.apply_formula:# 初始化公式检测模型- self.mfd_model = mfd_model_init(str(os.path.join(models_dir, self.configs["weights"]["mfd"])))-+ # self.mfd_model = mfd_model_init(str(os.path.join(models_dir, self.configs["weights"]["mfd"])))+ self.mfd_model = atom_model_manager.get_atom_model(+ atom_model_name=AtomicModel.MFD,+ mfd_weights=str(os.path.join(models_dir, self.configs["weights"]["mfd"]))+ )# 初始化公式解析模型mfr_weight_dir = str(os.path.join(models_dir, self.configs["weights"]["mfr"]))mfr_cfg_path = str(os.path.join(model_config_dir, "UniMERNet", "demo.yaml"))- self.mfr_model, mfr_vis_processors = mfr_model_init(mfr_weight_dir, mfr_cfg_path, _device_=self.device)- self.mfr_transform = transforms.Compose([mfr_vis_processors, ])+ # self.mfr_model, mfr_vis_processors = mfr_model_init(mfr_weight_dir, mfr_cfg_path, _device_=self.device)+ # self.mfr_transform = transforms.Compose([mfr_vis_processors, ])+ self.mfr_model, self.mfr_transform = atom_model_manager.get_atom_model(+ atom_model_name=AtomicModel.MFR,+ mfr_weight_dir=mfr_weight_dir,+ mfr_cfg_path=mfr_cfg_path,+ device=self.device+ )# 初始化layout模型- self.layout_model = Layoutlmv3_Predictor(- str(os.path.join(models_dir, self.configs['weights']['layout'])),- str(os.path.join(model_config_dir, "layoutlmv3", "layoutlmv3_base_inference.yaml")),+ # self.layout_model = Layoutlmv3_Predictor(+ # str(os.path.join(models_dir, self.configs['weights']['layout'])),+ # str(os.path.join(model_config_dir, "layoutlmv3", "layoutlmv3_base_inference.yaml")),+ # device=self.device+ # )+ self.layout_model = atom_model_manager.get_atom_model(+ atom_model_name=AtomicModel.Layout,+ layout_weights=str(os.path.join(models_dir, self.configs['weights']['layout'])),+ layout_config_file=str(os.path.join(model_config_dir, "layoutlmv3", "layoutlmv3_base_inference.yaml")),device=self.device)# 初始化ocrif self.apply_ocr:- self.ocr_model = ModifiedPaddleOCR(show_log=show_log)+ # self.ocr_model = ModifiedPaddleOCR(show_log=show_log, det_db_box_thresh=0.3)+ self.ocr_model = atom_model_manager.get_atom_model(+ atom_model_name=AtomicModel.OCR,+ ocr_show_log=show_log,+ det_db_box_thresh=0.3+ )# init table modelif self.apply_table:table_model_dir = self.configs["weights"][self.table_model_type]- self.table_model = table_model_init(self.table_model_type, str(os.path.join(models_dir, table_model_dir)),- max_time=self.table_max_time, _device_=self.device)+ # self.table_model = table_model_init(self.table_model_type, str(os.path.join(models_dir, table_model_dir)),+ # max_time=self.table_max_time, _device_=self.device)+ self.table_model = atom_model_manager.get_atom_model(+ atom_model_name=AtomicModel.Table,+ table_model_type=self.table_model_type,+ table_model_path=str(os.path.join(models_dir, table_model_dir)),+ table_max_time=self.table_max_time,+ device=self.device+ )+logger.info('DocAnalysis init done!')def __call__(self, image):@@ -291,11 +380,12 @@ class CustomPEKModel:logger.info("------------------table recognition processing begins-----------------")latex_code = Nonehtml_code = None- with torch.no_grad():- if self.table_model_type == STRUCT_EQTABLE:+ if self.table_model_type == STRUCT_EQTABLE:+ with torch.no_grad():latex_code = self.table_model.image2latex(new_image)[0]- else:- html_code = self.table_model.img2html(new_image)+ else:+ html_code = self.table_model.img2html(new_image)+run_time = time.time() - single_table_start_timelogger.info(f"------------table recognition processing ends within {run_time}s-----")if run_time > self.table_max_time:diff --git a/magic_pdf/model/pek_sub_modules/self_modify.py b/magic_pdf/model/pek_sub_modules/self_modify.pyindex 5316bc76..c39c1a9c 100644--- a/magic_pdf/model/pek_sub_modules/self_modify.py+++ b/magic_pdf/model/pek_sub_modules/self_modify.py@@ -12,6 +12,7 @@ from paddleocr.ppocr.utils.utility import check_and_read, alpha_to_color, binarifrom paddleocr.tools.infer.utility import draw_ocr_box_txt, get_rotate_crop_image, get_minarea_rect_cropfrom magic_pdf.libs.boxbase import __is_overlaps_y_exceeds_threshold+from magic_pdf.pre_proc.ocr_dict_merge import merge_spans_to_linelogger = get_logger()@@ -162,6 +163,86 @@ def update_det_boxes(dt_boxes, mfd_res):return new_dt_boxes+def merge_overlapping_spans(spans):+ """+ Merges overlapping spans on the same line.++ :param spans: A list of span coordinates [(x1, y1, x2, y2), ...]+ :return: A list of merged spans+ """+ # Return an empty list if the input spans list is empty+ if not spans:+ return []++ # Sort spans by their starting x-coordinate+ spans.sort(key=lambda x: x[0])++ # Initialize the list of merged spans+ merged = []+ for span in spans:+ # Unpack span coordinates+ x1, y1, x2, y2 = span+ # If the merged list is empty or there's no horizontal overlap, add the span directly+ if not merged or merged[-1][2] < x1:+ merged.append(span)+ else:+ # If there is horizontal overlap, merge the current span with the previous one+ last_span = merged.pop()+ # Update the merged span's top-left corner to the smaller (x1, y1) and bottom-right to the larger (x2, y2)+ x1 = min(last_span[0], x1)+ y1 = min(last_span[1], y1)+ x2 = max(last_span[2], x2)+ y2 = max(last_span[3], y2)+ # Add the merged span back to the list+ merged.append((x1, y1, x2, y2))++ # Return the list of merged spans+ return merged+++def merge_det_boxes(dt_boxes):+ """+ Merge detection boxes.++ This function takes a list of detected bounding boxes, each represented by four corner points.+ The goal is to merge these bounding boxes into larger text regions.++ Parameters:+ dt_boxes (list): A list containing multiple text detection boxes, where each box is defined by four corner points.++ Returns:+ list: A list containing the merged text regions, where each region is represented by four corner points.+ """+ # Convert the detection boxes into a dictionary format with bounding boxes and type+ dt_boxes_dict_list = []+ for text_box in dt_boxes:+ text_bbox = points_to_bbox(text_box)+ text_box_dict = {+ 'bbox': text_bbox,+ 'type': 'text',+ }+ dt_boxes_dict_list.append(text_box_dict)++ # Merge adjacent text regions into lines+ lines = merge_spans_to_line(dt_boxes_dict_list)++ # Initialize a new list for storing the merged text regions+ new_dt_boxes = []+ for line in lines:+ line_bbox_list = []+ for span in line:+ line_bbox_list.append(span['bbox'])++ # Merge overlapping text regions within the same line+ merged_spans = merge_overlapping_spans(line_bbox_list)++ # Convert the merged text regions back to point format and add them to the new detection box list+ for span in merged_spans:+ new_dt_boxes.append(bbox_to_points(span))++ return new_dt_boxes++class ModifiedPaddleOCR(PaddleOCR):def ocr(self, img, det=True, rec=True, cls=True, bin=False, inv=False, mfd_res=None, alpha_color=(255, 255, 255)):"""@@ -265,6 +346,9 @@ class ModifiedPaddleOCR(PaddleOCR):img_crop_list = []dt_boxes = sorted_boxes(dt_boxes)++ dt_boxes = merge_det_boxes(dt_boxes)+if mfd_res:bef = time.time()dt_boxes = update_det_boxes(dt_boxes, mfd_res)diff --git a/magic_pdf/para/para_split_v2.py b/magic_pdf/para/para_split_v2.pyindex 53401682..0e9ab0cd 100644--- a/magic_pdf/para/para_split_v2.py+++ b/magic_pdf/para/para_split_v2.py@@ -1,3 +1,5 @@+import copy+from sklearn.cluster import DBSCANimport numpy as npfrom loguru import logger@@ -167,7 +169,7 @@ def cluster_line_x(lines: list) -> dict:x0_lst = np.array([[round(line['bbox'][0]), 0] for line in lines])x0_clusters = DBSCAN(eps=min_distance, min_samples=min_sample).fit(x0_lst)x0_uniq_label = np.unique(x0_clusters.labels_)- #x1_lst = np.array([[line['bbox'][2], 0] for line in lines])+ # x1_lst = np.array([[line['bbox'][2], 0] for line in lines])x0_2_new_val = {} # 存储旧值对应的新值映射min_x0 = round(lines[0]["bbox"][0])for label in x0_uniq_label:@@ -200,7 +202,9 @@ def __valign_lines(blocks, layout_bboxes):min_distance = 3min_sample = 2new_layout_bboxes = []-+ # add bbox_fs for para split calculation+ for block in blocks:+ block["bbox_fs"] = copy.deepcopy(block["bbox"])for layout_box in layout_bboxes:blocks_in_layoutbox = [b for b in blocks ifb["type"] == BlockType.Text and is_in_layout(b['bbox'], layout_box['layout_bbox'])]@@ -245,16 +249,15 @@ def __valign_lines(blocks, layout_bboxes):# 由于修改了block里的line长度,现在需要重新计算block的bboxfor block in blocks_in_layoutbox:if len(block["lines"]) > 0:- block['bbox'] = [min([line['bbox'][0] for line in block['lines']]),- min([line['bbox'][1] for line in block['lines']]),- max([line['bbox'][2] for line in block['lines']]),- max([line['bbox'][3] for line in block['lines']])]-+ block['bbox_fs'] = [min([line['bbox'][0] for line in block['lines']]),+ min([line['bbox'][1] for line in block['lines']]),+ max([line['bbox'][2] for line in block['lines']]),+ max([line['bbox'][3] for line in block['lines']])]"""新计算layout的bbox,因为block的bbox变了。"""- layout_x0 = min([block['bbox'][0] for block in blocks_in_layoutbox])- layout_y0 = min([block['bbox'][1] for block in blocks_in_layoutbox])- layout_x1 = max([block['bbox'][2] for block in blocks_in_layoutbox])- layout_y1 = max([block['bbox'][3] for block in blocks_in_layoutbox])+ layout_x0 = min([block['bbox_fs'][0] for block in blocks_in_layoutbox])+ layout_y0 = min([block['bbox_fs'][1] for block in blocks_in_layoutbox])+ layout_x1 = max([block['bbox_fs'][2] for block in blocks_in_layoutbox])+ layout_y1 = max([block['bbox_fs'][3] for block in blocks_in_layoutbox])new_layout_bboxes.append([layout_x0, layout_y0, layout_x1, layout_y1])return new_layout_bboxes@@ -312,7 +315,7 @@ def __group_line_by_layout(blocks, layout_bboxes):# 因为只是一个block一行目前, 一个block就是一个段落blocks_group = []for lyout in layout_bboxes:- blocks_in_layout = [block for block in blocks if is_in_layout(block['bbox'], lyout['layout_bbox'])]+ blocks_in_layout = [block for block in blocks if is_in_layout(block.get('bbox_fs', None), lyout['layout_bbox'])]blocks_group.append(blocks_in_layout)return blocks_group@@ -365,7 +368,8 @@ def __split_para_in_layoutbox(blocks_group, new_layout_bbox, lang="en"):for i in range(0, len(list_start)):index = list_start[i] - 1if index >= 0:- if "content" in lines[index]["spans"][-1]:+ if "content" in lines[index]["spans"][-1] and lines[index]["spans"][-1].get('type', '') not in [+ ContentType.InlineEquation, ContentType.InterlineEquation]:lines[index]["spans"][-1]["content"] += '\n\n'layout_list_info = [False, False] # 这个layout最后是不是列表,记录每一个layout里是不是列表开头,列表结尾for content_type, start, end in text_segments:@@ -477,7 +481,7 @@ def __connect_list_inter_page(pre_page_paras, next_page_paras, pre_page_layout_bbreak# 如果这些行的缩进是相等的,那么连到上一个layout的最后一个段落上。if len(may_list_lines) > 0 and len(set([x['bbox'][0] for x in may_list_lines])) == 1:- #pre_page_paras[-1].append(may_list_lines)+ # pre_page_paras[-1].append(may_list_lines)# 下一页合并到上一页最后一段,打一个cross_page的标签for line in may_list_lines:for span in line["spans"]:@@ -537,7 +541,6 @@ def __connect_para_inter_layoutbox(blocks_group, new_layout_bbox):next_first_line_text = ''.join([__get_span_text(span) for span in next_first_line['spans']])next_first_line_type = next_first_line['spans'][0]['type']if pre_last_line_type not in [TEXT, INLINE_EQUATION] or next_first_line_type not in [TEXT, INLINE_EQUATION]:- #connected_layout_paras.append(layout_paras[i])connected_layout_blocks.append(blocks_group[i])continuepre_layout = __find_layout_bbox_by_line(pre_last_line['bbox'], new_layout_bbox)@@ -552,10 +555,8 @@ def __connect_para_inter_layoutbox(blocks_group, new_layout_bbox):-1] not in LINE_STOP_FLAG and \next_first_line['bbox'][0] == next_x0_min: # 前面一行沾满了整个行,并且没有结尾符号.下一行没有空白开头。"""连接段落条件成立,将前一个layout的段落和后一个layout的段落连接。"""- #connected_layout_paras[-1][-1].extend(layout_paras[i][0])connected_layout_blocks[-1][-1]["lines"].extend(blocks_group[i][0]["lines"])- #layout_paras[i].pop(0) # 删除后一个layout的第一个段落, 因为他已经被合并到前一个layout的最后一个段落了。- blocks_group[i][0]["lines"] = [] #删除后一个layout第一个段落中的lines,因为他已经被合并到前一个layout的最后一个段落了+ blocks_group[i][0]["lines"] = [] # 删除后一个layout第一个段落中的lines,因为他已经被合并到前一个layout的最后一个段落了blocks_group[i][0][LINES_DELETED] = True# if len(layout_paras[i]) == 0:# layout_paras.pop(i)@@ -564,7 +565,6 @@ def __connect_para_inter_layoutbox(blocks_group, new_layout_bbox):connected_layout_blocks.append(blocks_group[i])else:"""连接段落条件不成立,将前一个layout的段落加入到结果中。"""- #connected_layout_paras.append(layout_paras[i])connected_layout_blocks.append(blocks_group[i])return connected_layout_blocks@@ -622,7 +622,7 @@ def __connect_para_inter_page(pre_page_paras, next_page_paras, pre_page_layout_bspan[CROSS_PAGE] = Truepre_last_para.extend(next_first_para)- #next_page_paras[0].pop(0) # 删除后一个页面的第一个段落, 因为他已经被合并到前一个页面的最后一个段落了。+ # next_page_paras[0].pop(0) # 删除后一个页面的第一个段落, 因为他已经被合并到前一个页面的最后一个段落了。next_page_paras[0][0]["lines"] = []next_page_paras[0][0][LINES_DELETED] = Truereturn True@@ -666,16 +666,15 @@ def __connect_middle_align_text(page_paras, new_layout_bbox, page_num, lang):layout_box = new_layout_bbox[layout_i]single_line_paras_tag = []for i in range(len(layout_para)):- #single_line_paras_tag.append(len(layout_para[i]) == 1 and layout_para[i][0]['spans'][0]['type'] == TEXT)+ # single_line_paras_tag.append(len(layout_para[i]) == 1 and layout_para[i][0]['spans'][0]['type'] == TEXT)single_line_paras_tag.append(layout_para[i]['type'] == BlockType.Text and len(layout_para[i]["lines"]) == 1)"""找出来连续的单行文本,如果连续行高度相同,那么合并为一个段落。"""consecutive_single_line_indices = find_consecutive_true_regions(single_line_paras_tag)if len(consecutive_single_line_indices) > 0:- #index_offset = 0"""检查这些行是否是高度相同的,居中的"""for start, end in consecutive_single_line_indices:- #start += index_offset- #end += index_offset+ # start += index_offset+ # end += index_offsetline_hi = np.array([block["lines"][0]['bbox'][3] - block["lines"][0]['bbox'][1] for block inlayout_para[start:end + 1]])first_line_text = ''.join([__get_span_text(span) for span in layout_para[start]["lines"][0]['spans']])@@ -700,9 +699,9 @@ def __connect_middle_align_text(page_paras, new_layout_bbox, page_num, lang):for i_para in range(start + 1, end + 1):layout_para[i_para]["lines"] = []layout_para[i_para][LINES_DELETED] = True- #layout_para[start:end + 1] = [merge_para]+ # layout_para[start:end + 1] = [merge_para]- #index_offset -= end - start+ # index_offset -= end - startreturn@@ -742,7 +741,7 @@ def para_split(pdf_info_dict, debug_mode, lang="en"):new_layout_of_pages = [] # 数组的数组,每个元素是一个页面的layoutSall_page_list_info = [] # 保存每个页面开头和结尾是否是列表for page_num, page in pdf_info_dict.items():- blocks = page['preproc_blocks']+ blocks = copy.deepcopy(page['preproc_blocks'])layout_bboxes = page['layout_bboxes']new_layout_bbox = __common_pre_proc(blocks, layout_bboxes)new_layout_of_pages.append(new_layout_bbox)diff --git a/magic_pdf/pdf_parse_union_core.py b/magic_pdf/pdf_parse_union_core.pyindex 4d3436d4..c764f0ce 100644--- a/magic_pdf/pdf_parse_union_core.py+++ b/magic_pdf/pdf_parse_union_core.py@@ -41,6 +41,23 @@ def remove_horizontal_overlap_block_which_smaller(all_bboxes):return is_useful_block_horz_overlap, all_bboxes+def __replace_STX_ETX(text_str:str):+ """ Replace \u0002 and \u0003, as these characters become garbled when extracted using pymupdf. In fact, they were originally quotation marks.+Drawback: This issue is only observed in English text; it has not been found in Chinese text so far.++ Args:+ text_str (str): raw text++ Returns:+ _type_: replaced text+ """+ if text_str:+ s = text_str.replace('\u0002', "'")+ s = s.replace("\u0003", "'")+ return s+ return text_str++def txt_spans_extract(pdf_page, inline_equations, interline_equations):text_raw_blocks = pdf_page.get_text("dict", flags=fitz.TEXTFLAGS_TEXT)["blocks"]char_level_text_blocks = pdf_page.get_text("rawdict", flags=fitz.TEXTFLAGS_TEXT)[@@ -63,7 +80,7 @@ def txt_spans_extract(pdf_page, inline_equations, interline_equations):spans.append({"bbox": list(span["bbox"]),- "content": span["text"],+ "content": __replace_STX_ETX(span["text"]),"type": ContentType.Text,"score": 1.0,}@@ -175,7 +192,7 @@ def parse_page_core(pdf_docs, magic_model, page_id, pdf_bytes_md5, imageWriter,sorted_blocks = sort_blocks_by_layout(all_bboxes, layout_bboxes)'''将span填入排好序的blocks中'''- block_with_spans, spans = fill_spans_in_blocks(sorted_blocks, spans, 0.6)+ block_with_spans, spans = fill_spans_in_blocks(sorted_blocks, spans, 0.3)'''对block进行fix操作'''fix_blocks = fix_block_spans(block_with_spans, img_blocks, table_blocks)@@ -208,13 +225,17 @@ def pdf_parse_union(pdf_bytes,magic_model = MagicModel(model_list, pdf_docs)'''根据输入的起始范围解析pdf'''- end_page_id = end_page_id if end_page_id else len(pdf_docs) - 1+ # end_page_id = end_page_id if end_page_id else len(pdf_docs) - 1+ end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else len(pdf_docs) - 1++ if end_page_id > len(pdf_docs) - 1:+ logger.warning("end_page_id is out of range, use pdf_docs length")+ end_page_id = len(pdf_docs) - 1'''初始化启动时间'''start_time = time.time()- for page_id in range(start_page_id, end_page_id + 1):-+ for page_id, page in enumerate(pdf_docs):'''debug时输出每页解析的耗时'''if debug_mode:time_now = time.time()@@ -224,7 +245,14 @@ def pdf_parse_union(pdf_bytes,start_time = time_now'''解析pdf中的每一页'''- page_info = parse_page_core(pdf_docs, magic_model, page_id, pdf_bytes_md5, imageWriter, parse_mode)+ if start_page_id <= page_id <= end_page_id:+ page_info = parse_page_core(pdf_docs, magic_model, page_id, pdf_bytes_md5, imageWriter, parse_mode)+ else:+ page_w = page.rect.width+ page_h = page.rect.height+ page_info = ocr_construct_page_component_v2([], [], page_id, page_w, page_h, [],+ [], [], [], [],+ True, "skip page")pdf_info_dict[f"page_{page_id}"] = page_info"""分段"""diff --git a/magic_pdf/pipe/AbsPipe.py b/magic_pdf/pipe/AbsPipe.pyindex f802a9a5..91d5a31b 100644--- a/magic_pdf/pipe/AbsPipe.py+++ b/magic_pdf/pipe/AbsPipe.py@@ -16,12 +16,15 @@ class AbsPipe(ABC):PIP_OCR = "ocr"PIP_TXT = "txt"- def __init__(self, pdf_bytes: bytes, model_list: list, image_writer: AbsReaderWriter, is_debug: bool = False):+ def __init__(self, pdf_bytes: bytes, model_list: list, image_writer: AbsReaderWriter, is_debug: bool = False,+ start_page_id=0, end_page_id=None):self.pdf_bytes = pdf_bytesself.model_list = model_listself.image_writer = image_writerself.pdf_mid_data = None # 未压缩self.is_debug = is_debug+ self.start_page_id = start_page_id+ self.end_page_id = end_page_iddef get_compress_pdf_mid_data(self):return JsonCompressor.compress_json(self.pdf_mid_data)diff --git a/magic_pdf/pipe/OCRPipe.py b/magic_pdf/pipe/OCRPipe.pyindex a46bdfd9..46525227 100644--- a/magic_pdf/pipe/OCRPipe.py+++ b/magic_pdf/pipe/OCRPipe.py@@ -9,17 +9,20 @@ from magic_pdf.user_api import parse_ocr_pdfclass OCRPipe(AbsPipe):- def __init__(self, pdf_bytes: bytes, model_list: list, image_writer: AbsReaderWriter, is_debug: bool = False):- super().__init__(pdf_bytes, model_list, image_writer, is_debug)+ def __init__(self, pdf_bytes: bytes, model_list: list, image_writer: AbsReaderWriter, is_debug: bool = False,+ start_page_id=0, end_page_id=None):+ super().__init__(pdf_bytes, model_list, image_writer, is_debug, start_page_id, end_page_id)def pipe_classify(self):passdef pipe_analyze(self):- self.model_list = doc_analyze(self.pdf_bytes, ocr=True)+ self.model_list = doc_analyze(self.pdf_bytes, ocr=True,+ start_page_id=self.start_page_id, end_page_id=self.end_page_id)def pipe_parse(self):- self.pdf_mid_data = parse_ocr_pdf(self.pdf_bytes, self.model_list, self.image_writer, is_debug=self.is_debug)+ self.pdf_mid_data = parse_ocr_pdf(self.pdf_bytes, self.model_list, self.image_writer, is_debug=self.is_debug,+ start_page_id=self.start_page_id, end_page_id=self.end_page_id)def pipe_mk_uni_format(self, img_parent_path: str, drop_mode=DropMode.WHOLE_PDF):result = super().pipe_mk_uni_format(img_parent_path, drop_mode)diff --git a/magic_pdf/pipe/TXTPipe.py b/magic_pdf/pipe/TXTPipe.pyindex 647b5069..2991e032 100644--- a/magic_pdf/pipe/TXTPipe.py+++ b/magic_pdf/pipe/TXTPipe.py@@ -10,17 +10,20 @@ from magic_pdf.user_api import parse_txt_pdfclass TXTPipe(AbsPipe):- def __init__(self, pdf_bytes: bytes, model_list: list, image_writer: AbsReaderWriter, is_debug: bool = False):- super().__init__(pdf_bytes, model_list, image_writer, is_debug)+ def __init__(self, pdf_bytes: bytes, model_list: list, image_writer: AbsReaderWriter, is_debug: bool = False,+ start_page_id=0, end_page_id=None):+ super().__init__(pdf_bytes, model_list, image_writer, is_debug, start_page_id, end_page_id)def pipe_classify(self):passdef pipe_analyze(self):- self.model_list = doc_analyze(self.pdf_bytes, ocr=False)+ self.model_list = doc_analyze(self.pdf_bytes, ocr=False,+ start_page_id=self.start_page_id, end_page_id=self.end_page_id)def pipe_parse(self):- self.pdf_mid_data = parse_txt_pdf(self.pdf_bytes, self.model_list, self.image_writer, is_debug=self.is_debug)+ self.pdf_mid_data = parse_txt_pdf(self.pdf_bytes, self.model_list, self.image_writer, is_debug=self.is_debug,+ start_page_id=self.start_page_id, end_page_id=self.end_page_id)def pipe_mk_uni_format(self, img_parent_path: str, drop_mode=DropMode.WHOLE_PDF):result = super().pipe_mk_uni_format(img_parent_path, drop_mode)diff --git a/magic_pdf/pipe/UNIPipe.py b/magic_pdf/pipe/UNIPipe.pyindex 243a8964..21f59178 100644--- a/magic_pdf/pipe/UNIPipe.py+++ b/magic_pdf/pipe/UNIPipe.py@@ -13,9 +13,10 @@ from magic_pdf.user_api import parse_union_pdf, parse_ocr_pdfclass UNIPipe(AbsPipe):- def __init__(self, pdf_bytes: bytes, jso_useful_key: dict, image_writer: AbsReaderWriter, is_debug: bool = False):+ def __init__(self, pdf_bytes: bytes, jso_useful_key: dict, image_writer: AbsReaderWriter, is_debug: bool = False,+ start_page_id=0, end_page_id=None):self.pdf_type = jso_useful_key["_pdf_type"]- super().__init__(pdf_bytes, jso_useful_key["model_list"], image_writer, is_debug)+ super().__init__(pdf_bytes, jso_useful_key["model_list"], image_writer, is_debug, start_page_id, end_page_id)if len(self.model_list) == 0:self.input_model_is_empty = Trueelse:@@ -26,17 +27,21 @@ class UNIPipe(AbsPipe):def pipe_analyze(self):if self.pdf_type == self.PIP_TXT:- self.model_list = doc_analyze(self.pdf_bytes, ocr=False)+ self.model_list = doc_analyze(self.pdf_bytes, ocr=False,+ start_page_id=self.start_page_id, end_page_id=self.end_page_id)elif self.pdf_type == self.PIP_OCR:- self.model_list = doc_analyze(self.pdf_bytes, ocr=True)+ self.model_list = doc_analyze(self.pdf_bytes, ocr=True,+ start_page_id=self.start_page_id, end_page_id=self.end_page_id)def pipe_parse(self):if self.pdf_type == self.PIP_TXT:self.pdf_mid_data = parse_union_pdf(self.pdf_bytes, self.model_list, self.image_writer,- is_debug=self.is_debug, input_model_is_empty=self.input_model_is_empty)+ is_debug=self.is_debug, input_model_is_empty=self.input_model_is_empty,+ start_page_id=self.start_page_id, end_page_id=self.end_page_id)elif self.pdf_type == self.PIP_OCR:self.pdf_mid_data = parse_ocr_pdf(self.pdf_bytes, self.model_list, self.image_writer,- is_debug=self.is_debug)+ is_debug=self.is_debug,+ start_page_id=self.start_page_id, end_page_id=self.end_page_id)def pipe_mk_uni_format(self, img_parent_path: str, drop_mode=DropMode.WHOLE_PDF):result = super().pipe_mk_uni_format(img_parent_path, drop_mode)diff --git a/magic_pdf/pre_proc/ocr_detect_all_bboxes.py b/magic_pdf/pre_proc/ocr_detect_all_bboxes.pyindex b058912a..9e2cd429 100644--- a/magic_pdf/pre_proc/ocr_detect_all_bboxes.py+++ b/magic_pdf/pre_proc/ocr_detect_all_bboxes.py@@ -133,6 +133,7 @@ def remove_need_drop_blocks(all_bboxes, discarded_blocks):def remove_overlaps_min_blocks(all_bboxes):+ # 重叠block,小的不能直接删除,需要和大的那个合并成一个更大的。# 删除重叠blocks中较小的那些need_remove = []for block1 in all_bboxes:@@ -142,9 +143,17 @@ def remove_overlaps_min_blocks(all_bboxes):block2_bbox = block2[:4]overlap_box = get_minbox_if_overlap_by_ratio(block1_bbox, block2_bbox, 0.8)if overlap_box is not None:- bbox_to_remove = next((block for block in all_bboxes if block[:4] == overlap_box), None)- if bbox_to_remove is not None and bbox_to_remove not in need_remove:- need_remove.append(bbox_to_remove)+ block_to_remove = next((block for block in all_bboxes if block[:4] == overlap_box), None)+ if block_to_remove is not None and block_to_remove not in need_remove:+ large_block = block1 if block1 != block_to_remove else block2+ x1, y1, x2, y2 = large_block[:4]+ sx1, sy1, sx2, sy2 = block_to_remove[:4]+ x1 = min(x1, sx1)+ y1 = min(y1, sy1)+ x2 = max(x2, sx2)+ y2 = max(y2, sy2)+ large_block[:4] = [x1, y1, x2, y2]+ need_remove.append(block_to_remove)if len(need_remove) > 0:for block in need_remove:diff --git a/magic_pdf/pre_proc/ocr_dict_merge.py b/magic_pdf/pre_proc/ocr_dict_merge.pyindex 74c1f89f..d9a24319 100644--- a/magic_pdf/pre_proc/ocr_dict_merge.py+++ b/magic_pdf/pre_proc/ocr_dict_merge.py@@ -1,18 +1,15 @@-from loguru import logger--from magic_pdf.libs.boxbase import __is_overlaps_y_exceeds_threshold, get_minbox_if_overlap_by_ratio, \- calculate_overlap_area_in_bbox1_area_ratio, _is_in_or_part_overlap_with_area_ratio+from magic_pdf.libs.boxbase import (__is_overlaps_y_exceeds_threshold,+ _is_in_or_part_overlap_with_area_ratio,+ calculate_overlap_area_in_bbox1_area_ratio)from magic_pdf.libs.drop_tag import DropTag-from magic_pdf.libs.ocr_content_type import ContentType, BlockType-from magic_pdf.pre_proc.ocr_span_list_modify import modify_y_axis, modify_inline_equation-from magic_pdf.pre_proc.remove_bbox_overlap import remove_overlap_between_bbox_for_span+from magic_pdf.libs.ocr_content_type import BlockType, ContentType# 将每一个line中的span从左到右排序def line_sort_spans_by_left_to_right(lines):line_objects = []for line in lines:- # 按照x0坐标排序+ # 按照x0坐标排序line.sort(key=lambda span: span['bbox'][0])line_bbox = [min(span['bbox'][0] for span in line), # x0@@ -21,8 +18,8 @@ def line_sort_spans_by_left_to_right(lines):max(span['bbox'][3] for span in line), # y1]line_objects.append({- "bbox": line_bbox,- "spans": line,+ 'bbox': line_bbox,+ 'spans': line,})return line_objects@@ -39,16 +36,21 @@ def merge_spans_to_line(spans):for span in spans[1:]:# 如果当前的span类型为"interline_equation" 或者 当前行中已经有"interline_equation"# image和table类型,同上- if span['type'] in [ContentType.InterlineEquation, ContentType.Image, ContentType.Table] or any(- s['type'] in [ContentType.InterlineEquation, ContentType.Image, ContentType.Table] for s in- current_line):+ if span['type'] in [+ ContentType.InterlineEquation, ContentType.Image,+ ContentType.Table+ ] or any(s['type'] in [+ ContentType.InterlineEquation, ContentType.Image,+ ContentType.Table+ ] for s in current_line):# 则开始新行lines.append(current_line)current_line = [span]continue# 如果当前的span与当前行的最后一个span在y轴上重叠,则添加到当前行- if __is_overlaps_y_exceeds_threshold(span['bbox'], current_line[-1]['bbox']):+ if __is_overlaps_y_exceeds_threshold(span['bbox'],+ current_line[-1]['bbox']):current_line.append(span)else:# 否则,开始新行@@ -71,7 +73,8 @@ def merge_spans_to_line_by_layout(spans, layout_bboxes):# 遍历spans,将每个span放入对应的layout中layout_sapns = []for span in spans:- if calculate_overlap_area_in_bbox1_area_ratio(span['bbox'], layout_bbox) > 0.6:+ if calculate_overlap_area_in_bbox1_area_ratio(+ span['bbox'], layout_bbox) > 0.6:layout_sapns.append(span)# 如果layout_sapns不为空,则放入new_spans中if len(layout_sapns) > 0:@@ -99,12 +102,10 @@ def merge_lines_to_block(lines):# 目前不做block拼接,先做个结构,每个block中只有一个line,block的bbox就是line的bboxblocks = []for line in lines:- blocks.append(- {- "bbox": line["bbox"],- "lines": [line],- }- )+ blocks.append({+ 'bbox': line['bbox'],+ 'lines': [line],+ })return blocks@@ -121,7 +122,8 @@ def sort_blocks_by_layout(all_bboxes, layout_bboxes):if block[7] == BlockType.Footnote:continueblock_bbox = block[:4]- if calculate_overlap_area_in_bbox1_area_ratio(block_bbox, layout_bbox) > 0.8:+ if calculate_overlap_area_in_bbox1_area_ratio(+ block_bbox, layout_bbox) > 0.8:layout_blocks.append(block)# 如果layout_blocks不为空,则放入new_blocks中@@ -134,7 +136,8 @@ def sort_blocks_by_layout(all_bboxes, layout_bboxes):# 如果new_blocks不为空,则对new_blocks中每个block进行排序if len(new_blocks) > 0:for bboxes_in_layout_block in new_blocks:- bboxes_in_layout_block.sort(key=lambda x: x[1]) # 一个layout内部的box,按照y0自上而下排序+ bboxes_in_layout_block.sort(+ key=lambda x: x[1]) # 一个layout内部的box,按照y0自上而下排序sort_blocks.extend(bboxes_in_layout_block)# sort_blocks中已经包含了当前页面所有最终留下的block,且已经排好了顺序@@ -142,9 +145,7 @@ def sort_blocks_by_layout(all_bboxes, layout_bboxes):def fill_spans_in_blocks(blocks, spans, radio):- '''- 将allspans中的span按位置关系,放入blocks中- '''+ """将allspans中的span按位置关系,放入blocks中."""block_with_spans = []for block in blocks:block_type = block[7]@@ -156,17 +157,15 @@ def fill_spans_in_blocks(blocks, spans, radio):block_spans = []for span in spans:span_bbox = span['bbox']- if calculate_overlap_area_in_bbox1_area_ratio(span_bbox, block_bbox) > radio:+ if calculate_overlap_area_in_bbox1_area_ratio(+ span_bbox, block_bbox) > radio:block_spans.append(span)-'''行内公式调整, 高度调整至与同行文字高度一致(优先左侧, 其次右侧)'''# displayed_list = []# text_inline_lines = []# modify_y_axis(block_spans, displayed_list, text_inline_lines)-'''模型识别错误的行间公式, type类型转换成行内公式'''# block_spans = modify_inline_equation(block_spans, displayed_list, text_inline_lines)-'''bbox去除粘连''' # 去粘连会影响span的bbox,导致后续fill的时候出错# block_spans = remove_overlap_between_bbox_for_span(block_spans)@@ -182,12 +181,9 @@ def fill_spans_in_blocks(blocks, spans, radio):def fix_block_spans(block_with_spans, img_blocks, table_blocks):- '''- 1、img_block和table_block因为包含caption和footnote的关系,存在block的嵌套关系- 需要将caption和footnote的text_span放入相应img_block和table_block内的- caption_block和footnote_block中- 2、同时需要删除block中的spans字段- '''+ """1、img_block和table_block因为包含caption和footnote的关系,存在block的嵌套关系+ 需要将caption和footnote的text_span放入相应img_block和table_block内的+ caption_block和footnote_block中 2、同时需要删除block中的spans字段."""fix_blocks = []for block in block_with_spans:block_type = block['type']@@ -218,16 +214,13 @@ def merge_spans_to_block(spans: list, block_bbox: list, block_type: str):block_spans = []# 如果有img_caption,则将img_block中的text_spans放入img_caption_block中for span in spans:- if calculate_overlap_area_in_bbox1_area_ratio(span['bbox'], block_bbox) > 0.6:+ if calculate_overlap_area_in_bbox1_area_ratio(span['bbox'],+ block_bbox) > 0.6:block_spans.append(span)block_lines = merge_spans_to_line(block_spans)# 对line中的span进行排序sort_block_lines = line_sort_spans_by_left_to_right(block_lines)- block = {- 'bbox': block_bbox,- 'type': block_type,- 'lines': sort_block_lines- }+ block = {'bbox': block_bbox, 'type': block_type, 'lines': sort_block_lines}return block, block_spans@@ -237,11 +230,7 @@ def make_body_block(span: dict, block_bbox: list, block_type: str):'bbox': block_bbox,'spans': [span],}- body_block = {- 'bbox': block_bbox,- 'type': block_type,- 'lines': [body_line]- }+ body_block = {'bbox': block_bbox, 'type': block_type, 'lines': [body_line]}return body_block@@ -249,13 +238,16 @@ def fix_image_block(block, img_blocks):block['blocks'] = []# 遍历img_blocks,找到与当前block匹配的img_blockfor img_block in img_blocks:- if _is_in_or_part_overlap_with_area_ratio(block['bbox'], img_block['bbox'], 0.95):+ if _is_in_or_part_overlap_with_area_ratio(block['bbox'],+ img_block['bbox'], 0.95):# 创建img_body_blockfor span in block['spans']:- if span['type'] == ContentType.Image and img_block['img_body_bbox'] == span['bbox']:+ if span['type'] == ContentType.Image and img_block[+ 'img_body_bbox'] == span['bbox']:# 创建img_body_block- img_body_block = make_body_block(span, img_block['img_body_bbox'], BlockType.ImageBody)+ img_body_block = make_body_block(+ span, img_block['img_body_bbox'], BlockType.ImageBody)block['blocks'].append(img_body_block)# 从spans中移除img_body_block中已经放入的span@@ -265,10 +257,15 @@ def fix_image_block(block, img_blocks):# 根据list长度,判断img_block中是否有img_captionif img_block['img_caption_bbox'] is not None:img_caption_block, img_caption_spans = merge_spans_to_block(- block['spans'], img_block['img_caption_bbox'], BlockType.ImageCaption- )+ block['spans'], img_block['img_caption_bbox'],+ BlockType.ImageCaption)block['blocks'].append(img_caption_block)+ if img_block['img_footnote_bbox'] is not None:+ img_footnote_block, img_footnote_spans = merge_spans_to_block(+ block['spans'], img_block['img_footnote_bbox'],+ BlockType.ImageFootnote)+ block['blocks'].append(img_footnote_block)breakdel block['spans']return block@@ -278,13 +275,17 @@ def fix_table_block(block, table_blocks):block['blocks'] = []# 遍历table_blocks,找到与当前block匹配的table_blockfor table_block in table_blocks:- if _is_in_or_part_overlap_with_area_ratio(block['bbox'], table_block['bbox'], 0.95):+ if _is_in_or_part_overlap_with_area_ratio(block['bbox'],+ table_block['bbox'], 0.95):# 创建table_body_blockfor span in block['spans']:- if span['type'] == ContentType.Table and table_block['table_body_bbox'] == span['bbox']:+ if span['type'] == ContentType.Table and table_block[+ 'table_body_bbox'] == span['bbox']:# 创建table_body_block- table_body_block = make_body_block(span, table_block['table_body_bbox'], BlockType.TableBody)+ table_body_block = make_body_block(+ span, table_block['table_body_bbox'],+ BlockType.TableBody)block['blocks'].append(table_body_block)# 从spans中移除img_body_block中已经放入的span@@ -294,8 +295,8 @@ def fix_table_block(block, table_blocks):# 根据list长度,判断table_block中是否有captionif table_block['table_caption_bbox'] is not None:table_caption_block, table_caption_spans = merge_spans_to_block(- block['spans'], table_block['table_caption_bbox'], BlockType.TableCaption- )+ block['spans'], table_block['table_caption_bbox'],+ BlockType.TableCaption)block['blocks'].append(table_caption_block)# 如果table_caption_block_spans不为空@@ -307,8 +308,8 @@ def fix_table_block(block, table_blocks):# 根据list长度,判断table_block中是否有table_noteif table_block['table_footnote_bbox'] is not None:table_footnote_block, table_footnote_spans = merge_spans_to_block(- block['spans'], table_block['table_footnote_bbox'], BlockType.TableFootnote- )+ block['spans'], table_block['table_footnote_bbox'],+ BlockType.TableFootnote)block['blocks'].append(table_footnote_block)breakdiff --git a/magic_pdf/tools/cli.py b/magic_pdf/tools/cli.pyindex 76fe3fa6..df8ee985 100644--- a/magic_pdf/tools/cli.py+++ b/magic_pdf/tools/cli.py@@ -1,53 +1,77 @@import os+from pathlib import Path+import clickfrom loguru import logger-from pathlib import Path-from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter-from magic_pdf.rw.AbsReaderWriter import AbsReaderWriterimport magic_pdf.model as model_config-from magic_pdf.tools.common import parse_pdf_methods, do_parsefrom magic_pdf.libs.version import __version__+from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter+from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter+from magic_pdf.tools.common import do_parse, parse_pdf_methods@click.command()[email protected]_option(__version__, "--version", "-v", help="display the version and exit")[email protected]_option(__version__,+ '--version',+ '-v',+ help='display the version and exit')@click.option(- "-p",- "--path",- "path",+ '-p',+ '--path',+ 'path',type=click.Path(exists=True),required=True,- help="local pdf filepath or directory",+ help='local pdf filepath or directory',)@click.option(- "-o",- "--output-dir",- "output_dir",- type=str,- help="output local directory",- default="",+ '-o',+ '--output-dir',+ 'output_dir',+ type=click.Path(),+ required=True,+ help='output local directory',)@click.option(- "-m",- "--method",- "method",+ '-m',+ '--method',+ 'method',type=parse_pdf_methods,- help="""the method for parsing pdf.+ help="""the method for parsing pdf.ocr: using ocr technique to extract information from pdf.txt: suitable for the text-based pdf only and outperform ocr.auto: automatically choose the best method for parsing pdf from ocr and txt.without method specified, auto will be used by default.""",- default="auto",+ default='auto',+)+ '-d',+ '--debug',+ 'debug_able',+ type=bool,+ help='Enables detailed debugging information during the execution of the CLI commands.',+ default=False,+)+ '-s',+ '--start',+ 'start_page_id',+ type=int,+ help='The starting page for PDF parsing, beginning from 0.',+ default=0,+)+ '-e',+ '--end',+ 'end_page_id',+ type=int,+ help='The ending page for PDF parsing, beginning from 0.',+ default=None,)-def cli(path, output_dir, method):+def cli(path, output_dir, method, debug_able, start_page_id, end_page_id):model_config.__use_inside_model__ = True- model_config.__model_mode__ = "full"- if output_dir == "":- if os.path.isdir(path):- output_dir = os.path.join(path, "output")- else:- output_dir = os.path.join(os.path.dirname(path), "output")+ model_config.__model_mode__ = 'full'+ os.makedirs(output_dir, exist_ok=True)def read_fn(path):disk_rw = DiskReaderWriter(os.path.dirname(path))@@ -63,17 +87,20 @@ def cli(path, output_dir, method):pdf_data,[],method,+ debug_able,+ start_page_id=start_page_id,+ end_page_id=end_page_id,)except Exception as e:logger.exception(e)if os.path.isdir(path):- for doc_path in Path(path).glob("*.pdf"):+ for doc_path in Path(path).glob('*.pdf'):parse_doc(doc_path)else:parse_doc(path)-if __name__ == "__main__":+if __name__ == '__main__':cli()diff --git a/magic_pdf/tools/cli_dev.py b/magic_pdf/tools/cli_dev.pyindex 14961bc0..c037f262 100644--- a/magic_pdf/tools/cli_dev.py+++ b/magic_pdf/tools/cli_dev.py@@ -1,35 +1,32 @@-import osimport json as json_parse-import click+import osfrom pathlib import Path-from magic_pdf.libs.path_utils import (- parse_s3path,- parse_s3_range_params,- remove_non_official_s3_args,-)-from magic_pdf.libs.config_reader import (- get_s3_config,-)-from magic_pdf.rw.S3ReaderWriter import S3ReaderWriter-from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter-from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter++import click+import magic_pdf.model as model_config-from magic_pdf.tools.common import parse_pdf_methods, do_parse+from magic_pdf.libs.config_reader import get_s3_config+from magic_pdf.libs.path_utils import (parse_s3_range_params, parse_s3path,+ remove_non_official_s3_args)from magic_pdf.libs.version import __version__+from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter+from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter+from magic_pdf.rw.S3ReaderWriter import S3ReaderWriter+from magic_pdf.tools.common import do_parse, parse_pdf_methodsdef read_s3_path(s3path):bucket, key = parse_s3path(s3path)s3_ak, s3_sk, s3_endpoint = get_s3_config(bucket)- s3_rw = S3ReaderWriter(- s3_ak, s3_sk, s3_endpoint, "auto", remove_non_official_s3_args(s3path)- )+ s3_rw = S3ReaderWriter(s3_ak, s3_sk, s3_endpoint, 'auto',+ remove_non_official_s3_args(s3path))may_range_params = parse_s3_range_params(s3path)if may_range_params is None or 2 != len(may_range_params):byte_start, byte_end = 0, Noneelse:- byte_start, byte_end = int(may_range_params[0]), int(may_range_params[1])+ byte_start, byte_end = int(may_range_params[0]), int(+ may_range_params[1])return s3_rw.read_offset(remove_non_official_s3_args(s3path),byte_start,@@ -38,51 +35,47 @@ def read_s3_path(s3path):@click.group()[email protected]_option(__version__, "--version", "-v", help="显示版本信息")[email protected]_option(__version__, '--version', '-v', help='显示版本信息')def cli():pass@cli.command()@click.option(- "-j",- "--jsonl",- "jsonl",+ '-j',+ '--jsonl',+ 'jsonl',type=str,- help="输入 jsonl 路径,本地或者 s3 上的文件",+ help='输入 jsonl 路径,本地或者 s3 上的文件',required=True,)@click.option(- "-m",- "--method",- "method",+ '-m',+ '--method',+ 'method',type=parse_pdf_methods,- help="指定解析方法。txt: 文本型 pdf 解析方法, ocr: 光学识别解析 pdf, auto: 程序智能选择解析方法",- default="auto",+ help='指定解析方法。txt: 文本型 pdf 解析方法, ocr: 光学识别解析 pdf, auto: 程序智能选择解析方法',+ default='auto',)@click.option(- "-o",- "--output-dir",- "output_dir",- type=str,- help="输出到本地目录",- default="",+ '-o',+ '--output-dir',+ 'output_dir',+ type=click.Path(),+ required=True,+ help='输出到本地目录',)def jsonl(jsonl, method, output_dir):model_config.__use_inside_model__ = False- if jsonl.startswith("s3://"):- jso = json_parse.loads(read_s3_path(jsonl).decode("utf-8"))- full_jsonl_path = "."+ if jsonl.startswith('s3://'):+ jso = json_parse.loads(read_s3_path(jsonl).decode('utf-8'))else:- full_jsonl_path = os.path.realpath(jsonl)with open(jsonl) as f:jso = json_parse.loads(f.readline())-- if output_dir == "":- output_dir = os.path.join(os.path.dirname(full_jsonl_path), "output")- s3_file_path = jso.get("file_location")+ os.makedirs(output_dir, exist_ok=True)+ s3_file_path = jso.get('file_location')if s3_file_path is None:- s3_file_path = jso.get("path")+ s3_file_path = jso.get('path')pdf_file_name = Path(s3_file_path).stempdf_data = read_s3_path(s3_file_path)@@ -91,8 +84,9 @@ def jsonl(jsonl, method, output_dir):output_dir,pdf_file_name,pdf_data,- jso["doc_layout_result"],+ jso['doc_layout_result'],method,+ False,f_dump_content_list=True,f_draw_model_bbox=True,)@@ -100,43 +94,45 @@ def jsonl(jsonl, method, output_dir):@cli.command()@click.option(- "-p",- "--pdf",- "pdf",+ '-p',+ '--pdf',+ 'pdf',type=click.Path(exists=True),required=True,- help="本地 PDF 文件",+ help='本地 PDF 文件',)@click.option(- "-j",- "--json",- "json_data",+ '-j',+ '--json',+ 'json_data',type=click.Path(exists=True),required=True,- help="本地模型推理出的 json 数据",-)- "-o", "--output-dir", "output_dir", type=str, help="本地输出目录", default=""+ help='本地模型推理出的 json 数据',)[email protected]('-o',+ '--output-dir',+ 'output_dir',+ type=click.Path(),+ required=True,+ help='本地输出目录')@click.option(- "-m",- "--method",- "method",+ '-m',+ '--method',+ 'method',type=parse_pdf_methods,- help="指定解析方法。txt: 文本型 pdf 解析方法, ocr: 光学识别解析 pdf, auto: 程序智能选择解析方法",- default="auto",+ help='指定解析方法。txt: 文本型 pdf 解析方法, ocr: 光学识别解析 pdf, auto: 程序智能选择解析方法',+ default='auto',)def pdf(pdf, json_data, output_dir, method):model_config.__use_inside_model__ = Falsefull_pdf_path = os.path.realpath(pdf)- if output_dir == "":- output_dir = os.path.join(os.path.dirname(full_pdf_path), "output")+ os.makedirs(output_dir, exist_ok=True)def read_fn(path):disk_rw = DiskReaderWriter(os.path.dirname(path))return disk_rw.read(os.path.basename(path), AbsReaderWriter.MODE_BIN)- model_json_list = json_parse.loads(read_fn(json_data).decode("utf-8"))+ model_json_list = json_parse.loads(read_fn(json_data).decode('utf-8'))file_name = str(Path(full_pdf_path).stem)pdf_data = read_fn(full_pdf_path)@@ -146,10 +142,11 @@ def pdf(pdf, json_data, output_dir, method):pdf_data,model_json_list,method,+ False,f_dump_content_list=True,f_draw_model_bbox=True,)-if __name__ == "__main__":+if __name__ == '__main__':cli()diff --git a/magic_pdf/tools/common.py b/magic_pdf/tools/common.pyindex 6ddea698..6d7a381b 100644--- a/magic_pdf/tools/common.py+++ b/magic_pdf/tools/common.py@@ -1,22 +1,25 @@-import os-import json as json_parseimport copy+import json as json_parse+import os+import clickfrom loguru import logger++import magic_pdf.model as model_config+from magic_pdf.libs.draw_bbox import (draw_layout_bbox, draw_span_bbox,+ drow_model_bbox)from magic_pdf.libs.MakeContentConfig import DropMode, MakeMode-from magic_pdf.libs.draw_bbox import draw_layout_bbox, draw_span_bbox, drow_model_bbox-from magic_pdf.pipe.UNIPipe import UNIPipefrom magic_pdf.pipe.OCRPipe import OCRPipefrom magic_pdf.pipe.TXTPipe import TXTPipe-from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter+from magic_pdf.pipe.UNIPipe import UNIPipefrom magic_pdf.rw.AbsReaderWriter import AbsReaderWriter-import magic_pdf.model as model_config+from magic_pdf.rw.DiskReaderWriter import DiskReaderWriterdef prepare_env(output_dir, pdf_file_name, method):local_parent_dir = os.path.join(output_dir, pdf_file_name, method)- local_image_dir = os.path.join(str(local_parent_dir), "images")+ local_image_dir = os.path.join(str(local_parent_dir), 'images')local_md_dir = local_parent_diros.makedirs(local_image_dir, exist_ok=True)os.makedirs(local_md_dir, exist_ok=True)@@ -29,6 +32,7 @@ def do_parse(pdf_bytes,model_list,parse_method,+ debug_able,f_draw_span_bbox=True,f_draw_layout_bbox=True,f_dump_md=True,@@ -38,24 +42,34 @@ def do_parse(f_dump_content_list=False,f_make_md_mode=MakeMode.MM_MD,f_draw_model_bbox=False,+ start_page_id=0,+ end_page_id=None,):+ if debug_able:+ logger.warning("debug mode is on")+ f_dump_content_list = True+ f_draw_model_bbox = True+orig_model_list = copy.deepcopy(model_list)- local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, parse_method)+ local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name,+ parse_method)- image_writer, md_writer = DiskReaderWriter(local_image_dir), DiskReaderWriter(- local_md_dir- )+ image_writer, md_writer = DiskReaderWriter(+ local_image_dir), DiskReaderWriter(local_md_dir)image_dir = str(os.path.basename(local_image_dir))- if parse_method == "auto":- jso_useful_key = {"_pdf_type": "", "model_list": model_list}- pipe = UNIPipe(pdf_bytes, jso_useful_key, image_writer, is_debug=True)- elif parse_method == "txt":- pipe = TXTPipe(pdf_bytes, model_list, image_writer, is_debug=True)- elif parse_method == "ocr":- pipe = OCRPipe(pdf_bytes, model_list, image_writer, is_debug=True)+ if parse_method == 'auto':+ jso_useful_key = {'_pdf_type': '', 'model_list': model_list}+ pipe = UNIPipe(pdf_bytes, jso_useful_key, image_writer, is_debug=True,+ start_page_id=start_page_id, end_page_id=end_page_id)+ elif parse_method == 'txt':+ pipe = TXTPipe(pdf_bytes, model_list, image_writer, is_debug=True,+ start_page_id=start_page_id, end_page_id=end_page_id)+ elif parse_method == 'ocr':+ pipe = OCRPipe(pdf_bytes, model_list, image_writer, is_debug=True,+ start_page_id=start_page_id, end_page_id=end_page_id)else:- logger.error("unknown parse method")+ logger.error('unknown parse method')exit(1)pipe.pipe_classify()@@ -65,58 +79,64 @@ def do_parse(pipe.pipe_analyze()orig_model_list = copy.deepcopy(pipe.model_list)else:- logger.error("need model list input")+ logger.error('need model list input')exit(2)pipe.pipe_parse()- pdf_info = pipe.pdf_mid_data["pdf_info"]+ pdf_info = pipe.pdf_mid_data['pdf_info']if f_draw_layout_bbox:- draw_layout_bbox(pdf_info, pdf_bytes, local_md_dir)+ draw_layout_bbox(pdf_info, pdf_bytes, local_md_dir, pdf_file_name)if f_draw_span_bbox:- draw_span_bbox(pdf_info, pdf_bytes, local_md_dir)+ draw_span_bbox(pdf_info, pdf_bytes, local_md_dir, pdf_file_name)if f_draw_model_bbox:- drow_model_bbox(orig_model_list, pdf_bytes, local_md_dir)+ drow_model_bbox(copy.deepcopy(orig_model_list), pdf_bytes, local_md_dir, pdf_file_name)- md_content = pipe.pipe_mk_markdown(- image_dir, drop_mode=DropMode.NONE, md_make_mode=f_make_md_mode- )+ md_content = pipe.pipe_mk_markdown(image_dir,+ drop_mode=DropMode.NONE,+ md_make_mode=f_make_md_mode)if f_dump_md:md_writer.write(content=md_content,- path=f"{pdf_file_name}.md",+ path=f'{pdf_file_name}.md',mode=AbsReaderWriter.MODE_TXT,)if f_dump_middle_json:md_writer.write(- content=json_parse.dumps(pipe.pdf_mid_data, ensure_ascii=False, indent=4),- path="middle.json",+ content=json_parse.dumps(pipe.pdf_mid_data,+ ensure_ascii=False,+ indent=4),+ path=f'{pdf_file_name}_middle.json',mode=AbsReaderWriter.MODE_TXT,)if f_dump_model_json:md_writer.write(- content=json_parse.dumps(orig_model_list, ensure_ascii=False, indent=4),- path="model.json",+ content=json_parse.dumps(orig_model_list,+ ensure_ascii=False,+ indent=4),+ path=f'{pdf_file_name}_model.json',mode=AbsReaderWriter.MODE_TXT,)if f_dump_orig_pdf:md_writer.write(content=pdf_bytes,- path="origin.pdf",+ path=f'{pdf_file_name}_origin.pdf',mode=AbsReaderWriter.MODE_BIN,)content_list = pipe.pipe_mk_uni_format(image_dir, drop_mode=DropMode.NONE)if f_dump_content_list:md_writer.write(- content=json_parse.dumps(content_list, ensure_ascii=False, indent=4),- path="content_list.json",+ content=json_parse.dumps(content_list,+ ensure_ascii=False,+ indent=4),+ path=f'{pdf_file_name}_content_list.json',mode=AbsReaderWriter.MODE_TXT,)- logger.info(f"local output dir is {local_md_dir}")+ logger.info(f'local output dir is {local_md_dir}')-parse_pdf_methods = click.Choice(["ocr", "txt", "auto"])+parse_pdf_methods = click.Choice(['ocr', 'txt', 'auto'])diff --git a/magic_pdf/user_api.py b/magic_pdf/user_api.pyindex bf364772..45f02c82 100644--- a/magic_pdf/user_api.py+++ b/magic_pdf/user_api.py@@ -25,8 +25,9 @@ PARSE_TYPE_TXT = "txt"PARSE_TYPE_OCR = "ocr"-def parse_txt_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWriter, is_debug=False, start_page=0, *args,- **kwargs):+def parse_txt_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWriter, is_debug=False,+ start_page_id=0, end_page_id=None,+ *args, **kwargs):"""解析文本类pdf"""@@ -34,7 +35,8 @@ def parse_txt_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWritpdf_bytes,pdf_models,imageWriter,- start_page_id=start_page,+ start_page_id=start_page_id,+ end_page_id=end_page_id,debug_mode=is_debug,)@@ -45,8 +47,9 @@ def parse_txt_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWritreturn pdf_info_dict-def parse_ocr_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWriter, is_debug=False, start_page=0, *args,- **kwargs):+def parse_ocr_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWriter, is_debug=False,+ start_page_id=0, end_page_id=None,+ *args, **kwargs):"""解析ocr类pdf"""@@ -54,7 +57,8 @@ def parse_ocr_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWritpdf_bytes,pdf_models,imageWriter,- start_page_id=start_page,+ start_page_id=start_page_id,+ end_page_id=end_page_id,debug_mode=is_debug,)@@ -65,8 +69,9 @@ def parse_ocr_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWritreturn pdf_info_dict-def parse_union_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWriter, is_debug=False, start_page=0,+def parse_union_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWriter, is_debug=False,input_model_is_empty: bool = False,+ start_page_id=0, end_page_id=None,*args, **kwargs):"""ocr和文本混合的pdf,全部解析出来@@ -78,7 +83,8 @@ def parse_union_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWrpdf_bytes,pdf_models,imageWriter,- start_page_id=start_page,+ start_page_id=start_page_id,+ end_page_id=end_page_id,debug_mode=is_debug,)except Exception as e:@@ -89,7 +95,9 @@ def parse_union_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWrif pdf_info_dict is None or pdf_info_dict.get("_need_drop", False):logger.warning(f"parse_pdf_by_txt drop or error, switch to parse_pdf_by_ocr")if input_model_is_empty:- pdf_models = doc_analyze(pdf_bytes, ocr=True)+ pdf_models = doc_analyze(pdf_bytes, ocr=True,+ start_page_id=start_page_id,+ end_page_id=end_page_id)pdf_info_dict = parse_pdf(parse_pdf_by_ocr)if pdf_info_dict is None:raise Exception("Both parse_pdf_by_txt and parse_pdf_by_ocr failed.")diff --git a/projects/README.md b/projects/README.mdnew file mode 100644index 00000000..f7c1631b--- /dev/null+++ b/projects/README.md@@ -0,0 +1,5 @@+# Welcome to the MinerU Project List++## Project List++- [llama_index_rag](./llama_index_rag/README.md): Build a lightweight RAG system based on llama_indexdiff --git a/projects/README_zh-CN.md b/projects/README_zh-CN.mdnew file mode 100644index 00000000..6e9dc7a3--- /dev/null+++ b/projects/README_zh-CN.md@@ -0,0 +1,5 @@+# 欢迎来到 MinerU 项目列表++## 项目列表++- [llama_index_rag](./llama_index_rag/README_zh-CN.md): 基于 llama_index 构建轻量级 RAG 系统diff --git a/projects/llama_index_rag/README.md b/projects/llama_index_rag/README.mdnew file mode 100644index 00000000..57cd9aeb--- /dev/null+++ b/projects/llama_index_rag/README.md@@ -0,0 +1,160 @@+## Installation++MinerU++```bash+git clone https://github.com/opendatalab/MinerU.git+cd MinerU++conda create -n MinerU python=3.10+conda activate MinerU+pip install .[full] --extra-index-url https://wheels.myhloli.com+```++Third-party software++```bash+# install+pip install llama-index-vector-stores-elasticsearch==0.2.0+pip install llama-index-embeddings-dashscope==0.2.0+pip install llama-index-core==0.10.68+pip install einops==0.7.0+pip install transformers-stream-generator==0.0.5+pip install accelerate==0.33.0++# uninstall+pip uninstall transformer-engine+```++## Environment Configuration++```+export DASHSCOPE_API_KEY={some_key}+export ES_USER={some_es_user}+export ES_PASSWORD={some_es_password}+export ES_URL=http://{es_url}:9200+```+For instructions on obtaining a DASHSCOPE_API_KEY, refer to [documentation](https://help.aliyun.com/zh/dashscope/opening-service)++## Usage++### Data Ingestion++```bash+python data_ingestion.py -p some.pdf # load data from pdf++ or++python data_ingestion.py -p /opt/data/some_pdf_directory/ # load data from multiples pdf which under the directory of {some_pdf_directory}+```++### Query++```bash+python query.py --question '{the_question_you_want_to_ask}'+```++## Example++````bash+# Start the es service+docker compose up -d++or++docker-compose up -d+++# Set environment variables+export ES_USER=elastic+export ES_PASSWORD=llama_index+export ES_URL=http://127.0.0.1:9200+export DASHSCOPE_API_KEY={some_key}+++# Ingest data+python data_ingestion.py example/data/declaration_of_the_rights_of_man_1789.pdf+++# Ask a question+python query.py -q 'how about the rights of men'++## outputs+Please answer the question based on the content within ```:+ ```+ I. Men are born, and always continue, free and equal in respect of their rights. Civil distinctions, therefore, can be founded only on public utility.+ ```+ My question is:how about the rights of men。++question: how about the rights of men+answer: The statement implies that men are born free and equal in terms of their rights. Civil distinctions should only be based on public utility. However, it does not specify what those rights are. It is up to society and individual countries to determine and protect the specific rights of their citizens.++````++## Development++`MinerU` provides a `RAG` integration interface, allowing users to specify a single input `pdf` file or a directory. `MinerU` will automatically parse the input files and return an iterable interface for retrieving the data.+++### API Interface++```python+from magic_pdf.integrations.rag.type import Node++class RagPageReader:+ def get_rel_map(self) -> list[ElementRelation]:+ # Retrieve the relationships between nodes+ pass+ ...++class RagDocumentReader:+ ...++class DataReader:+ def __init__(self, path_or_directory: str, method: str, output_dir: str):+ pass++ def get_documents_count(self) -> int:+ """Get the number of pdf documents"""+ pass++ def get_document_result(self, idx: int) -> RagDocumentReader | None:+ """Retrieve the parsed content of a specific pdf"""+ pass+++ def get_document_filename(self, idx: int) -> Path:+ """Retrieve the path of a specific pdf"""+ pass+++```++Type Definitions++```python+++class Node(BaseModel):+ category_type: CategoryType = Field(description='Category') # Category+ text: str | None = Field(description='Text content', default=None)+ image_path: str | None = Field(description='Path to image or table (table may be stored as an image)', default=None)+ anno_id: int = Field(description='Unique ID', default=-1)+ latex: str | None = Field(description='LaTeX output for equations or tables', default=None)+ html: str | None = Field(description='HTML output for tables', default=None)++++```++Tables can be stored in one of three formats: image, LaTeX, or HTML.+`anno_id` is a globally unique ID for each Node. It can be used later to match this Node with other Nodes. The relationships between nodes can be retrieved using the `get_rel_map` method. Users can use `anno_id` to link nodes and construct a RAG index that includes node relationships.+++### Node Relationship Matrix++| | image_body | table_body |+| -------------- | ---------- | ---------- |+| image_caption | sibling | |+| table_caption | | sibling |+| table_footnote | | sibling |diff --git a/projects/llama_index_rag/README_zh-CN.md b/projects/llama_index_rag/README_zh-CN.mdnew file mode 100644index 00000000..a54c5c1f--- /dev/null+++ b/projects/llama_index_rag/README_zh-CN.md@@ -0,0 +1,194 @@+<details open="open">+ <summary><h2 style="display: inline-block">目录</h2></summary>+ <li><a href="#介绍">介绍</a></li>+ <li><a href="#安装">安装</a></li>+ <li><a href="#示例">示例</a></li>+ <li><a href="#开发">开发</a></li>+ </ol>+</details>++## 介绍++`MinerU` 提供数据 `API接口` 以支持用户导入数据到 `RAG` 系统。本项目将基于`通义千问`展示如何构建一个轻量级的 `RAG` 系统。++<p align="center">+ <img src="rag_data_api.png" width="300px" style="vertical-align:middle;">+</p>++## 安装++环境要求++```text+NVIDIA A100 80GB,+Centos 7 3.10.0-957.el7.x86_64++Client: Docker Engine - Community+ Version: 24.0.5+ API version: 1.43+ Go version: go1.20.6+ Git commit: ced0996+ Built: Fri Jul 21 20:39:02 2023+ OS/Arch: linux/amd64+ Context: default++Server: Docker Engine - Community+ Engine:+ Version: 24.0.5+ API version: 1.43 (minimum version 1.12)+ Go version: go1.20.6+ Git commit: a61e2b4+ Built: Fri Jul 21 20:38:05 2023+ OS/Arch: linux/amd64+ Experimental: false+ containerd:+ Version: 1.6.25+ GitCommit: d8f198a4ed8892c764191ef7b3b06d8a2eeb5c7f+ runc:+ Version: 1.1.10+ GitCommit: v1.1.10-0-g18a0cb0+ docker-init:+ Version: 0.19.0+ GitCommit: de40ad0+```++请参考[文档](../../README_zh-CN.md) 安装 MinerU++第三方软件++```bash+# install+pip install modelscope==1.14.0+pip install llama-index-vector-stores-elasticsearch==0.2.0+pip install llama-index-embeddings-dashscope==0.2.0+pip install llama-index-core==0.10.68+pip install einops==0.7.0+pip install transformers-stream-generator==0.0.5+pip install accelerate==0.33.0++# uninstall+pip uninstall transformer-engine+```++## 示例++````bash+cd projects/llama_index_rag++docker compose up -d++or++docker-compose up -d+++export ES_USER=elastic+export ES_PASSWORD=llama_index+export ES_URL=http://127.0.0.1:9200+export DASHSCOPE_API_KEY={some_key}++DASHSCOPE_API_KEY 开通参考[文档](https://help.aliyun.com/zh/dashscope/opening-service)++# 未导入数据,查询问题。返回通义千问默认答案+python query.py -q 'how about the rights of men'++## outputs+question: how about the rights of men+answer: The topic of men's rights often refers to discussions around legal, social, and political issues that affect men specifically or differently from women. Movements related to men's rights advocate for addressing areas where men face discrimination or unique challenges, such as:++ Child Custody: Ensuring that men have equal opportunities for custody of their children following divorce or separation.+ Domestic Violence: Recognizing that men can also be victims of domestic abuse and ensuring they have access to support services.+ Mental Health and Suicide Rates: Addressing the higher rates of suicide among men and providing mental health resources.+ Military Conscription: In some countries, only men are required to register for military service, which is seen as a gender-based obligation.+ Workplace Safety: Historically, more men than women have been employed in high-risk occupations, leading to higher workplace injury and death rates.+ Parental Leave: Advocating for paternity leave policies that allow men to take time off work for family care.+ Men's rights activism often intersects with broader discussions on gender equality and aims to promote fairness and equity across genders. It's important to note that while advocating for these issues, it should be done in a way that does not detract from or oppose the goals of gender equality and the rights of other groups. The focus should be on creating a fair society where everyone has equal opportunities and protections under the law.+++# 导入数据+python data_ingestion.py -p example/data/++or++python data_ingestion.py -p example/data/declaration_of_the_rights_of_man_1789.pdf+++# 导入数据后,查询问题。通义千问模型会根据 RAG 系统的检索结果,结合上下文,给出答案。+python query.py -q 'how about the rights of men'++## outputs+请基于```内的内容回答问题。"+ ```+ I. Men are born, and always continue, free and equal in respect of their rights. Civil distinctions, therefore, can be founded only on public utility.+ ```+ 我的问题是:how about the rights of men。++question: how about the rights of men+answer: The statement implies that men are born free and equal in terms of their rights. Civil distinctions should only be based on public utility. However, it does not specify what those rights are. It is up to society and individual countries to determine and protect the specific rights of their citizens.++````++## 开发++`MinerU` 提供了 `RAG` 集成接口,用户可以通过指定输入单个 `pdf` 文件或者某个目录。`MinerU` 会自动解析输入文件并返回可以迭代的接口用于获取数据++### API 接口++```python+from magic_pdf.integrations.rag.type import Node++class RagPageReader:+ def get_rel_map(self) -> list[ElementRelation]:+ # 获取节点间的关系+ pass+ ...++class RagDocumentReader:+ ...++class DataReader:+ def __init__(self, path_or_directory: str, method: str, output_dir: str):+ pass++ def get_documents_count(self) -> int:+ """获取 pdf 文档数量"""+ pass++ def get_document_result(self, idx: int) -> RagDocumentReader | None:+ """获取某个 pdf 的解析内容"""+ pass+++ def get_document_filename(self, idx: int) -> Path:+ """获取某个 pdf 的具体路径"""+ pass+++```++类型定义++```python++class Node(BaseModel):+ category_type: CategoryType = Field(description='类别') # 类别+ text: str | None = Field(description='文本内容',+ default=None)+ image_path: str | None = Field(description='图或者表格(表可能用图片形式存储)的存储路径',+ default=None)+ anno_id: int = Field(description='unique id', default=-1)+ latex: str | None = Field(description='公式或表格 latex 解析结果', default=None)+ html: str | None = Field(description='表格的 html 解析结果', default=None)++```++表格存储形式可能会是 图片、latex、html 三种形式之一。+anno_id 是该 Node 的在全局唯一ID。后续可以用于匹配该 Node 和其他 Node 的关系。节点的关系可以通过方法 `get_rel_map` 获取。用户可以用 `anno_id` 匹配节点之间的关系,并用于构建具备节点的关系的 rag index。++### 节点类型关系矩阵++| | image_body | table_body |+| -------------- | ---------- | ---------- |+| image_caption | sibling | |+| table_caption | | sibling |+| table_footnote | | sibling |diff --git a/projects/llama_index_rag/data_ingestion.py b/projects/llama_index_rag/data_ingestion.pynew file mode 100644index 00000000..821a1081--- /dev/null+++ b/projects/llama_index_rag/data_ingestion.py@@ -0,0 +1,68 @@+import os++import click+from llama_index.core.schema import TextNode+from llama_index.embeddings.dashscope import (DashScopeEmbedding,+ DashScopeTextEmbeddingModels,+ DashScopeTextEmbeddingType)+from llama_index.vector_stores.elasticsearch import ElasticsearchStore++from magic_pdf.integrations.rag.api import DataReader++es_vec_store = ElasticsearchStore(+ index_name='rag_index',+ es_url=os.getenv('ES_URL', 'http://127.0.0.1:9200'),+ es_user=os.getenv('ES_USER', 'elastic'),+ es_password=os.getenv('ES_PASSWORD', 'llama_index'),+)+++# Create embeddings+# text_type=`document` to build index+def embed_node(node):+ embedder = DashScopeEmbedding(+ model_name=DashScopeTextEmbeddingModels.TEXT_EMBEDDING_V2,+ text_type=DashScopeTextEmbeddingType.TEXT_TYPE_DOCUMENT,+ )++ result_embeddings = embedder.get_text_embedding(node.text)+ node.embedding = result_embeddings+ return node+++ '-p',+ '--path',+ 'path',+ type=click.Path(exists=True),+ required=True,+ help='local pdf filepath or directory',+)+def cli(path):+ output_dir = '/tmp/magic_pdf/integrations/rag/'+ os.makedirs(output_dir, exist_ok=True)+ documents = DataReader(path, 'ocr', output_dir)++ # build nodes+ nodes = []++ for idx in range(documents.get_documents_count()):+ doc = documents.get_document_result(idx)+ if doc is None: # something wrong happens when parse pdf !+ continue++ for page in iter(+ doc): # iterate documents from initial page to last page !+ for element in iter(page): # iterate the element from all page !+ if element.text is None:+ continue+ nodes.append(+ embed_node(+ TextNode(text=element.text,+ metadata={'purpose': 'demo'})))+ es_vec_store.add(nodes)+++if __name__ == '__main__':+ cli()diff --git a/projects/llama_index_rag/docker-compose.yml b/projects/llama_index_rag/docker-compose.ymlnew file mode 100644index 00000000..b6dc24d6--- /dev/null+++ b/projects/llama_index_rag/docker-compose.yml@@ -0,0 +1,24 @@+services:+ es:+ container_name: es+ image: docker.elastic.co/elasticsearch/elasticsearch:8.11.3+ volumes:+ - esdata01:/usr/share/elasticsearch/data+ ports:+ - 9200:9200+ environment:+ - node.name=es+ - ELASTIC_PASSWORD=llama_index+ - bootstrap.memory_lock=false+ - discovery.type=single-node+ - xpack.security.enabled=true+ - xpack.security.http.ssl.enabled=false+ - xpack.security.transport.ssl.enabled=false+ ulimits:+ memlock:+ soft: -1+ hard: -1+ restart: always+volumes:+ esdata01:+ driver: localdiff --git a/projects/llama_index_rag/example/data/declaration_of_the_rights_of_man_1789.pdf b/projects/llama_index_rag/example/data/declaration_of_the_rights_of_man_1789.pdfnew file mode 100644index 00000000..eff02687Binary files /dev/null and b/projects/llama_index_rag/example/data/declaration_of_the_rights_of_man_1789.pdf differdiff --git a/projects/llama_index_rag/query.py b/projects/llama_index_rag/query.pynew file mode 100644index 00000000..64151dae--- /dev/null+++ b/projects/llama_index_rag/query.py@@ -0,0 +1,84 @@+import os++import click+from llama_index.core.vector_stores.types import VectorStoreQuery+from llama_index.embeddings.dashscope import (DashScopeEmbedding,+ DashScopeTextEmbeddingModels,+ DashScopeTextEmbeddingType)+from llama_index.vector_stores.elasticsearch import (AsyncDenseVectorStrategy,+ ElasticsearchStore)+# initialize qwen 7B model+from modelscope import AutoModelForCausalLM, AutoTokenizer, GenerationConfig++es_vector_store = ElasticsearchStore(+ index_name='rag_index',+ es_url=os.getenv('ES_URL', 'http://127.0.0.1:9200'),+ es_user=os.getenv('ES_USER', 'elastic'),+ es_password=os.getenv('ES_PASSWORD', 'llama_index'),+ retrieval_strategy=AsyncDenseVectorStrategy(),+)+++def embed_text(text):+ embedder = DashScopeEmbedding(+ model_name=DashScopeTextEmbeddingModels.TEXT_EMBEDDING_V2,+ text_type=DashScopeTextEmbeddingType.TEXT_TYPE_DOCUMENT,+ )+ return embedder.get_text_embedding(text)+++def search(vector_store: ElasticsearchStore, query: str):+ query_vec = VectorStoreQuery(query_embedding=embed_text(query))+ result = vector_store.query(query_vec)+ return '\n'.join([node.text for node in result.nodes])+++ '-q',+ '--question',+ 'question',+ required=True,+ help='ask what you want to know!',+)+def cli(question):+ tokenizer = AutoTokenizer.from_pretrained('qwen/Qwen-7B-Chat',+ revision='v1.0.5',+ trust_remote_code=True)+ model = AutoModelForCausalLM.from_pretrained('qwen/Qwen-7B-Chat',+ revision='v1.0.5',+ device_map='auto',+ trust_remote_code=True,+ fp32=True).eval()+ model.generation_config = GenerationConfig.from_pretrained(+ 'Qwen/Qwen-7B-Chat', revision='v1.0.5', trust_remote_code=True)++ # define a prompt template for the vectorDB-enhanced LLM generation+ def answer_question(question, context, model):+ if context == '':+ prompt = question+ else:+ prompt = f'''请基于```内的内容回答问题。"+ ```+ {context}+ ```+ 我的问题是:{question}。+ '''+ history = None+ print(prompt)+ response, history = model.chat(tokenizer, prompt, history=None)+ return response++ answer = answer_question(question, search(es_vector_store, question),+ model)+ print(f'question: {question}\n'+ f'answer: {answer}')+++"""++python query.py -q 'how about the rights of men'+"""++if __name__ == '__main__':+ cli()diff --git a/projects/llama_index_rag/rag_data_api.png b/projects/llama_index_rag/rag_data_api.pngnew file mode 100644index 00000000..0aa4b2e5Binary files /dev/null and b/projects/llama_index_rag/rag_data_api.png differdiff --git a/requirements-qa.txt b/requirements-qa.txtindex 5c9dd1e3..56b2dbea 100644--- a/requirements-qa.txt+++ b/requirements-qa.txt@@ -14,4 +14,6 @@ tqdmhtmltabletomdpypandocpyopenssl==24.0.0-struct-eqtable==0.1.0\ No newline at end of file+struct-eqtable==0.1.0+pytest-cov+beautifulsoup4\ No newline at end of filediff --git a/requirements.txt b/requirements.txtindex ff17e4b6..4e6a0f94 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,11 +1,12 @@boto3>=1.28.43Brotli>=1.1.0click>=8.1.7-PyMuPDF>=1.24.9+fast-langdetect==0.2.0loguru>=0.6.0numpy>=1.21.6,<2.0.0-fast-langdetect==0.2.0-wordninja>=2.0.0-scikit-learn>=1.0.2pdfminer.six==20231228+pydantic>=2.7.2,<2.8.0+PyMuPDF>=1.24.9+scikit-learn>=1.0.2+wordninja>=2.0.0# The requirements.txt must ensure that only necessary external dependencies are introduced. If there are new dependencies to add, please contact the project administrator.diff --git a/tests/get_coverage.py b/tests/get_coverage.pynew file mode 100644index 00000000..765f6e19--- /dev/null+++ b/tests/get_coverage.py@@ -0,0 +1,22 @@+"""+get cov+"""+from bs4 import BeautifulSoup++def get_covrage():+ """get covrage"""+ # 发送请求获取网页内容+ html_content = open("htmlcov/index.html", "r", encoding="utf-8").read()+ soup = BeautifulSoup(html_content, 'html.parser')++ # 查找包含"pc_cov"的span标签+ pc_cov_span = soup.find('span', class_='pc_cov')++ # 提取百分比值+ percentage_value = pc_cov_span.text.strip()+ percentage_float = float(percentage_value.rstrip('%'))+ print ("percentage_float:", percentage_float)+ assert percentage_float >= 0.2++if __name__ == '__main__':+ get_covrage()\ No newline at end of filediff --git a/tests/pdf_indicator/overall_indicator.py b/tests/pdf_indicator/overall_indicator.pydeleted file mode 100644index e46f7b46..00000000--- a/tests/pdf_indicator/overall_indicator.py+++ /dev/null@@ -1,456 +0,0 @@-import json-import pandas as pd-import numpy as np-from nltk.translate.bleu_score import sentence_bleu-import argparse-from sklearn.metrics import classification_report-from collections import Counter-from sklearn import metrics-from pandas import isnull----def indicator_cal(json_standard,json_test):-- json_standard = pd.DataFrame(json_standard)- json_test = pd.DataFrame(json_test)---- '''数据集总体指标'''-- a=json_test[['id','mid_json']]- b=json_standard[['id','mid_json','pass_label']]-- a=a.drop_duplicates(subset='id',keep='first')- a.index=range(len(a))- b=b.drop_duplicates(subset='id',keep='first')- b.index=range(len(b))-- outer_merge=pd.merge(a,b,on='id',how='outer')- outer_merge.columns=['id','standard_mid_json','test_mid_json','pass_label']- standard_exist=outer_merge.standard_mid_json.apply(lambda x: not isnull(x))- test_exist=outer_merge.test_mid_json.apply(lambda x: not isnull(x))-- overall_report = {}- overall_report['accuracy']=metrics.accuracy_score(standard_exist,test_exist)- overall_report['precision']=metrics.precision_score(standard_exist,test_exist)- overall_report['recall']=metrics.recall_score(standard_exist,test_exist)- overall_report['f1_score']=metrics.f1_score(standard_exist,test_exist)--- inner_merge=pd.merge(a,b,on='id',how='inner')- inner_merge.columns=['id','standard_mid_json','test_mid_json','pass_label']- json_standard = inner_merge['standard_mid_json']#check一下是否对齐- json_test = inner_merge['test_mid_json']----- '''批量读取中间生成的json文件'''- test_inline_equations=[]- test_interline_equations=[]- test_inline_euqations_bboxs=[]- test_interline_equations_bboxs=[]- test_dropped_text_bboxes=[]- test_dropped_text_tag=[]- test_dropped_image_bboxes=[]- test_dropped_table_bboxes=[]- test_preproc_num=[]#阅读顺序- test_para_num=[]- test_para_text=[]-- for i in json_test:- mid_json=pd.DataFrame(i)- mid_json=mid_json.iloc[:,:-1]- for j1 in mid_json.loc['inline_equations',:]:- page_in_text=[]- page_in_bbox=[]- for k1 in j1:- page_in_text.append(k1['latex_text'])- page_in_bbox.append(k1['bbox'])- test_inline_equations.append(page_in_text)- test_inline_euqations_bboxs.append(page_in_bbox)- for j2 in mid_json.loc['interline_equations',:]:- page_in_text=[]- page_in_bbox=[]- for k2 in j2:- page_in_text.append(k2['latex_text'])- page_in_bbox.append(k2['bbox'])- test_interline_equations.append(page_in_text)- test_interline_equations_bboxs.append(page_in_bbox)-- for j3 in mid_json.loc['droped_text_block',:]:- page_in_bbox=[]- page_in_tag=[]- for k3 in j3:- page_in_bbox.append(k3['bbox'])- #如果k3中存在tag这个key- if 'tag' in k3.keys():- page_in_tag.append(k3['tag'])- else:- page_in_tag.append('None')- test_dropped_text_tag.append(page_in_tag)- test_dropped_text_bboxes.append(page_in_bbox)- for j4 in mid_json.loc['droped_image_block',:]:- test_dropped_image_bboxes.append(j4)- for j5 in mid_json.loc['droped_table_block',:]:- test_dropped_table_bboxes.append(j5)- for j6 in mid_json.loc['preproc_blocks',:]:- page_in=[]- for k6 in j6:- page_in.append(k6['number'])- test_preproc_num.append(page_in)-- test_pdf_text=[]- for j7 in mid_json.loc['para_blocks',:]:- test_para_num.append(len(j7))- for k7 in j7:- test_pdf_text.append(k7['text'])- test_para_text.append(test_pdf_text)---- standard_inline_equations=[]- standard_interline_equations=[]- standard_inline_euqations_bboxs=[]- standard_interline_equations_bboxs=[]- standard_dropped_text_bboxes=[]- standard_dropped_text_tag=[]- standard_dropped_image_bboxes=[]- standard_dropped_table_bboxes=[]- standard_preproc_num=[]#阅读顺序- standard_para_num=[]- standard_para_text=[]-- for i in json_standard:- mid_json=pd.DataFrame(i)- mid_json=mid_json.iloc[:,:-1]- for j1 in mid_json.loc['inline_equations',:]:- page_in_text=[]- page_in_bbox=[]- for k1 in j1:- page_in_text.append(k1['latex_text'])- page_in_bbox.append(k1['bbox'])- standard_inline_equations.append(page_in_text)- standard_inline_euqations_bboxs.append(page_in_bbox)- for j2 in mid_json.loc['interline_equations',:]:- page_in_text=[]- page_in_bbox=[]- for k2 in j2:- page_in_text.append(k2['latex_text'])- page_in_bbox.append(k2['bbox'])- standard_interline_equations.append(page_in_text)- standard_interline_equations_bboxs.append(page_in_bbox)- for j3 in mid_json.loc['droped_text_block',:]:- page_in_bbox=[]- page_in_tag=[]- for k3 in j3:- page_in_bbox.append(k3['bbox'])- if 'tag' in k3.keys():- page_in_tag.append(k3['tag'])- else:- page_in_tag.append('None')- standard_dropped_text_bboxes.append(page_in_bbox)- standard_dropped_text_tag.append(page_in_tag)- for j4 in mid_json.loc['droped_image_block',:]:- standard_dropped_image_bboxes.append(j4)- for j5 in mid_json.loc['droped_table_block',:]:- standard_dropped_table_bboxes.append(j5)- for j6 in mid_json.loc['preproc_blocks',:]:- page_in=[]- for k6 in j6:- page_in.append(k6['number'])- standard_preproc_num.append(page_in)-- standard_pdf_text=[]- for j7 in mid_json.loc['para_blocks',:]:- standard_para_num.append(len(j7))- for k7 in j7:- standard_pdf_text.append(k7['text'])- standard_para_text.append(standard_pdf_text)--- """- 在计算指标之前最好先确认基本统计信息是否一致- """--- '''- 计算pdf之间的总体编辑距离和bleu- 这里只计算正例的pdf- '''-- test_para_text=np.asarray(test_para_text, dtype = object)[inner_merge['pass_label']=='yes']- standard_para_text=np.asarray(standard_para_text, dtype = object)[inner_merge['pass_label']=='yes']-- pdf_dis=[]- pdf_bleu=[]- for a,b in zip(test_para_text,standard_para_text):- a1=[ ''.join(i) for i in a]- b1=[ ''.join(i) for i in b]- pdf_dis.append(Levenshtein_Distance(a1,b1))- pdf_bleu.append(sentence_bleu([a1],b1))- overall_report['pdf间的平均编辑距离']=np.mean(pdf_dis)- overall_report['pdf间的平均bleu']=np.mean(pdf_bleu)--- '''行内公式和行间公式的编辑距离和bleu'''- inline_equations_edit_bleu=equations_indicator(test_inline_euqations_bboxs,standard_inline_euqations_bboxs,test_inline_equations,standard_inline_equations)- interline_equations_edit_bleu=equations_indicator(test_interline_equations_bboxs,standard_interline_equations_bboxs,test_interline_equations,standard_interline_equations)-- '''行内公式bbox匹配相关指标'''- inline_equations_bbox_report=bbox_match_indicator(test_inline_euqations_bboxs,standard_inline_euqations_bboxs)-- '''行间公式bbox匹配相关指标'''- interline_equations_bbox_report=bbox_match_indicator(test_interline_equations_bboxs,standard_interline_equations_bboxs)-- '''可以先检查page和bbox数量是否一致'''- '''dropped_text_block的bbox匹配相关指标'''- test_text_bbox=[]- standard_text_bbox=[]- test_tag=[]- standard_tag=[]-- index=0- for a,b in zip(test_dropped_text_bboxes,standard_dropped_text_bboxes):- test_page_tag=[]- standard_page_tag=[]- test_page_bbox=[]- standard_page_bbox=[]- if len(a)==0 and len(b)==0:- pass- else:- for i in range(len(b)):- judge=0- standard_page_tag.append(standard_dropped_text_tag[index][i])- standard_page_bbox.append(1)- for j in range(len(a)):- if bbox_offset(b[i],a[j]):- judge=1- test_page_tag.append(test_dropped_text_tag[index][j])- test_page_bbox.append(1)- break- if judge==0:- test_page_tag.append('None')- test_page_bbox.append(0)--- if len(test_dropped_text_tag[index])+test_page_tag.count('None')>len(standard_dropped_text_tag[index]):#有多删的情况出现- test_page_tag1=test_page_tag.copy()- if 'None' in test_page_tag:- test_page_tag1=test_page_tag1.remove('None')- else:- test_page_tag1=test_page_tag-- diff=list((Counter(test_dropped_text_tag[index]) - Counter(test_page_tag1)).elements())-- test_page_tag.extend(diff)- standard_page_tag.extend(['None']*len(diff))- test_page_bbox.extend([1]*len(diff))- standard_page_bbox.extend([0]*len(diff))-- test_tag.extend(test_page_tag)- standard_tag.extend(standard_page_tag)- test_text_bbox.extend(test_page_bbox)- standard_text_bbox.extend(standard_page_bbox)-- index+=1--- text_block_report = {}- text_block_report['accuracy']=metrics.accuracy_score(standard_text_bbox,test_text_bbox)- text_block_report['precision']=metrics.precision_score(standard_text_bbox,test_text_bbox)- text_block_report['recall']=metrics.recall_score(standard_text_bbox,test_text_bbox)- text_block_report['f1_score']=metrics.f1_score(standard_text_bbox,test_text_bbox)-- '''删除的text_block的tag的准确率,召回率和f1-score'''- text_block_tag_report = classification_report(y_true=standard_tag , y_pred=test_tag,output_dict=True)- del text_block_tag_report['None']- del text_block_tag_report["macro avg"]- del text_block_tag_report["weighted avg"]--- '''dropped_image_block的bbox匹配相关指标'''- '''有数据格式不一致的问题'''- image_block_report=bbox_match_indicator(test_dropped_image_bboxes,standard_dropped_image_bboxes)--- '''dropped_table_block的bbox匹配相关指标'''- table_block_report=bbox_match_indicator(test_dropped_table_bboxes,standard_dropped_table_bboxes)--- '''阅读顺序编辑距离的均值'''- preproc_num_dis=[]- for a,b in zip(test_preproc_num,standard_preproc_num):- preproc_num_dis.append(Levenshtein_Distance(a,b))- preproc_num_edit=np.mean(preproc_num_dis)--- '''分段准确率'''- test_para_num=np.array(test_para_num)- standard_para_num=np.array(standard_para_num)- acc_para=np.mean(test_para_num==standard_para_num)--- output=pd.DataFrame()- output['总体指标']=[overall_report]- output['行内公式平均编辑距离']=[inline_equations_edit_bleu[0]]- output['行内公式平均bleu']=[inline_equations_edit_bleu[1]]- output['行间公式平均编辑距离']=[interline_equations_edit_bleu[0]]- output['行间公式平均bleu']=[interline_equations_edit_bleu[1]]- output['行内公式识别相关指标']=[inline_equations_bbox_report]- output['行间公式识别相关指标']=[interline_equations_bbox_report]- output['阅读顺序平均编辑距离']=[preproc_num_edit]- output['分段准确率']=[acc_para]- output['删除的text block的相关指标']=[text_block_report]- output['删除的image block的相关指标']=[image_block_report]- output['删除的table block的相关指标']=[table_block_report]- output['删除的text block的tag相关指标']=[text_block_tag_report]--- return output----"""-计算编辑距离-"""-def Levenshtein_Distance(str1, str2):- matrix = [[ i + j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)]- for i in range(1, len(str1)+1):- for j in range(1, len(str2)+1):- if(str1[i-1] == str2[j-1]):- d = 0- else:- d = 1- matrix[i][j] = min(matrix[i-1][j]+1, matrix[i][j-1]+1, matrix[i-1][j-1]+d)- return matrix[len(str1)][len(str2)]---'''-计算bbox偏移量是否符合标准的函数-'''-def bbox_offset(b_t,b_s):- '''b_t是test_doc里的bbox,b_s是standard_doc里的bbox'''- x1_t,y1_t,x2_t,y2_t=b_t- x1_s,y1_s,x2_s,y2_s=b_s- x1=max(x1_t,x1_s)- x2=min(x2_t,x2_s)- y1=max(y1_t,y1_s)- y2=min(y2_t,y2_s)- area_overlap=(x2-x1)*(y2-y1)- area_t=(x2_t-x1_t)*(y2_t-y1_t)+(x2_s-x1_s)*(y2_s-y1_s)-area_overlap- if area_t-area_overlap==0 or area_overlap/(area_t-area_overlap)>0.95:- return True- else:- return False---'''bbox匹配和对齐函数,输出相关指标'''-'''输入的是以page为单位的bbox列表'''-def bbox_match_indicator(test_bbox_list,standard_bbox_list):-- test_bbox=[]- standard_bbox=[]- for a,b in zip(test_bbox_list,standard_bbox_list):-- test_page_bbox=[]- standard_page_bbox=[]- if len(a)==0 and len(b)==0:- pass- else:- for i in b:- if len(i)!=4:- continue- else:- judge=0- standard_page_bbox.append(1)- for j in a:- if bbox_offset(i,j):- judge=1- test_page_bbox.append(1)- break- if judge==0:- test_page_bbox.append(0)-- diff_num=len(a)+test_page_bbox.count(0)-len(b)- if diff_num>0:#有多删的情况出现- test_page_bbox.extend([1]*diff_num)- standard_page_bbox.extend([0]*diff_num)--- test_bbox.extend(test_page_bbox)- standard_bbox.extend(standard_page_bbox)--- block_report = {}- block_report['accuracy']=metrics.accuracy_score(standard_bbox,test_bbox)- block_report['precision']=metrics.precision_score(standard_bbox,test_bbox)- block_report['recall']=metrics.recall_score(standard_bbox,test_bbox)- block_report['f1_score']=metrics.f1_score(standard_bbox,test_bbox)-- return block_report--'''公式编辑距离和bleu'''-def equations_indicator(test_euqations_bboxs,standard_euqations_bboxs,test_equations,standard_equations):- test_match_equations=[]- standard_match_equations=[]-- index=0- for a,b in zip(test_euqations_bboxs,standard_euqations_bboxs):- if len(a)==0 and len(b)==0:- pass- else:- for i in range(len(b)):- for j in range(len(a)):- if bbox_offset(b[i],a[j]):- standard_match_equations.append(standard_equations[index][i])- test_match_equations.append(test_equations[index][j])- break- index+=1--- dis=[]- bleu=[]- for a,b in zip(test_match_equations,standard_match_equations):- if len(a)==0 and len(b)==0:- continue- else:- if a==b:- dis.append(0)- bleu.append(1)- else:- dis.append(Levenshtein_Distance(a,b))- bleu.append(sentence_bleu([a],b))-- equations_edit=np.mean(dis)- equations_bleu=np.mean(bleu)- return (equations_edit,equations_bleu)-------parser = argparse.ArgumentParser()-parser.add_argument('--test', type=str)-parser.add_argument('--standard', type=str)-args = parser.parse_args()-pdf_json_test = args.test-pdf_json_standard = args.standard----if __name__ == '__main__':-- pdf_json_test = [json.loads(line)- for line in open(pdf_json_test, 'r', encoding='utf-8')]- pdf_json_standard = [json.loads(line)- for line in open(pdf_json_standard, 'r', encoding='utf-8')]-- overall_indicator=indicator_cal(pdf_json_standard,pdf_json_test)-- '''计算的指标输出到overall_indicator_output.json中'''- overall_indicator.to_json('overall_indicator_output.json',orient='records',lines=True,force_ascii=False)-\ No newline at end of filediff --git a/tests/retry_env.sh b/tests/retry_env.shnew file mode 100644index 00000000..d769a5e5--- /dev/null+++ b/tests/retry_env.sh@@ -0,0 +1,26 @@+#!/bin/bash++# 定义最大重试次数+max_retries=5+retry_count=0++while true; do+ # prepare env+ source activate MinerU+ pip install -r requirements-qa.txt+ pip install magic-pdf[full]==0.7.0b1 --extra-index-url https://wheels.myhloli.com -i https://pypi.tuna.tsinghua.edu.cn/simple+ pip install paddlepaddle-gpu==3.0.0b1 -i https://www.paddlepaddle.org.cn/packages/stable/cu118/+ exit_code=$?+ if [ $exit_code -eq 0 ]; then+ echo "test.sh 成功执行!"+ break+ else+ let retry_count+=1+ if [ $retry_count -ge $max_retries ]; then+ echo "达到最大重试次数 ($max_retries),放弃重试。"+ exit 1+ fi+ echo "test.sh 执行失败 (退出码: $exit_code)。尝试第 $retry_count 次重试..."+ sleep 5 # 等待 5 秒后重试+ fi+donediff --git a/tests/test_cli/lib/common.py b/tests/test_cli/lib/common.pyindex 4fd21f3a..a676aeac 100644--- a/tests/test_cli/lib/common.py+++ b/tests/test_cli/lib/common.py@@ -1,22 +1,43 @@-import subprocess+"""common definitions."""import os+import shutildef check_shell(cmd):- """- shell successful- """+ """shell successful."""res = os.system(cmd)assert res == 0-def count_folders_and_check_contents(file_path):- """"- 获取文件夹大小- """++def cli_count_folders_and_check_contents(file_path):+ """" count cli files."""+ if os.path.exists(file_path):+ for files in os.listdir(file_path):+ folder_count = os.path.getsize(os.path.join(file_path, files))+ assert folder_count > 0+ assert len(os.listdir(file_path)) > 5++def sdk_count_folders_and_check_contents(file_path):+ """count folders."""if os.path.exists(file_path):- folder_count = os.path.getsize(file_path)- assert folder_count > 0+ file_count = os.path.getsize(file_path)+ assert file_count > 0+ else:+ exit(1)-if __name__ == "__main__":- count_folders_and_check_contents("/home/quyuan/code/Magic-PDF/Magic-PDF/Magic-PDF/ci")\ No newline at end of file+def delete_file(path):+ """delete file."""+ if not os.path.exists(path):+ if os.path.isfile(path):+ try:+ os.remove(path)+ print(f"File '{path}' deleted.")+ except TypeError as e:+ print(f"Error deleting file '{path}': {e}")+ elif os.path.isdir(path):+ try:+ shutil.rmtree(path)+ print(f"Directory '{path}' and its contents deleted.")+ except TypeError as e:+ print(f"Error deleting directory '{path}': {e}")\ No newline at end of filediff --git a/tests/test_cli/pdf_dev/academic_literature_0b2c9c91f5232541a7ace8984df306b2_model.json b/tests/test_cli/pdf_dev/academic_literature_0b2c9c91f5232541a7ace8984df306b2_model.jsondeleted file mode 100644index 43e65517..00000000--- a/tests/test_cli/pdf_dev/academic_literature_0b2c9c91f5232541a7ace8984df306b2_model.json+++ /dev/null@@ -1,5315 +0,0 @@-[- {- "layout_dets": [- {- "category_id": 1,- "poly": [- 90.49365997314453,- 948.371826171875,- 259.435546875,- 948.371826171875,- 259.435546875,- 1065.0518798828125,- 90.49365997314453,- 1065.0518798828125- ],- "score": 0.9999996423721313- },- {- "category_id": 1,- "poly": [- 90.44364929199219,- 798.0250244140625,- 420.619873046875,- 798.0250244140625,- 420.619873046875,- 913.686279296875,- 90.44364929199219,- 913.686279296875- ],- "score": 0.9999980926513672- },- {- "category_id": 0,- "poly": [- 91.91043853759766,- 487.7512512207031,- 1292.0186767578125,- 487.7512512207031,- 1292.0186767578125,- 584.2667236328125,- 91.91043853759766,- 584.2667236328125- ],- "score": 0.9999946355819702- },- {- "category_id": 2,- "poly": [- 103.35292053222656,- 1951.1502685546875,- 775.5437622070312,- 1951.1502685546875,- 775.5437622070312,- 2000.939453125,- 103.35292053222656,- 2000.939453125- ],- "score": 0.999994158744812- },- {- "category_id": 2,- "poly": [- 1378.5472412109375,- 497.7952880859375,- 1533.4482421875,- 497.7952880859375,- 1533.4482421875,- 554.8080444335938,- 1378.5472412109375,- 554.8080444335938- ],- "score": 0.9999939799308777- },- {- "category_id": 1,- "poly": [- 547.7000122070312,- 798.6962890625,- 1536.8516845703125,- 798.6962890625,- 1536.8516845703125,- 1087.2454833984375,- 547.7000122070312,- 1087.2454833984375- ],- "score": 0.9999936819076538- },- {- "category_id": 1,- "poly": [- 838.4812622070312,- 1227.66015625,- 1533.677490234375,- 1227.66015625,- 1533.677490234375,- 1341.39697265625,- 838.4812622070312,- 1341.39697265625- ],- "score": 0.9999936819076538- },- {- "category_id": 1,- "poly": [- 838.9534301757812,- 1605.1298828125,- 1535.55908203125,- 1605.1298828125,- 1535.55908203125,- 1747.72119140625,- 838.9534301757812,- 1747.72119140625- ],- "score": 0.9999905824661255- },- {- "category_id": 1,- "poly": [- 838.2545776367188,- 1343.30908203125,- 1535.676513671875,- 1343.30908203125,- 1535.676513671875,- 1602.3951416015625,- 838.2545776367188,- 1602.3951416015625- ],- "score": 0.9999809265136719- },- {- "category_id": 1,- "poly": [- 838.8796997070312,- 1749.916015625,- 1535.641357421875,- 1749.916015625,- 1535.641357421875,- 1980.151611328125,- 838.8796997070312,- 1980.151611328125- ],- "score": 0.9999707937240601- },- {- "category_id": 1,- "poly": [- 89.87824249267578,- 605.3556518554688,- 392.66705322265625,- 605.3556518554688,- 392.66705322265625,- 641.5532836914062,- 89.87824249267578,- 641.5532836914062- ],- "score": 0.9999632835388184- },- {- "category_id": 2,- "poly": [- 88.07671356201172,- 178.80319213867188,- 1540.334228515625,- 178.80319213867188,- 1540.334228515625,- 415.3953552246094,- 88.07671356201172,- 415.3953552246094- ],- "score": 0.9999510645866394- },- {- "category_id": 1,- "poly": [- 90.96092224121094,- 1283.6514892578125,- 787.3784790039062,- 1283.6514892578125,- 787.3784790039062,- 1720.0255126953125,- 90.96092224121094,- 1720.0255126953125- ],- "score": 0.9999505281448364- },- {- "category_id": 1,- "poly": [- 1155.4818115234375,- 1091.02734375,- 1533.6707763671875,- 1091.02734375,- 1533.6707763671875,- 1114.8646240234375,- 1155.4818115234375,- 1114.8646240234375- ],- "score": 0.9999305605888367- },- {- "category_id": 2,- "poly": [- 581.09765625,- 130.82400512695312,- 1045.2071533203125,- 130.82400512695312,- 1045.2071533203125,- 150.460205078125,- 581.09765625,- 150.460205078125- ],- "score": 0.999903678894043- },- {- "category_id": 2,- "poly": [- 90.04467010498047,- 2029.578857421875,- 524.6141967773438,- 2029.578857421875,- 524.6141967773438,- 2073.1865234375,- 90.04467010498047,- 2073.1865234375- ],- "score": 0.9998822212219238- },- {- "category_id": 0,- "poly": [- 92.48286437988281,- 1226.6429443359375,- 257.3620910644531,- 1226.6429443359375,- 257.3620910644531,- 1253.4033203125,- 92.48286437988281,- 1253.4033203125- ],- "score": 0.9998089671134949- },- {- "category_id": 1,- "poly": [- 89.78173828125,- 1721.44873046875,- 788.7147827148438,- 1721.44873046875,- 788.7147827148438,- 1891.7547607421875,- 89.78173828125,- 1891.7547607421875- ],- "score": 0.999518096446991- },- {- "category_id": 1,- "poly": [- 90.23831939697266,- 660.470947265625,- 844.7678833007812,- 660.470947265625,- 844.7678833007812,- 680.8494262695312,- 90.23831939697266,- 680.8494262695312- ],- "score": 0.9993680715560913- },- {- "category_id": 0,- "poly": [- 546.9752807617188,- 739.2661743164062,- 729.0658569335938,- 739.2661743164062,- 729.0658569335938,- 769.2426147460938,- 546.9752807617188,- 769.2426147460938- ],- "score": 0.9981608390808105- },- {- "category_id": 0,- "poly": [- 90.21405029296875,- 738.3426513671875,- 350.7695617675781,- 738.3426513671875,- 350.7695617675781,- 768.7169189453125,- 90.21405029296875,- 768.7169189453125- ],- "score": 0.9972051382064819- },- {- "category_id": 13,- "poly": [- 1110,- 1255,- 1173,- 1255,- 1173,- 1283,- 1110,- 1283- ],- "score": 0.9,- "latex": "{\\sf A l}_{2}O_{3}"- },- {- "category_id": 13,- "poly": [- 1350,- 824,- 1395,- 824,- 1395,- 850,- 1350,- 850- ],- "score": 0.9,- "latex": "\\mathrm{TiO}_{2}"- },- {- "category_id": 13,- "poly": [- 1436,- 798,- 1483,- 798,- 1483,- 823,- 1436,- 823- ],- "score": 0.85,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 1014,- 1255,- 1062,- 1255,- 1062,- 1283,- 1014,- 1283- ],- "score": 0.83,- "latex": "\\mathrm{TiB}_{2}"- },- {- "category_id": 13,- "poly": [- 965,- 1255,- 1006,- 1255,- 1006,- 1283,- 965,- 1283- ],- "score": 0.72,- "latex": "\\mathsf{C_{4}B}"- },- {- "category_id": 13,- "poly": [- 1153,- 1091,- 1173,- 1091,- 1173,- 1113,- 1153,- 1113- ],- "score": 0.62,- "latex": "\\copyright"- },- {- "category_id": 13,- "poly": [- 1262,- 824,- 1322,- 824,- 1322,- 848,- 1262,- 848- ],- "score": 0.44,- "latex": "8\\,\\mathsf{w t\\%}"- },- {- "category_id": 13,- "poly": [- 1158,- 824,- 1217,- 824,- 1217,- 849,- 1158,- 849- ],- "score": 0.42,- "latex": "2\\,\\mathsf{w t\\%}"- },- {- "category_id": 13,- "poly": [- 186,- 2053,- 205,- 2053,- 205,- 2073,- 186,- 2073- ],- "score": 0.27,- "latex": "I(\\mathbb{C})"- }- ],- "page_info": {- "page_no": 0,- "height": 2205,- "width": 1654- }- },- {- "layout_dets": [- {- "category_id": 5,- "poly": [- 863.7239379882812,- 1964.214111328125,- 1567.1441650390625,- 1964.214111328125,- 1567.1441650390625,- 2095.432373046875,- 863.7239379882812,- 2095.432373046875- ],- "score": 0.9999992251396179- },- {- "category_id": 1,- "poly": [- 116.88060760498047,- 181.18443298339844,- 815.2633666992188,- 181.18443298339844,- 815.2633666992188,- 502.25347900390625,- 116.88060760498047,- 502.25347900390625- ],- "score": 0.9999946355819702- },- {- "category_id": 1,- "poly": [- 865.6710205078125,- 1444.2073974609375,- 1562.981689453125,- 1444.2073974609375,- 1562.981689453125,- 1728.4532470703125,- 865.6710205078125,- 1728.4532470703125- ],- "score": 0.9999915957450867- },- {- "category_id": 1,- "poly": [- 866.3514404296875,- 252.02035522460938,- 1565.2509765625,- 252.02035522460938,- 1565.2509765625,- 635.9597778320312,- 866.3514404296875,- 635.9597778320312- ],- "score": 0.9999898672103882- },- {- "category_id": 1,- "poly": [- 865.9268798828125,- 1160.2176513671875,- 1564.0030517578125,- 1160.2176513671875,- 1564.0030517578125,- 1444.03125,- 865.9268798828125,- 1444.03125- ],- "score": 0.9999892115592957- },- {- "category_id": 1,- "poly": [- 865.9280395507812,- 183.47573852539062,- 1564.9075927734375,- 183.47573852539062,- 1564.9075927734375,- 254.07687377929688,- 865.9280395507812,- 254.07687377929688- ],- "score": 0.9999834895133972- },- {- "category_id": 1,- "poly": [- 116.96244049072266,- 502.8096923828125,- 815.2603149414062,- 502.8096923828125,- 815.2603149414062,- 1489.82470703125,- 116.96244049072266,- 1489.82470703125- ],- "score": 0.9999810457229614- },- {- "category_id": 1,- "poly": [- 866.2127685546875,- 633.9317016601562,- 1564.4998779296875,- 633.9317016601562,- 1564.4998779296875,- 1037.8985595703125,- 866.2127685546875,- 1037.8985595703125- ],- "score": 0.9999791979789734- },- {- "category_id": 6,- "poly": [- 864.68115234375,- 1914.5120849609375,- 1235.378662109375,- 1914.5120849609375,- 1235.378662109375,- 1960.7431640625,- 864.68115234375,- 1960.7431640625- ],- "score": 0.9999697208404541- },- {- "category_id": 1,- "poly": [- 118.18121337890625,- 1981.5723876953125,- 816.2428588867188,- 1981.5723876953125,- 816.2428588867188,- 2098.903564453125,- 118.18121337890625,- 2098.903564453125- ],- "score": 0.9999620318412781- },- {- "category_id": 1,- "poly": [- 118.17263793945312,- 1492.0596923828125,- 815.34619140625,- 1492.0596923828125,- 815.34619140625,- 1693.1812744140625,- 118.17263793945312,- 1693.1812744140625- ],- "score": 0.9999526739120483- },- {- "category_id": 1,- "poly": [- 118.46794891357422,- 1695.7735595703125,- 815.2138671875,- 1695.7735595703125,- 815.2138671875,- 1895.4493408203125,- 118.46794891357422,- 1895.4493408203125- ],- "score": 0.9999057650566101- },- {- "category_id": 2,- "poly": [- 528.7487182617188,- 130.04393005371094,- 1152.2757568359375,- 130.04393005371094,- 1152.2757568359375,- 152.6596221923828,- 528.7487182617188,- 152.6596221923828- ],- "score": 0.999844491481781- },- {- "category_id": 1,- "poly": [- 865.2322998046875,- 1040.92236328125,- 1561.4454345703125,- 1040.92236328125,- 1561.4454345703125,- 1158.04931640625,- 865.2322998046875,- 1158.04931640625- ],- "score": 0.9997740983963013- },- {- "category_id": 1,- "poly": [- 865.71240234375,- 1811.2293701171875,- 1562.9034423828125,- 1811.2293701171875,- 1562.9034423828125,- 1862.283203125,- 865.71240234375,- 1862.283203125- ],- "score": 0.9997434616088867- },- {- "category_id": 0,- "poly": [- 116.96478271484375,- 1933.8809814453125,- 363.2524108886719,- 1933.8809814453125,- 363.2524108886719,- 1956.3245849609375,- 116.96478271484375,- 1956.3245849609375- ],- "score": 0.9996492266654968- },- {- "category_id": 0,- "poly": [- 864.6090698242188,- 1754.5186767578125,- 966.8403930664062,- 1754.5186767578125,- 966.8403930664062,- 1781.56591796875,- 864.6090698242188,- 1781.56591796875- ],- "score": 0.9938722848892212- },- {- "category_id": 2,- "poly": [- 1531.025634765625,- 131.12342834472656,- 1564.9666748046875,- 131.12342834472656,- 1564.9666748046875,- 150.2338104248047,- 1531.025634765625,- 150.2338104248047- ],- "score": 0.9937113523483276- },- {- "category_id": 9,- "poly": [- 1539.2025146484375,- 1757.8359375,- 1561.8992919921875,- 1757.8359375,- 1561.8992919921875,- 1785.4232177734375,- 1539.2025146484375,- 1785.4232177734375- ],- "score": 0.899275004863739- },- {- "category_id": 13,- "poly": [- 1024,- 730,- 1085,- 730,- 1085,- 753,- 1024,- 753- ],- "score": 0.91,- "latex": "\\beta=60^{\\circ}"- },- {- "category_id": 13,- "poly": [- 1123,- 611,- 1202,- 611,- 1202,- 634,- 1123,- 634- ],- "score": 0.9,- "latex": "21.8\\,^{\\circ}\\mathrm{C}/\\mathrm{h}"- },- {- "category_id": 13,- "poly": [- 556,- 1839,- 606,- 1839,- 606,- 1867,- 556,- 1867- ],- "score": 0.9,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 1299,- 184,- 1357,- 184,- 1357,- 206,- 1299,- 206- ],- "score": 0.89,- "latex": "40\\,\\upmu\\mathrm{m}"- },- {- "category_id": 13,- "poly": [- 1218,- 468,- 1368,- 468,- 1368,- 490,- 1218,- 490- ],- "score": 0.89,- "latex": "15\\times15\\times80\\,\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 463,- 1752,- 513,- 1752,- 513,- 1780,- 463,- 1780- ],- "score": 0.88,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 1237,- 421,- 1277,- 421,- 1277,- 444,- 1237,- 444- ],- "score": 0.88,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 703,- 2076,- 773,- 2076,- 773,- 2100,- 703,- 2100- ],- "score": 0.88,- "latex": "{<\\!45~\\upmu\\mathrm{m}}"- },- {- "category_id": 13,- "poly": [- 1129,- 825,- 1265,- 825,- 1265,- 847,- 1129,- 847- ],- "score": 0.87,- "latex": "14.6\\times14.6\\:\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 1428,- 635,- 1476,- 635,- 1476,- 658,- 1428,- 658- ],- "score": 0.87,- "latex": "\\mathrm{MoS}_{2}"- },- {- "category_id": 13,- "poly": [- 1291,- 825,- 1426,- 825,- 1426,- 847,- 1291,- 847- ],- "score": 0.87,- "latex": "14.2\\times14.2\\:\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 1178,- 706,- 1314,- 706,- 1314,- 728,- 1178,- 728- ],- "score": 0.87,- "latex": "14.6\\times14.6\\,\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 1100,- 1278,- 1148,- 1278,- 1148,- 1301,- 1100,- 1301- ],- "score": 0.87,- "latex": "\\mathsf{A l}_{4}\\mathsf C_{3}"- },- {- "category_id": 13,- "poly": [- 1108,- 207,- 1148,- 207,- 1148,- 230,- 1108,- 230- ],- "score": 0.86,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 862,- 540,- 920,- 540,- 920,- 562,- 862,- 562- ],- "score": 0.85,- "latex": "640~^{\\circ}\\mathrm{C}"- },- {- "category_id": 13,- "poly": [- 115,- 1751,- 236,- 1751,- 236,- 1780,- 115,- 1780- ],- "score": 0.85,- "latex": "\\mathsf{A l-C u/T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 1035,- 1420,- 1094,- 1420,- 1094,- 1443,- 1035,- 1443- ],- "score": 0.84,- "latex": "1000\\,\\mathrm{g}"- },- {- "category_id": 13,- "poly": [- 489,- 1981,- 530,- 1981,- 530,- 2003,- 489,- 2003- ],- "score": 0.84,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 1470,- 516,- 1528,- 516,- 1528,- 538,- 1470,- 538- ],- "score": 0.84,- "latex": "580\\,^{\\circ}\\mathrm{C}"- },- {- "category_id": 13,- "poly": [- 1049,- 183,- 1101,- 183,- 1101,- 205,- 1049,- 205- ],- "score": 0.84,- "latex": "99.9\\%"- },- {- "category_id": 13,- "poly": [- 1406,- 183,- 1458,- 183,- 1458,- 205,- 1406,- 205- ],- "score": 0.83,- "latex": "99.0\\%"- },- {- "category_id": 13,- "poly": [- 1402,- 873,- 1508,- 873,- 1508,- 895,- 1402,- 895- ],- "score": 0.83,- "latex": "15\\times15\\,\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 684,- 909,- 725,- 909,- 725,- 935,- 684,- 935- ],- "score": 0.82,- "latex": "90^{\\circ}"- },- {- "category_id": 13,- "poly": [- 1407,- 516,- 1464,- 516,- 1464,- 538,- 1407,- 538- ],- "score": 0.81,- "latex": "550\\,^{\\circ}\\mathrm{C}"- },- {- "category_id": 14,- "poly": [- 861,- 1755,- 969,- 1755,- 969,- 1783,- 861,- 1783- ],- "score": 0.79,- "latex": "V=K W L/H"- },- {- "category_id": 13,- "poly": [- 863,- 706,- 943,- 706,- 943,- 730,- 863,- 730- ],- "score": 0.79,- "latex": "1.1\\:\\mathrm{mm}/s"- },- {- "category_id": 13,- "poly": [- 1124,- 968,- 1243,- 968,- 1243,- 991,- 1124,- 991- ],- "score": 0.78,- "latex": "68.4\\,\\mathrm{mm/min}"- },- {- "category_id": 13,- "poly": [- 1053,- 944,- 1248,- 944,- 1248,- 967,- 1053,- 967- ],- "score": 0.74,- "latex": "\\mathsf{A l-4\\,w t\\%C u/2\\,w t\\%T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 260,- 1868,- 326,- 1868,- 326,- 1894,- 260,- 1894- ],- "score": 0.71,- "latex": "8\\,\\mathrm{wt\\%}"- },- {- "category_id": 13,- "poly": [- 972,- 1278,- 1051,- 1278,- 1051,- 1301,- 972,- 1301- ],- "score": 0.7,- "latex": "\\mathsf{A l}_{7}\\mathsf{C u}_{2}\\mathsf{F e}"- },- {- "category_id": 13,- "poly": [- 923,- 1814,- 940,- 1814,- 940,- 1834,- 923,- 1834- ],- "score": 0.67,- "latex": "V"- },- {- "category_id": 13,- "poly": [- 1222,- 873,- 1285,- 873,- 1285,- 895,- 1222,- 895- ],- "score": 0.67,- "latex": "80\\,\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 1428,- 1682,- 1492,- 1682,- 1492,- 1704,- 1428,- 1704- ],- "score": 0.64,- "latex": "1000\\,\\mathrm{m}"- },- {- "category_id": 13,- "poly": [- 1519,- 396,- 1559,- 396,- 1559,- 419,- 1519,- 419- ],- "score": 0.63,- "latex": "16\\,\\mathrm{h}"- },- {- "category_id": 13,- "poly": [- 1501,- 1587,- 1564,- 1587,- 1564,- 1609,- 1501,- 1609- ],- "score": 0.6,- "latex": "50\\,\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 1162,- 421,- 1215,- 421,- 1215,- 443,- 1162,- 443- ],- "score": 0.58,- "latex": "8\\,\\mathsf{w t\\%}"- },- {- "category_id": 13,- "poly": [- 981,- 516,- 1056,- 516,- 1056,- 538,- 981,- 538- ],- "score": 0.57,- "latex": "100\\,\\mathrm{MPa}"- },- {- "category_id": 13,- "poly": [- 862,- 1658,- 916,- 1658,- 916,- 1680,- 862,- 1680- ],- "score": 0.56,- "latex": "5\\:\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 885,- 230,- 942,- 230,- 942,- 252,- 885,- 252- ],- "score": 0.55,- "latex": "50\\,\\mathrm{nm}"- },- {- "category_id": 13,- "poly": [- 1502,- 468,- 1564,- 468,- 1564,- 490,- 1502,- 490- ],- "score": 0.53,- "latex": "15\\,\\mathrm{{min}}"- },- {- "category_id": 13,- "poly": [- 985,- 1611,- 1039,- 1611,- 1039,- 1633,- 985,- 1633- ],- "score": 0.53,- "latex": "4\\,\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 1020,- 1659,- 1074,- 1659,- 1074,- 1680,- 1020,- 1680- ],- "score": 0.5,- "latex": "2\\:\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 1292,- 944,- 1411,- 944,- 1411,- 967,- 1292,- 967- ],- "score": 0.5,- "latex": "\\mathsf{A l-4\\,w t\\%C u}/8"- },- {- "category_id": 13,- "poly": [- 1349,- 1838,- 1366,- 1838,- 1366,- 1858,- 1349,- 1858- ],- "score": 0.5,- "latex": "K"- },- {- "category_id": 13,- "poly": [- 1487,- 540,- 1564,- 540,- 1564,- 562,- 1487,- 562- ],- "score": 0.5,- "latex": "700\\,\\mathrm{MPa}"- },- {- "category_id": 13,- "poly": [- 946,- 1563,- 999,- 1563,- 999,- 1585,- 946,- 1585- ],- "score": 0.49,- "latex": "1\\:\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 999,- 373,- 1062,- 373,- 1062,- 395,- 999,- 395- ],- "score": 0.49,- "latex": "30\\,\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 1276,- 564,- 1349,- 564,- 1349,- 586,- 1276,- 586- ],- "score": 0.47,- "latex": "120\\,\\mathrm{min}"- },- {- "category_id": 13,- "poly": [- 1302,- 1814,- 1321,- 1814,- 1321,- 1834,- 1302,- 1834- ],- "score": 0.47,- "latex": "H"- },- {- "category_id": 13,- "poly": [- 1328,- 802,- 1390,- 802,- 1390,- 823,- 1328,- 823- ],- "score": 0.45,- "latex": "29\\,\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 953,- 278,- 1034,- 278,- 1034,- 301,- 953,- 301- ],- "score": 0.43,- "latex": "0.001\\;\\mathrm{mg}"- },- {- "category_id": 13,- "poly": [- 1281,- 1838,- 1310,- 1838,- 1310,- 1860,- 1281,- 1860- ],- "score": 0.43,- "latex": "(\\mathrm{m})"- },- {- "category_id": 13,- "poly": [- 943,- 397,- 1019,- 397,- 1019,- 420,- 943,- 420- ],- "score": 0.42,- "latex": "300\\,\\mathrm{rpm}"- },- {- "category_id": 13,- "poly": [- 1074,- 421,- 1126,- 421,- 1126,- 443,- 1074,- 443- ],- "score": 0.41,- "latex": "2\\,\\mathsf{w t\\%}"- },- {- "category_id": 13,- "poly": [- 1348,- 1682,- 1390,- 1682,- 1390,- 1704,- 1348,- 1704- ],- "score": 0.41,- "latex": "30\\,\\mathrm{N}"- },- {- "category_id": 13,- "poly": [- 762,- 1981,- 817,- 1981,- 817,- 2003,- 762,- 2003- ],- "score": 0.31,- "latex": "\\mathsf{A l-C u}"- },- {- "category_id": 13,- "poly": [- 1046,- 1837,- 1087,- 1837,- 1087,- 1859,- 1046,- 1859- ],- "score": 0.29,- "latex": "30\\,\\mathrm{N}"- },- {- "category_id": 13,- "poly": [- 1416,- 944,- 1487,- 944,- 1487,- 967,- 1416,- 967- ],- "score": 0.28,- "latex": "\\mathsf{w t}\\%\\mathrm{Ti}0_{2}"- },- {- "category_id": 13,- "poly": [- 917,- 492,- 992,- 492,- 992,- 514,- 917,- 514- ],- "score": 0.28,- "latex": "600\\,\\mathrm{MPa}"- }- ],- "page_info": {- "page_no": 1,- "height": 2205,- "width": 1654- }- },- {- "layout_dets": [- {- "category_id": 0,- "poly": [- 91.65608215332031,- 795.8480224609375,- 366.66326904296875,- 795.8480224609375,- 366.66326904296875,- 821.7848510742188,- 91.65608215332031,- 821.7848510742188- ],- "score": 0.9999936819076538- },- {- "category_id": 3,- "poly": [- 341.48529052734375,- 186.12124633789062,- 1285.360595703125,- 186.12124633789062,- 1285.360595703125,- 490.6669921875,- 341.48529052734375,- 490.6669921875- ],- "score": 0.9999930262565613- },- {- "category_id": 2,- "poly": [- 91.01846313476562,- 131.80783081054688,- 123.18841552734375,- 131.80783081054688,- 123.18841552734375,- 149.31529235839844,- 91.01846313476562,- 149.31529235839844- ],- "score": 0.999992847442627- },- {- "category_id": 1,- "poly": [- 837.5799560546875,- 590.760498046875,- 1537.0125732421875,- 590.760498046875,- 1537.0125732421875,- 1112.033935546875,- 837.5799560546875,- 1112.033935546875- ],- "score": 0.9999901056289673- },- {- "category_id": 3,- "poly": [- 247.45184326171875,- 1181.2760009765625,- 1375.3214111328125,- 1181.2760009765625,- 1375.3214111328125,- 2025.7017822265625,- 247.45184326171875,- 2025.7017822265625- ],- "score": 0.9999861717224121- },- {- "category_id": 1,- "poly": [- 91.52316284179688,- 911.5580444335938,- 786.8192749023438,- 911.5580444335938,- 786.8192749023438,- 1112.388427734375,- 91.52316284179688,- 1112.388427734375- ],- "score": 0.9999761581420898- },- {- "category_id": 2,- "poly": [- 502.0841064453125,- 130.44076538085938,- 1124.5677490234375,- 130.44076538085938,- 1124.5677490234375,- 153.38043212890625,- 502.0841064453125,- 153.38043212890625- ],- "score": 0.9999574422836304- },- {- "category_id": 1,- "poly": [- 91.35797882080078,- 591.5709228515625,- 787.5947265625,- 591.5709228515625,- 787.5947265625,- 755.6906127929688,- 91.35797882080078,- 755.6906127929688- ],- "score": 0.9999534487724304- },- {- "category_id": 4,- "poly": [- 87.87506103515625,- 2050.768798828125,- 1537.935791015625,- 2050.768798828125,- 1537.935791015625,- 2102.665771484375,- 87.87506103515625,- 2102.665771484375- ],- "score": 0.9999040365219116- },- {- "category_id": 0,- "poly": [- 91.45085144042969,- 855.3868408203125,- 357.5746154785156,- 855.3868408203125,- 357.5746154785156,- 879.35302734375,- 91.45085144042969,- 879.35302734375- ],- "score": 0.9998759627342224- },- {- "category_id": 4,- "poly": [- 575.242919921875,- 515.7332153320312,- 1046.6873779296875,- 515.7332153320312,- 1046.6873779296875,- 538.0972290039062,- 575.242919921875,- 538.0972290039062- ],- "score": 0.9996908903121948- },- {- "category_id": 13,- "poly": [- 109,- 662,- 173,- 662,- 173,- 685,- 109,- 685- ],- "score": 0.9,- "latex": "H/D=1"- },- {- "category_id": 13,- "poly": [- 985,- 515,- 1045,- 515,- 1045,- 538,- 985,- 538- ],- "score": 0.89,- "latex": "\\beta=60^{\\circ}"- },- {- "category_id": 13,- "poly": [- 1440,- 736,- 1537,- 736,- 1537,- 764,- 1440,- 764- ],- "score": 0.89,- "latex": "\\mathsf{A l}_{7}\\mathsf{C u}_{2}\\mathrm{Fe}"- },- {- "category_id": 13,- "poly": [- 959,- 649,- 1009,- 649,- 1009,- 677,- 959,- 677- ],- "score": 0.89,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 885,- 515,- 946,- 515,- 946,- 536,- 885,- 536- ],- "score": 0.89,- "latex": "\\mathcal{L}=90^{\\circ}"- },- {- "category_id": 13,- "poly": [- 726,- 1027,- 790,- 1027,- 790,- 1056,- 726,- 1056- ],- "score": 0.88,- "latex": "\\mathsf{A l_{2}C u}"- },- {- "category_id": 13,- "poly": [- 999,- 910,- 1095,- 910,- 1095,- 938,- 999,- 938- ],- "score": 0.88,- "latex": "\\mathsf{A l}_{7}\\mathsf{C u}_{2}\\mathsf{F e}"- },- {- "category_id": 13,- "poly": [- 1125,- 1028,- 1190,- 1028,- 1190,- 1055,- 1125,- 1055- ],- "score": 0.88,- "latex": "\\mathsf{A l_{2}C u}"- },- {- "category_id": 13,- "poly": [- 160,- 1086,- 226,- 1086,- 226,- 1113,- 160,- 1113- ],- "score": 0.87,- "latex": "\\mathsf{A l_{2}C u}"- },- {- "category_id": 13,- "poly": [- 1051,- 998,- 1162,- 998,- 1162,- 1025,- 1051,- 1025- ],- "score": 0.85,- "latex": "8\\,\\mathsf{w t}\\%\\mathrm{Ti}0_{2}"- },- {- "category_id": 13,- "poly": [- 863,- 1085,- 959,- 1085,- 959,- 1112,- 863,- 1112- ],- "score": 0.84,- "latex": "\\mathsf{A l}_{7}\\mathsf{C u}_{2}\\mathrm{Fe}"- },- {- "category_id": 13,- "poly": [- 897,- 591,- 1008,- 591,- 1008,- 618,- 897,- 618- ],- "score": 0.83,- "latex": "2\\,\\mathsf{w t}\\%\\mathrm{TiO}_{2}"- },- {- "category_id": 13,- "poly": [- 572,- 662,- 660,- 662,- 660,- 685,- 572,- 685- ],- "score": 0.72,- "latex": "8\\,\\mathsf{w t\\%T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 1208,- 998,- 1258,- 998,- 1258,- 1025,- 1208,- 1025- ],- "score": 0.69,- "latex": "16\\,\\mathrm{h}"- },- {- "category_id": 13,- "poly": [- 1481,- 852,- 1531,- 852,- 1531,- 879,- 1481,- 879- ],- "score": 0.66,- "latex": "16\\,\\mathrm{h}"- },- {- "category_id": 13,- "poly": [- 135,- 969,- 172,- 969,- 172,- 995,- 135,- 995- ],- "score": 0.66,- "latex": "8\\,\\mathrm{h}"- },- {- "category_id": 13,- "poly": [- 1113,- 678,- 1164,- 678,- 1164,- 705,- 1113,- 705- ],- "score": 0.61,- "latex": "16\\,\\mathrm{h}"- },- {- "category_id": 13,- "poly": [- 222,- 941,- 316,- 941,- 316,- 968,- 222,- 968- ],- "score": 0.59,- "latex": "4\\,\\mathsf{w t\\%C u}"- },- {- "category_id": 13,- "poly": [- 1108,- 939,- 1157,- 939,- 1157,- 966,- 1108,- 966- ],- "score": 0.54,- "latex": "16\\,\\mathrm{h}"- },- {- "category_id": 13,- "poly": [- 624,- 1057,- 661,- 1057,- 661,- 1083,- 624,- 1083- ],- "score": 0.48,- "latex": "8\\,\\mathrm{h}"- },- {- "category_id": 13,- "poly": [- 984,- 2051,- 1024,- 2051,- 1024,- 2074,- 984,- 2074- ],- "score": 0.43,- "latex": "12\\,\\mathrm{h}"- },- {- "category_id": 13,- "poly": [- 348,- 2076,- 436,- 2076,- 436,- 2099,- 348,- 2099- ],- "score": 0.43,- "latex": "8\\,\\mathsf{w t\\%T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 521,- 2052,- 583,- 2052,- 583,- 2074,- 521,- 2074- ],- "score": 0.4,- "latex": "\\mathsf{A l-4C u}"- },- {- "category_id": 13,- "poly": [- 1061,- 2052,- 1101,- 2052,- 1101,- 2074,- 1061,- 2074- ],- "score": 0.34,- "latex": "16\\,\\mathrm{h}"- }- ],- "page_info": {- "page_no": 2,- "height": 2205,- "width": 1654- }- },- {- "layout_dets": [- {- "category_id": 1,- "poly": [- 865.62939453125,- 1252.281494140625,- 1564.0399169921875,- 1252.281494140625,- 1564.0399169921875,- 1398.3865966796875,- 865.62939453125,- 1398.3865966796875- ],- "score": 0.9999939799308777- },- {- "category_id": 3,- "poly": [- 399.5266418457031,- 1712.743896484375,- 1277.1873779296875,- 1712.743896484375,- 1277.1873779296875,- 2050.62353515625,- 399.5266418457031,- 2050.62353515625- ],- "score": 0.9999939799308777- },- {- "category_id": 3,- "poly": [- 936.306640625,- 737.6135864257812,- 1491.9893798828125,- 737.6135864257812,- 1491.9893798828125,- 1129.449462890625,- 936.306640625,- 1129.449462890625- ],- "score": 0.9999932050704956- },- {- "category_id": 1,- "poly": [- 117.89160919189453,- 767.1466674804688,- 816.2000732421875,- 767.1466674804688,- 816.2000732421875,- 1056.1663818359375,- 117.89160919189453,- 1056.1663818359375- ],- "score": 0.9999916553497314- },- {- "category_id": 6,- "poly": [- 113.91787719726562,- 185.0103759765625,- 724.5757446289062,- 185.0103759765625,- 724.5757446289062,- 232.8446502685547,- 113.91787719726562,- 232.8446502685547- ],- "score": 0.9999884366989136- },- {- "category_id": 8,- "poly": [- 113.7851791381836,- 1070.353759765625,- 516.7171020507812,- 1070.353759765625,- 516.7171020507812,- 1138.810302734375,- 113.7851791381836,- 1138.810302734375- ],- "score": 0.9999841451644897- },- {- "category_id": 4,- "poly": [- 864.9486083984375,- 1153.076416015625,- 1564.9884033203125,- 1153.076416015625,- 1564.9884033203125,- 1201.17822265625,- 864.9486083984375,- 1201.17822265625- ],- "score": 0.9999566078186035- },- {- "category_id": 9,- "poly": [- 783.90625,- 1280.2330322265625,- 814.7933959960938,- 1280.2330322265625,- 814.7933959960938,- 1304.727294921875,- 783.90625,- 1304.727294921875- ],- "score": 0.9999472498893738- },- {- "category_id": 2,- "poly": [- 1530.7386474609375,- 130.15716552734375,- 1563.5892333984375,- 130.15716552734375,- 1563.5892333984375,- 150.149169921875,- 1530.7386474609375,- 150.149169921875- ],- "score": 0.9999317526817322- },- {- "category_id": 6,- "poly": [- 116.33224487304688,- 1449.589111328125,- 778.643310546875,- 1449.589111328125,- 778.643310546875,- 1497.123046875,- 116.33224487304688,- 1497.123046875- ],- "score": 0.9999303221702576- },- {- "category_id": 9,- "poly": [- 783.6682739257812,- 1187.593505859375,- 814.88330078125,- 1187.593505859375,- 814.88330078125,- 1211.3541259765625,- 783.6682739257812,- 1211.3541259765625- ],- "score": 0.9999110102653503- },- {- "category_id": 8,- "poly": [- 112.70803833007812,- 1168.94580078125,- 249.83746337890625,- 1168.94580078125,- 249.83746337890625,- 1239.764404296875,- 112.70803833007812,- 1239.764404296875- ],- "score": 0.9998843669891357- },- {- "category_id": 5,- "poly": [- 115.95402526855469,- 1503.884033203125,- 1566.2525634765625,- 1503.884033203125,- 1566.2525634765625,- 1654.9158935546875,- 115.95402526855469,- 1654.9158935546875- ],- "score": 0.9998706579208374- },- {- "category_id": 2,- "poly": [- 528.3235473632812,- 129.1370849609375,- 1153.358154296875,- 129.1370849609375,- 1153.358154296875,- 152.72943115234375,- 528.3235473632812,- 152.72943115234375- ],- "score": 0.9998427629470825- },- {- "category_id": 5,- "poly": [- 113.63433074951172,- 237.37672424316406,- 1568.111572265625,- 237.37672424316406,- 1568.111572265625,- 390.4731140136719,- 113.63433074951172,- 390.4731140136719- ],- "score": 0.9998158812522888- },- {- "category_id": 1,- "poly": [- 116.50083923339844,- 1340.106689453125,- 817.1612548828125,- 1340.106689453125,- 817.1612548828125,- 1401.006103515625,- 116.50083923339844,- 1401.006103515625- ],- "score": 0.9996623396873474- },- {- "category_id": 5,- "poly": [- 114.75572204589844,- 500.40631103515625,- 1567.5216064453125,- 500.40631103515625,- 1567.5216064453125,- 653.8458862304688,- 114.75572204589844,- 653.8458862304688- ],- "score": 0.999612033367157- },- {- "category_id": 6,- "poly": [- 114.71136474609375,- 448.86712646484375,- 842.3986206054688,- 448.86712646484375,- 842.3986206054688,- 493.80615234375,- 114.71136474609375,- 493.80615234375- ],- "score": 0.999423623085022- },- {- "category_id": 9,- "poly": [- 783.654052734375,- 1092.427734375,- 813.9013061523438,- 1092.427734375,- 813.9013061523438,- 1117.3460693359375,- 783.654052734375,- 1117.3460693359375- ],- "score": 0.9993578791618347- },- {- "category_id": 8,- "poly": [- 116.0940933227539,- 1263.635986328125,- 393.264892578125,- 1263.635986328125,- 393.264892578125,- 1322.1510009765625,- 116.0940933227539,- 1322.1510009765625- ],- "score": 0.9971747398376465- },- {- "category_id": 0,- "poly": [- 118.0734634399414,- 709.4276733398438,- 413.09381103515625,- 709.4276733398438,- 413.09381103515625,- 736.09228515625,- 118.0734634399414,- 736.09228515625- ],- "score": 0.9927340745925903- },- {- "category_id": 4,- "poly": [- 448.8941345214844,- 2077.12890625,- 1232.0526123046875,- 2077.12890625,- 1232.0526123046875,- 2098.308349609375,- 448.8941345214844,- 2098.308349609375- ],- "score": 0.9925144910812378- },- {- "category_id": 13,- "poly": [- 188,- 1341,- 235,- 1341,- 235,- 1368,- 188,- 1368- ],- "score": 0.9,- "latex": "W_{a i r}"- },- {- "category_id": 13,- "poly": [- 405,- 1029,- 458,- 1029,- 458,- 1058,- 405,- 1058- ],- "score": 0.9,- "latex": "(h/d)"- },- {- "category_id": 13,- "poly": [- 707,- 1341,- 777,- 1341,- 777,- 1369,- 707,- 1369- ],- "score": 0.9,- "latex": "W_{w a t e r}"- },- {- "category_id": 13,- "poly": [- 220,- 913,- 292,- 913,- 292,- 941,- 220,- 941- ],- "score": 0.89,- "latex": "({\\mathfrak{<}}97\\%)"- },- {- "category_id": 13,- "poly": [- 1070,- 1282,- 1143,- 1282,- 1143,- 1309,- 1070,- 1309- ],- "score": 0.87,- "latex": "640~^{\\circ}\\mathsf{C}"- },- {- "category_id": 13,- "poly": [- 977,- 1369,- 1050,- 1369,- 1050,- 1395,- 977,- 1395- ],- "score": 0.87,- "latex": "640~^{\\circ}\\mathsf{C}"- },- {- "category_id": 13,- "poly": [- 114,- 796,- 225,- 796,- 225,- 824,- 114,- 824- ],- "score": 0.87,- "latex": "2\\,\\mathsf{w t\\%T i O}_{2}"- },- {- "category_id": 13,- "poly": [- 479,- 796,- 553,- 796,- 553,- 823,- 479,- 823- ],- "score": 0.87,- "latex": "550\\,^{\\circ}\\mathrm{C}"- },- {- "category_id": 13,- "poly": [- 678,- 796,- 753,- 796,- 753,- 823,- 678,- 823- ],- "score": 0.86,- "latex": "580\\,^{\\circ}\\mathrm{C}"- },- {- "category_id": 13,- "poly": [- 862,- 1177,- 903,- 1177,- 903,- 1200,- 862,- 1200- ],- "score": 0.86,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 556,- 1473,- 614,- 1473,- 614,- 1495,- 556,- 1495- ],- "score": 0.83,- "latex": "640~^{\\circ}\\mathrm{C}"- },- {- "category_id": 13,- "poly": [- 790,- 1373,- 819,- 1373,- 819,- 1399,- 790,- 1399- ],- "score": 0.82,- "latex": "\\rho_{T}"- },- {- "category_id": 14,- "poly": [- 113,- 1162,- 250,- 1162,- 250,- 1238,- 113,- 1238- ],- "score": 0.79,- "latex": "\\rho_{T}=\\sum_{i=1}^{n}f_{i}\\rho_{i}"- },- {- "category_id": 13,- "poly": [- 302,- 1374,- 321,- 1374,- 321,- 1398,- 302,- 1398- ],- "score": 0.77,- "latex": "\\rho"- },- {- "category_id": 14,- "poly": [- 113,- 1070,- 516,- 1070,- 516,- 1136,- 113,- 1136- ],- "score": 0.76,- "latex": "\\rho=\\frac{W_{a i r}\\lfloor\\rho_{w a t e r}-0.0012\\rfloor}{0.99983\\lfloor W_{a i r}-W_{w a t e r}\\rfloor}+0.0012"- },- {- "category_id": 14,- "poly": [- 112,- 1261,- 393,- 1261,- 393,- 1324,- 112,- 1324- ],- "score": 0.73,- "latex": "\\%P o r o s i t y=\\frac{\\rho_{T}-\\rho}{\\rho_{T}}\\times100\\"- },- {- "category_id": 13,- "poly": [- 1092,- 1369,- 1180,- 1369,- 1180,- 1396,- 1092,- 1396- ],- "score": 0.6,- "latex": "120\\,\\mathrm{min}"- },- {- "category_id": 13,- "poly": [- 382,- 1473,- 457,- 1473,- 457,- 1496,- 382,- 1496- ],- "score": 0.56,- "latex": "700\\,\\mathrm{MPa}"- },- {- "category_id": 13,- "poly": [- 1470,- 1311,- 1557,- 1311,- 1557,- 1338,- 1470,- 1338- ],- "score": 0.42,- "latex": "120\\,\\mathrm{min}"- },- {- "category_id": 13,- "poly": [- 564,- 471,- 625,- 471,- 625,- 494,- 564,- 494- ],- "score": 0.37,- "latex": "30\\,\\mathrm{{min}}"- },- {- "category_id": 13,- "poly": [- 642,- 942,- 718,- 942,- 718,- 969,- 642,- 969- ],- "score": 0.36,- "latex": "30\\,\\mathrm{{min}}"- },- {- "category_id": 13,- "poly": [- 508,- 942,- 602,- 942,- 602,- 969,- 508,- 969- ],- "score": 0.36,- "latex": "700\\,\\mathrm{MPa}"- },- {- "category_id": 14,- "poly": [- 110,- 1068,- 513,- 1068,- 513,- 1326,- 110,- 1326- ],- "score": 0.29,- "latex": "\\begin{array}{l l}{\\rho=\\displaystyle\\frac{W_{a i r}\\lfloor\\rho_{w a t e r}-0.0012\\rfloor}{0.99983\\lfloor W_{a i r}-W_{w a t e r}\\rfloor}+0.0012}\\\\ {\\hfill}\\\\ {\\rho_{T}=\\displaystyle\\sum_{i=1}^{n}f_{i}\\rho_{i}}\\\\ {\\hfill}\\\\ {\\%P o r o s i t y=\\displaystyle\\frac{\\rho_{T}-\\rho}{\\rho_{T}}\\times100}\\end{array}"- },- {- "category_id": 13,- "poly": [- 530,- 1374,- 547,- 1374,- 547,- 1399,- 530,- 1399- ],- "score": 0.26,- "latex": "\\rho"- },- {- "category_id": 13,- "poly": [- 505,- 1510,- 570,- 1510,- 570,- 1537,- 505,- 1537- ],- "score": 0.26,- "latex": "(\\mathsf{g}/\\mathsf{c m}^{3})"- },- {- "category_id": 13,- "poly": [- 530,- 1371,- 593,- 1371,- 593,- 1399,- 530,- 1399- ],- "score": 0.26,- "latex": "\\rho_{w a t e r}"- }- ],- "page_info": {- "page_no": 3,- "height": 2205,- "width": 1654- }- },- {- "layout_dets": [- {- "category_id": 5,- "poly": [- 85.1810302734375,- 1178.9913330078125,- 793.0934448242188,- 1178.9913330078125,- 793.0934448242188,- 1384.3555908203125,- 85.1810302734375,- 1384.3555908203125- ],- "score": 0.999996542930603- },- {- "category_id": 1,- "poly": [- 838.4283447265625,- 1057.19189453125,- 1534.9283447265625,- 1057.19189453125,- 1534.9283447265625,- 1260.71875,- 838.4283447265625,- 1260.71875- ],- "score": 0.9999948740005493- },- {- "category_id": 3,- "poly": [- 193.11087036132812,- 1497.1810302734375,- 1420.6529541015625,- 1497.1810302734375,- 1420.6529541015625,- 2032.4029541015625,- 193.11087036132812,- 2032.4029541015625- ],- "score": 0.9999937415122986- },- {- "category_id": 2,- "poly": [- 90.88475036621094,- 131.75665283203125,- 122.91204071044922,- 131.75665283203125,- 122.91204071044922,- 149.78347778320312,- 90.88475036621094,- 149.78347778320312- ],- "score": 0.9999936819076538- },- {- "category_id": 6,- "poly": [- 87.61775970458984,- 1105.0426025390625,- 791.9078369140625,- 1105.0426025390625,- 791.9078369140625,- 1175.47900390625,- 87.61775970458984,- 1175.47900390625- ],- "score": 0.999993085861206- },- {- "category_id": 3,- "poly": [- 253.66595458984375,- 184.99485778808594,- 1372.848388671875,- 184.99485778808594,- 1372.848388671875,- 964.6041259765625,- 253.66595458984375,- 964.6041259765625- ],- "score": 0.9999756813049316- },- {- "category_id": 1,- "poly": [- 838.6137084960938,- 1261.0406494140625,- 1535.6204833984375,- 1261.0406494140625,- 1535.6204833984375,- 1436.0789794921875,- 838.6137084960938,- 1436.0789794921875- ],- "score": 0.9999641180038452- },- {- "category_id": 2,- "poly": [- 501.697021484375,- 130.6166534423828,- 1125.6859130859375,- 130.6166534423828,- 1125.6859130859375,- 153.36607360839844,- 501.697021484375,- 153.36607360839844- ],- "score": 0.9999618530273438- },- {- "category_id": 4,- "poly": [- 85.6832046508789,- 2050.6435546875,- 1536.8809814453125,- 2050.6435546875,- 1536.8809814453125,- 2101.74169921875,- 85.6832046508789,- 2101.74169921875- ],- "score": 0.9999083280563354- },- {- "category_id": 4,- "poly": [- 87.19976043701172,- 983.0482788085938,- 1538.29150390625,- 983.0482788085938,- 1538.29150390625,- 1008.1719360351562,- 87.19976043701172,- 1008.1719360351562- ],- "score": 0.9997954368591309- },- {- "category_id": 13,- "poly": [- 955,- 1115,- 1065,- 1115,- 1065,- 1143,- 955,- 1143- ],- "score": 0.89,- "latex": "8\\,\\mathsf{w t\\%T i O}_{2}"- },- {- "category_id": 13,- "poly": [- 1389,- 1143,- 1503,- 1143,- 1503,- 1173,- 1389,- 1173- ],- "score": 0.88,- "latex": "(4.5\\,\\mathrm{g}/\\mathrm{cm}^{3})"- },- {- "category_id": 13,- "poly": [- 1487,- 1115,- 1537,- 1115,- 1537,- 1143,- 1487,- 1143- ],- "score": 0.87,- "latex": "\\mathrm{TiO}_{2}"- },- {- "category_id": 13,- "poly": [- 835,- 1290,- 946,- 1290,- 946,- 1318,- 835,- 1318- ],- "score": 0.86,- "latex": "2\\,\\mathsf{w t}\\%\\mathrm{TiO}_{2}"- },- {- "category_id": 13,- "poly": [- 998,- 1290,- 1110,- 1290,- 1110,- 1318,- 998,- 1318- ],- "score": 0.82,- "latex": "8\\,\\mathsf{w t\\%T i O}_{2}"- },- {- "category_id": 13,- "poly": [- 513,- 2052,- 599,- 2052,- 599,- 2075,- 513,- 2075- ],- "score": 0.74,- "latex": "2\\,\\mathsf{w t}\\%\\mathrm{TiO}_{2}"- },- {- "category_id": 13,- "poly": [- 1293,- 2052,- 1381,- 2052,- 1381,- 2075,- 1293,- 2075- ],- "score": 0.73,- "latex": "8\\,\\mathsf{w t}\\%\\mathrm{TiO}_{2}"- },- {- "category_id": 13,- "poly": [- 376,- 1128,- 455,- 1128,- 455,- 1151,- 376,- 1151- ],- "score": 0.65,- "latex": "\\mathsf{A l-}4\\mathsf{C u}/2"- },- {- "category_id": 13,- "poly": [- 569,- 1128,- 647,- 1128,- 647,- 1151,- 569,- 1151- ],- "score": 0.62,- "latex": "\\mathsf{A l-4C u}/8"- },- {- "category_id": 13,- "poly": [- 619,- 983,- 694,- 983,- 694,- 1006,- 619,- 1006- ],- "score": 0.51,- "latex": "\\mathsf{w t}\\%\\mathrm{Ti}0_{2}"- },- {- "category_id": 13,- "poly": [- 649,- 1128,- 721,- 1128,- 721,- 1151,- 649,- 1151- ],- "score": 0.48,- "latex": "\\mathsf{w t}\\%\\mathrm{Ti}0_{2}"- },- {- "category_id": 13,- "poly": [- 732,- 983,- 821,- 983,- 821,- 1006,- 732,- 1006- ],- "score": 0.48,- "latex": "8\\,\\mathsf{w t\\%T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 458,- 1128,- 529,- 1128,- 529,- 1151,- 458,- 1151- ],- "score": 0.41,- "latex": "\\mathsf{w t}\\%\\mathrm{Ti}0_{2}"- }- ],- "page_info": {- "page_no": 4,- "height": 2205,- "width": 1654- }- },- {- "layout_dets": [- {- "category_id": 5,- "poly": [- 863.0476684570312,- 1368.269775390625,- 1566.6636962890625,- 1368.269775390625,- 1566.6636962890625,- 1500.9300537109375,- 863.0476684570312,- 1500.9300537109375- ],- "score": 0.9999980926513672- },- {- "category_id": 5,- "poly": [- 114.84563446044922,- 1964.6473388671875,- 1568.7454833984375,- 1964.6473388671875,- 1568.7454833984375,- 2095.1533203125,- 114.84563446044922,- 2095.1533203125- ],- "score": 0.9999978542327881- },- {- "category_id": 4,- "poly": [- 863.0890502929688,- 603.7634887695312,- 1565.33349609375,- 603.7634887695312,- 1565.33349609375,- 650.4027099609375,- 863.0890502929688,- 650.4027099609375- ],- "score": 0.9999968409538269- },- {- "category_id": 3,- "poly": [- 902.3161010742188,- 702.9896850585938,- 1519.22314453125,- 702.9896850585938,- 1519.22314453125,- 1135.4776611328125,- 902.3161010742188,- 1135.4776611328125- ],- "score": 0.9999963641166687- },- {- "category_id": 6,- "poly": [- 115.81310272216797,- 1913.5933837890625,- 628.254638671875,- 1913.5933837890625,- 628.254638671875,- 1961.8775634765625,- 115.81310272216797,- 1961.8775634765625- ],- "score": 0.9999960660934448- },- {- "category_id": 1,- "poly": [- 117.44493103027344,- 744.39404296875,- 815.6377563476562,- 744.39404296875,- 815.6377563476562,- 1120.616455078125,- 117.44493103027344,- 1120.616455078125- ],- "score": 0.9999946355819702- },- {- "category_id": 6,- "poly": [- 864.2783813476562,- 1318.18115234375,- 1232.5885009765625,- 1318.18115234375,- 1232.5885009765625,- 1365.5872802734375,- 864.2783813476562,- 1365.5872802734375- ],- "score": 0.9999942779541016- },- {- "category_id": 1,- "poly": [- 864.7146606445312,- 1556.3634033203125,- 1562.9923095703125,- 1556.3634033203125,- 1562.9923095703125,- 1788.9207763671875,- 864.7146606445312,- 1788.9207763671875- ],- "score": 0.9999929666519165- },- {- "category_id": 1,- "poly": [- 117.9727783203125,- 626.1322631835938,- 816.0490112304688,- 626.1322631835938,- 816.0490112304688,- 742.09912109375,- 117.9727783203125,- 742.09912109375- ],- "score": 0.9999925494194031- },- {- "category_id": 3,- "poly": [- 167.24481201171875,- 186.04148864746094,- 768.68212890625,- 186.04148864746094,- 768.68212890625,- 498.0415344238281,- 167.24481201171875,- 498.0415344238281- ],- "score": 0.9999908208847046- },- {- "category_id": 3,- "poly": [- 921.4217529296875,- 182.8133544921875,- 1510.5697021484375,- 182.8133544921875,- 1510.5697021484375,- 582.5126342773438,- 921.4217529296875,- 582.5126342773438- ],- "score": 0.9999903440475464- },- {- "category_id": 4,- "poly": [- 116.5409927368164,- 517.916015625,- 817.6602783203125,- 517.916015625,- 817.6602783203125,- 565.9894409179688,- 116.5409927368164,- 565.9894409179688- ],- "score": 0.9999828338623047- },- {- "category_id": 2,- "poly": [- 529.67138671875,- 130.6990203857422,- 1153.0557861328125,- 130.6990203857422,- 1153.0557861328125,- 152.77474975585938,- 529.67138671875,- 152.77474975585938- ],- "score": 0.9999527931213379- },- {- "category_id": 1,- "poly": [- 117.72147369384766,- 1732.668701171875,- 815.99853515625,- 1732.668701171875,- 815.99853515625,- 1846.7703857421875,- 117.72147369384766,- 1846.7703857421875- ],- "score": 0.9999458193778992- },- {- "category_id": 1,- "poly": [- 117.80567169189453,- 1411.1651611328125,- 816.5452270507812,- 1411.1651611328125,- 816.5452270507812,- 1728.624755859375,- 117.80567169189453,- 1728.624755859375- ],- "score": 0.9999319911003113- },- {- "category_id": 1,- "poly": [- 118.55921936035156,- 1121.5235595703125,- 815.2808227539062,- 1121.5235595703125,- 815.2808227539062,- 1410.293212890625,- 118.55921936035156,- 1410.293212890625- ],- "score": 0.9999170303344727- },- {- "category_id": 1,- "poly": [- 867.0330200195312,- 1788.76171875,- 1564.1209716796875,- 1788.76171875,- 1564.1209716796875,- 1844.2109375,- 867.0330200195312,- 1844.2109375- ],- "score": 0.9998733401298523- },- {- "category_id": 2,- "poly": [- 1531.4898681640625,- 131.4331817626953,- 1564.71728515625,- 131.4331817626953,- 1564.71728515625,- 149.570556640625,- 1531.4898681640625,- 149.570556640625- ],- "score": 0.9984385371208191- },- {- "category_id": 4,- "poly": [- 862.66455078125,- 1206.7962646484375,- 1566.1624755859375,- 1206.7962646484375,- 1566.1624755859375,- 1255.7220458984375,- 862.66455078125,- 1255.7220458984375- ],- "score": 0.9733632802963257- },- {- "category_id": 13,- "poly": [- 201,- 1295,- 349,- 1295,- 349,- 1324,- 201,- 1324- ],- "score": 0.9,- "latex": "\\mathsf{A l-4C u/8T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 258,- 772,- 355,- 772,- 355,- 800,- 258,- 800- ],- "score": 0.9,- "latex": "\\mathsf{A l}_{7}\\mathsf{C u}_{2}\\mathsf{F e}"- },- {- "category_id": 13,- "poly": [- 270,- 1789,- 321,- 1789,- 321,- 1817,- 270,- 1817- ],- "score": 0.89,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 1096,- 1643,- 1147,- 1643,- 1147,- 1671,- 1096,- 1671- ],- "score": 0.89,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 556,- 1325,- 607,- 1325,- 607,- 1353,- 556,- 1353- ],- "score": 0.89,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 502,- 1615,- 552,- 1615,- 552,- 1643,- 502,- 1643- ],- "score": 0.89,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 682,- 1499,- 732,- 1499,- 732,- 1527,- 682,- 1527- ],- "score": 0.89,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 543,- 628,- 652,- 628,- 652,- 655,- 543,- 655- ],- "score": 0.88,- "latex": "8\\,\\mathsf{w t\\%T i O}_{2}"- },- {- "category_id": 13,- "poly": [- 940,- 1614,- 1049,- 1614,- 1049,- 1642,- 940,- 1642- ],- "score": 0.88,- "latex": "8\\,\\mathsf{w t\\%T i O}_{2}"- },- {- "category_id": 13,- "poly": [- 115,- 1470,- 226,- 1470,- 226,- 1498,- 115,- 1498- ],- "score": 0.87,- "latex": "8\\,\\mathsf{w t\\%T i O}_{2}"- },- {- "category_id": 13,- "poly": [- 235,- 1586,- 308,- 1586,- 308,- 1613,- 235,- 1613- ],- "score": 0.87,- "latex": "640~^{\\circ}\\mathrm{C}"- },- {- "category_id": 13,- "poly": [- 514,- 772,- 660,- 772,- 660,- 800,- 514,- 800- ],- "score": 0.87,- "latex": "\\mathsf{A l-4C u}/2\\mathrm{Ti}0_{2}"- },- {- "category_id": 13,- "poly": [- 338,- 1150,- 486,- 1150,- 486,- 1178,- 338,- 1178- ],- "score": 0.84,- "latex": "\\mathsf{A l-4C u}/2\\mathrm{Ti}0_{2}"- },- {- "category_id": 13,- "poly": [- 861,- 1816,- 1057,- 1816,- 1057,- 1846,- 861,- 1846- ],- "score": 0.77,- "latex": "\\mathsf{A l-4C u}/2\\,\\mathsf{w t\\%T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 670,- 831,- 817,- 831,- 817,- 860,- 670,- 860- ],- "score": 0.77,- "latex": "\\mathsf{A l-4C u/8T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 1106,- 1817,- 1302,- 1817,- 1302,- 1846,- 1106,- 1846- ],- "score": 0.66,- "latex": "\\mathsf{A l-4C u/8\\,w t\\%T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 728,- 1440,- 817,- 1440,- 817,- 1470,- 728,- 1470- ],- "score": 0.57,- "latex": "\\mathsf{A l-4C u}/"- },- {- "category_id": 13,- "poly": [- 1061,- 1232,- 1104,- 1232,- 1104,- 1253,- 1061,- 1253- ],- "score": 0.45,- "latex": "30\\,\\mathrm{N}."- },- {- "category_id": 13,- "poly": [- 345,- 1586,- 434,- 1586,- 434,- 1613,- 345,- 1613- ],- "score": 0.37,- "latex": "120\\,\\mathrm{min}"- }- ],- "page_info": {- "page_no": 5,- "height": 2205,- "width": 1654- }- },- {- "layout_dets": [- {- "category_id": 1,- "poly": [- 838.4785766601562,- 809.7486572265625,- 1535.69775390625,- 809.7486572265625,- 1535.69775390625,- 1303.6871337890625,- 838.4785766601562,- 1303.6871337890625- ],- "score": 0.9999957084655762- },- {- "category_id": 1,- "poly": [- 89.58891296386719,- 1360.1927490234375,- 786.6004028320312,- 1360.1927490234375,- 786.6004028320312,- 1767.0189208984375,- 89.58891296386719,- 1767.0189208984375- ],- "score": 0.9999921321868896- },- {- "category_id": 3,- "poly": [- 212.2220001220703,- 184.3780517578125,- 1397.35400390625,- 184.3780517578125,- 1397.35400390625,- 682.5625610351562,- 212.2220001220703,- 682.5625610351562- ],- "score": 0.9999915957450867- },- {- "category_id": 6,- "poly": [- 85.9394302368164,- 1880.3299560546875,- 957.58984375,- 1880.3299560546875,- 957.58984375,- 1927.9156494140625,- 85.9394302368164,- 1927.9156494140625- ],- "score": 0.9999909400939941- },- {- "category_id": 3,- "poly": [- 161.99993896484375,- 812.5205688476562,- 715.10693359375,- 812.5205688476562,- 715.10693359375,- 1230.4681396484375,- 161.99993896484375,- 1230.4681396484375- ],- "score": 0.9999885559082031- },- {- "category_id": 2,- "poly": [- 90.9200210571289,- 131.76174926757812,- 124.43859100341797,- 131.76174926757812,- 124.43859100341797,- 148.8311004638672,- 90.9200210571289,- 148.8311004638672- ],- "score": 0.9999874830245972- },- {- "category_id": 2,- "poly": [- 501.8257751464844,- 130.71768188476562,- 1125.0487060546875,- 130.71768188476562,- 1125.0487060546875,- 152.62339782714844,- 501.8257751464844,- 152.62339782714844- ],- "score": 0.9999841451644897- },- {- "category_id": 5,- "poly": [- 86.02467346191406,- 1930.7803955078125,- 1540.3294677734375,- 1930.7803955078125,- 1540.3294677734375,- 2095.2333984375,- 86.02467346191406,- 2095.2333984375- ],- "score": 0.9999808073043823- },- {- "category_id": 4,- "poly": [- 88.29225158691406,- 709.4813842773438,- 1538.2086181640625,- 709.4813842773438,- 1538.2086181640625,- 758.3853149414062,- 88.29225158691406,- 758.3853149414062- ],- "score": 0.9999644160270691- },- {- "category_id": 1,- "poly": [- 91.33769226074219,- 1770.4210205078125,- 787.563720703125,- 1770.4210205078125,- 787.563720703125,- 1824.697021484375,- 91.33769226074219,- 1824.697021484375- ],- "score": 0.9999616146087646- },- {- "category_id": 4,- "poly": [- 89.59349060058594,- 1256.2301025390625,- 787.7970581054688,- 1256.2301025390625,- 787.7970581054688,- 1301.826171875,- 89.59349060058594,- 1301.826171875- ],- "score": 0.9998611807823181- },- {- "category_id": 1,- "poly": [- 838.697509765625,- 1303.13720703125,- 1535.5999755859375,- 1303.13720703125,- 1535.5999755859375,- 1622.256103515625,- 838.697509765625,- 1622.256103515625- ],- "score": 0.9998583793640137- },- {- "category_id": 1,- "poly": [- 839.3837280273438,- 1624.2615966796875,- 1535.1070556640625,- 1624.2615966796875,- 1535.1070556640625,- 1824.7913818359375,- 839.3837280273438,- 1824.7913818359375- ],- "score": 0.9951456785202026- },- {- "category_id": 13,- "poly": [- 1225,- 925,- 1276,- 925,- 1276,- 953,- 1225,- 953- ],- "score": 0.89,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 406,- 1391,- 456,- 1391,- 456,- 1418,- 406,- 1418- ],- "score": 0.88,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 563,- 1797,- 614,- 1797,- 614,- 1825,- 563,- 1825- ],- "score": 0.87,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 966,- 838,- 1161,- 838,- 1161,- 867,- 966,- 867- ],- "score": 0.77,- "latex": "\\mathsf{A l-4C u/8\\,w t\\%T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 1497,- 1478,- 1530,- 1478,- 1530,- 1505,- 1497,- 1505- ],- "score": 0.66,- "latex": "(\\mathscr{x})"- },- {- "category_id": 13,- "poly": [- 183,- 1278,- 272,- 1278,- 272,- 1301,- 183,- 1301- ],- "score": 0.58,- "latex": "8\\,\\mathsf{w t}\\%\\mathrm{TiO}_{2}"- },- {- "category_id": 13,- "poly": [- 228,- 1904,- 269,- 1904,- 269,- 1927,- 228,- 1927- ],- "score": 0.56,- "latex": "(\\upmu\\mathrm{m})"- },- {- "category_id": 13,- "poly": [- 1333,- 1565,- 1367,- 1565,- 1367,- 1592,- 1333,- 1592- ],- "score": 0.53,- "latex": "(\\alpha)"- },- {- "category_id": 13,- "poly": [- 1279,- 713,- 1294,- 713,- 1294,- 733,- 1279,- 733- ],- "score": 0.48,- "latex": "\\mathrm{g}"- },- {- "category_id": 13,- "poly": [- 1127,- 1564,- 1160,- 1564,- 1160,- 1593,- 1127,- 1593- ],- "score": 0.42,- "latex": "(\\beta)"- },- {- "category_id": 13,- "poly": [- 497,- 710,- 569,- 710,- 569,- 733,- 497,- 733- ],- "score": 0.41,- "latex": "\\mathsf{w t}\\%\\mathrm{Ti}0_{2}"- },- {- "category_id": 13,- "poly": [- 442,- 710,- 493,- 710,- 493,- 733,- 442,- 733- ],- "score": 0.37,- "latex": "\\cdot4\\mathsf{C u}/2"- },- {- "category_id": 13,- "poly": [- 759,- 710,- 819,- 710,- 819,- 733,- 759,- 733- ],- "score": 0.3,- "latex": "/\\mathrm{t}\\%\\mathrm{Ti}{\\cal O}_{2}"- },- {- "category_id": 13,- "poly": [- 692,- 710,- 744,- 710,- 744,- 733,- 692,- 733- ],- "score": 0.3,- "latex": "\\cdot4\\mathrm{Cu}/8"- }- ],- "page_info": {- "page_no": 6,- "height": 2205,- "width": 1654- }- },- {- "layout_dets": [- {- "category_id": 3,- "poly": [- 369.993896484375,- 1025.989990234375,- 1307.3125,- 1025.989990234375,- 1307.3125,- 1628.5306396484375,- 369.993896484375,- 1628.5306396484375- ],- "score": 0.999998927116394- },- {- "category_id": 3,- "poly": [- 365.5954895019531,- 1760.14208984375,- 1305.3201904296875,- 1760.14208984375,- 1305.3201904296875,- 2056.136962890625,- 365.5954895019531,- 2056.136962890625- ],- "score": 0.9999980926513672- },- {- "category_id": 3,- "poly": [- 158.45411682128906,- 181.25823974609375,- 778.4968872070312,- 181.25823974609375,- 778.4968872070312,- 554.7548828125,- 158.45411682128906,- 554.7548828125- ],- "score": 0.9999955892562866- },- {- "category_id": 1,- "poly": [- 117.11503601074219,- 658.9713745117188,- 817.1693725585938,- 658.9713745117188,- 817.1693725585938,- 980.625732421875,- 117.11503601074219,- 980.625732421875- ],- "score": 0.9999954104423523- },- {- "category_id": 1,- "poly": [- 863.5519409179688,- 182.35403442382812,- 1565.46240234375,- 182.35403442382812,- 1565.46240234375,- 387.18804931640625,- 863.5519409179688,- 387.18804931640625- ],- "score": 0.9999946355819702- },- {- "category_id": 4,- "poly": [- 114.14527893066406,- 1638.676513671875,- 1567.2890625,- 1638.676513671875,- 1567.2890625,- 1717.432373046875,- 114.14527893066406,- 1717.432373046875- ],- "score": 0.9999929666519165- },- {- "category_id": 1,- "poly": [- 863.70361328125,- 486.5367736816406,- 1564.496826171875,- 486.5367736816406,- 1564.496826171875,- 689.2080688476562,- 863.70361328125,- 689.2080688476562- ],- "score": 0.9999901652336121- },- {- "category_id": 1,- "poly": [- 864.369384765625,- 689.6195068359375,- 1565.134521484375,- 689.6195068359375,- 1565.134521484375,- 981.2111206054688,- 864.369384765625,- 981.2111206054688- ],- "score": 0.9999884366989136- },- {- "category_id": 9,- "poly": [- 1530.6024169921875,- 431.962890625,- 1562.739013671875,- 431.962890625,- 1562.739013671875,- 462.3264465332031,- 1530.6024169921875,- 462.3264465332031- ],- "score": 0.9999829530715942- },- {- "category_id": 2,- "poly": [- 528.20263671875,- 129.11875915527344,- 1153.5458984375,- 129.11875915527344,- 1153.5458984375,- 152.70664978027344,- 528.20263671875,- 152.70664978027344- ],- "score": 0.9999731779098511- },- {- "category_id": 4,- "poly": [- 127.99922180175781,- 569.7291259765625,- 805.6174926757812,- 569.7291259765625,- 805.6174926757812,- 592.1964111328125,- 127.99922180175781,- 592.1964111328125- ],- "score": 0.9999423027038574- },- {- "category_id": 2,- "poly": [- 1530.2342529296875,- 130.36260986328125,- 1562.608154296875,- 130.36260986328125,- 1562.608154296875,- 151.24363708496094,- 1530.2342529296875,- 151.24363708496094- ],- "score": 0.999907374382019- },- {- "category_id": 4,- "poly": [- 287.3680725097656,- 2076.7841796875,- 1393.78759765625,- 2076.7841796875,- 1393.78759765625,- 2099.181884765625,- 287.3680725097656,- 2099.181884765625- ],- "score": 0.9998682737350464- },- {- "category_id": 8,- "poly": [- 860.1067504882812,- 412.01446533203125,- 1015.9995727539062,- 412.01446533203125,- 1015.9995727539062,- 475.002685546875,- 860.1067504882812,- 475.002685546875- ],- "score": 0.9998018145561218- },- {- "category_id": 14,- "poly": [- 860,- 413,- 1014,- 413,- 1014,- 474,- 860,- 474- ],- "score": 0.92,- "latex": "V=\\frac{S D}{\\bar{x}}\\times100\\"- },- {- "category_id": 13,- "poly": [- 1366,- 632,- 1466,- 632,- 1466,- 658,- 1366,- 658- ],- "score": 0.9,- "latex": "V={\\sim}16\\%"- },- {- "category_id": 13,- "poly": [- 1222,- 690,- 1273,- 690,- 1273,- 718,- 1222,- 718- ],- "score": 0.89,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 1466,- 719,- 1515,- 719,- 1515,- 747,- 1466,- 747- ],- "score": 0.89,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 1012,- 516,- 1064,- 516,- 1064,- 544,- 1012,- 544- ],- "score": 0.87,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 709,- 1643,- 750,- 1643,- 750,- 1666,- 709,- 1666- ],- "score": 0.87,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 968,- 359,- 986,- 359,- 986,- 382,- 968,- 382- ],- "score": 0.73,- "latex": "\\bar{x}"- },- {- "category_id": 13,- "poly": [- 548,- 1667,- 629,- 1667,- 629,- 1691,- 548,- 1691- ],- "score": 0.39,- "latex": "\\mathsf{A l-}4\\mathsf{C u}/2"- },- {- "category_id": 13,- "poly": [- 694,- 1669,- 704,- 1669,- 704,- 1690,- 694,- 1690- ],- "score": 0.31,- "latex": "\\vert_{2}"- },- {- "category_id": 13,- "poly": [- 324,- 1691,- 479,- 1691,- 479,- 1714,- 324,- 1714- ],- "score": 0.29,- "latex": "\\mathsf{A l-4C u/8\\,w t\\%T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 1156,- 2077,- 1188,- 2077,- 1188,- 2099,- 1156,- 2099- ],- "score": 0.26,- "latex": "\\Gamma\\mathrm{i}O_{2}"- }- ],- "page_info": {- "page_no": 7,- "height": 2205,- "width": 1654- }- },- {- "layout_dets": [- {- "category_id": 3,- "poly": [- 315.550537109375,- 1421.5843505859375,- 1307.8612060546875,- 1421.5843505859375,- 1307.8612060546875,- 2034.2489013671875,- 315.550537109375,- 2034.2489013671875- ],- "score": 0.9999936819076538- },- {- "category_id": 3,- "poly": [- 125.49573516845703,- 183.7899627685547,- 757.64404296875,- 183.7899627685547,- 757.64404296875,- 602.4992065429688,- 125.49573516845703,- 602.4992065429688- ],- "score": 0.9999936819076538- },- {- "category_id": 2,- "poly": [- 90.73932647705078,- 131.2456512451172,- 124.18511199951172,- 131.2456512451172,- 124.18511199951172,- 150.24986267089844,- 90.73932647705078,- 150.24986267089844- ],- "score": 0.9999882578849792- },- {- "category_id": 1,- "poly": [- 90.7034912109375,- 707.3358764648438,- 790.2741088867188,- 707.3358764648438,- 790.2741088867188,- 820.606201171875,- 90.7034912109375,- 820.606201171875- ],- "score": 0.9999868869781494- },- {- "category_id": 1,- "poly": [- 837.475341796875,- 184.11471557617188,- 1537.574462890625,- 184.11471557617188,- 1537.574462890625,- 822.212890625,- 837.475341796875,- 822.212890625- ],- "score": 0.9999837279319763- },- {- "category_id": 4,- "poly": [- 89.11482238769531,- 2053.7275390625,- 1536.4208984375,- 2053.7275390625,- 1536.4208984375,- 2100.177490234375,- 89.11482238769531,- 2100.177490234375- ],- "score": 0.999964714050293- },- {- "category_id": 2,- "poly": [- 500.9217529296875,- 128.96173095703125,- 1125.63623046875,- 128.96173095703125,- 1125.63623046875,- 153.2847137451172,- 500.9217529296875,- 153.2847137451172- ],- "score": 0.9999575614929199- },- {- "category_id": 5,- "poly": [- 85.36759948730469,- 1216.1656494140625,- 1540.72998046875,- 1216.1656494140625,- 1540.72998046875,- 1372.0894775390625,- 85.36759948730469,- 1372.0894775390625- ],- "score": 0.9998849630355835- },- {- "category_id": 5,- "poly": [- 88.48777770996094,- 939.8333129882812,- 1542.62939453125,- 939.8333129882812,- 1542.62939453125,- 1093.4588623046875,- 88.48777770996094,- 1093.4588623046875- ],- "score": 0.9998706579208374- },- {- "category_id": 4,- "poly": [- 140.62600708007812,- 619.0916137695312,- 738.7869262695312,- 619.0916137695312,- 738.7869262695312,- 641.984375,- 140.62600708007812,- 641.984375- ],- "score": 0.9997395873069763- },- {- "category_id": 6,- "poly": [- 90.02525329589844,- 1164.81298828125,- 1012.4185180664062,- 1164.81298828125,- 1012.4185180664062,- 1210.54345703125,- 90.02525329589844,- 1210.54345703125- ],- "score": 0.999527096748352- },- {- "category_id": 6,- "poly": [- 86.55492401123047,- 888.3580322265625,- 1012.7340087890625,- 888.3580322265625,- 1012.7340087890625,- 934.6002807617188,- 86.55492401123047,- 934.6002807617188- ],- "score": 0.9986597299575806- },- {- "category_id": 13,- "poly": [- 835,- 735,- 1030,- 735,- 1030,- 764,- 835,- 764- ],- "score": 0.88,- "latex": "\\mathsf{A l-4C u}/2\\,\\mathsf{w t\\%T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 835,- 532,- 945,- 532,- 945,- 559,- 835,- 559- ],- "score": 0.87,- "latex": "8\\,\\mathsf{w t}\\%\\mathrm{TiO}_{2}"- },- {- "category_id": 13,- "poly": [- 1251,- 532,- 1295,- 532,- 1295,- 558,- 1251,- 558- ],- "score": 0.86,- "latex": "46\\%"- },- {- "category_id": 13,- "poly": [- 1080,- 503,- 1126,- 503,- 1126,- 530,- 1080,- 530- ],- "score": 0.86,- "latex": "52\\%"- },- {- "category_id": 13,- "poly": [- 1375,- 474,- 1486,- 474,- 1486,- 502,- 1375,- 502- ],- "score": 0.84,- "latex": "2\\,\\mathsf{w t}\\%\\mathrm{Ti}0_{2}"- },- {- "category_id": 13,- "poly": [- 1210,- 620,- 1248,- 620,- 1248,- 647,- 1210,- 647- ],- "score": 0.81,- "latex": "\\left(\\varepsilon_{\\mathrm{r}}\\right)"- },- {- "category_id": 13,- "poly": [- 722,- 2052,- 803,- 2052,- 803,- 2075,- 722,- 2075- ],- "score": 0.75,- "latex": "\\mathsf{A l-}4\\mathsf{C u}/2"- },- {- "category_id": 13,- "poly": [- 1342,- 735,- 1536,- 735,- 1536,- 764,- 1342,- 764- ],- "score": 0.67,- "latex": "\\mathsf{A l-4C u/8\\,w t\\%T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 805,- 2052,- 878,- 2052,- 878,- 2075,- 805,- 2075- ],- "score": 0.65,- "latex": "\\mathsf{w t}\\%\\mathrm{Ti}0_{2}"- },- {- "category_id": 13,- "poly": [- 1196,- 2051,- 1277,- 2051,- 1277,- 2076,- 1196,- 2076- ],- "score": 0.52,- "latex": "\\mathsf{A l-}4\\mathsf{C u}/8"- },- {- "category_id": 13,- "poly": [- 440,- 911,- 519,- 911,- 519,- 935,- 440,- 935- ],- "score": 0.45,- "latex": "\\mathsf{A l-}4\\mathsf{C u}/2"- },- {- "category_id": 13,- "poly": [- 469,- 1188,- 519,- 1188,- 519,- 1212,- 469,- 1212- ],- "score": 0.34,- "latex": "4\\mathrm{Cu}/8"- },- {- "category_id": 13,- "poly": [- 520,- 911,- 593,- 911,- 593,- 934,- 520,- 934- ],- "score": 0.27,- "latex": "\\mathsf{w t}\\%\\mathrm{Ti}0_{2}"- }- ],- "page_info": {- "page_no": 8,- "height": 2205,- "width": 1654- }- },- {- "layout_dets": [- {- "category_id": 1,- "poly": [- 125.04467010498047,- 1900.961669921875,- 818.0674438476562,- 1900.961669921875,- 818.0674438476562,- 2099.676513671875,- 125.04467010498047,- 2099.676513671875- ],- "score": 0.9999930262565613- },- {- "category_id": 1,- "poly": [- 117.00285339355469,- 479.2565002441406,- 815.6820068359375,- 479.2565002441406,- 815.6820068359375,- 858.2724609375,- 117.00285339355469,- 858.2724609375- ],- "score": 0.9999915957450867- },- {- "category_id": 1,- "poly": [- 117.78018188476562,- 859.7821655273438,- 816.0628662109375,- 859.7821655273438,- 816.0628662109375,- 1264.90966796875,- 117.78018188476562,- 1264.90966796875- ],- "score": 0.9999914169311523- },- {- "category_id": 1,- "poly": [- 862.9544677734375,- 472.034423828125,- 1571.095458984375,- 472.034423828125,- 1571.095458984375,- 2097.14453125,- 862.9544677734375,- 2097.14453125- ],- "score": 0.9999908804893494- },- {- "category_id": 1,- "poly": [- 117.97256469726562,- 1368.7080078125,- 816.1634521484375,- 1368.7080078125,- 816.1634521484375,- 1803.0389404296875,- 117.97256469726562,- 1803.0389404296875- ],- "score": 0.9999855756759644- },- {- "category_id": 6,- "poly": [- 113.38352966308594,- 183.38063049316406,- 1333.41357421875,- 183.38063049316406,- 1333.41357421875,- 232.4031982421875,- 113.38352966308594,- 232.4031982421875- ],- "score": 0.9999827146530151- },- {- "category_id": 5,- "poly": [- 111.89353942871094,- 231.0700225830078,- 1569.332763671875,- 231.0700225830078,- 1569.332763671875,- 428.4253845214844,- 111.89353942871094,- 428.4253845214844- ],- "score": 0.9999675154685974- },- {- "category_id": 2,- "poly": [- 1530.6534423828125,- 130.892822265625,- 1564.269287109375,- 130.892822265625,- 1564.269287109375,- 150.33241271972656,- 1530.6534423828125,- 150.33241271972656- ],- "score": 0.9999557733535767- },- {- "category_id": 0,- "poly": [- 118.35118103027344,- 1847.25,- 238.82887268066406,- 1847.25,- 238.82887268066406,- 1869.611083984375,- 118.35118103027344,- 1869.611083984375- ],- "score": 0.9999529719352722- },- {- "category_id": 0,- "poly": [- 117.5119857788086,- 1311.59375,- 277.2406005859375,- 1311.59375,- 277.2406005859375,- 1336.6551513671875,- 117.5119857788086,- 1336.6551513671875- ],- "score": 0.9999474287033081- },- {- "category_id": 2,- "poly": [- 528.5934448242188,- 131.14019775390625,- 1153.2890625,- 131.14019775390625,- 1153.2890625,- 152.47512817382812,- 528.5934448242188,- 152.47512817382812- ],- "score": 0.9996868968009949- },- {- "category_id": 13,- "poly": [- 1069,- 1810,- 1168,- 1810,- 1168,- 1833,- 1069,- 1833- ],- "score": 0.89,- "latex": "{\\mathrm{Al}}_{6061}\\mathrm{-TiO}_{2}"- },- {- "category_id": 13,- "poly": [- 515,- 568,- 661,- 568,- 661,- 596,- 515,- 596- ],- "score": 0.86,- "latex": "\\mathsf{A l-4C u}/2\\mathrm{Ti}0_{2}"- },- {- "category_id": 13,- "poly": [- 444,- 1427,- 494,- 1427,- 494,- 1455,- 444,- 1455- ],- "score": 0.78,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 115,- 946,- 227,- 946,- 227,- 974,- 115,- 974- ],- "score": 0.77,- "latex": "8\\,\\mathsf{w t}\\%\\mathrm{TiO}_{2}"- },- {- "category_id": 13,- "poly": [- 727,- 916,- 817,- 916,- 817,- 946,- 727,- 946- ],- "score": 0.72,- "latex": "\\mathsf{A l-4C u}/"- },- {- "category_id": 13,- "poly": [- 465,- 916,- 661,- 916,- 661,- 946,- 465,- 946- ],- "score": 0.7,- "latex": "\\mathsf{A l-4C u}/2\\,\\mathsf{w t\\%T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 347,- 626,- 491,- 626,- 491,- 654,- 347,- 654- ],- "score": 0.57,- "latex": "\\mathsf{A l-4C u/8T i O_{2}}"- },- {- "category_id": 13,- "poly": [- 735,- 207,- 814,- 207,- 814,- 232,- 735,- 232- ],- "score": 0.51,- "latex": "\\mathsf{A l-}4\\mathsf{C u}/8"- },- {- "category_id": 13,- "poly": [- 544,- 208,- 623,- 208,- 623,- 232,- 544,- 232- ],- "score": 0.48,- "latex": "\\mathsf{A l-}4\\mathsf{C u}/2"- },- {- "category_id": 13,- "poly": [- 427,- 626,- 491,- 626,- 491,- 654,- 427,- 654- ],- "score": 0.47,- "latex": "I8\\mathrm{Ti}0_{2}"- },- {- "category_id": 13,- "poly": [- 1517,- 1966,- 1564,- 1966,- 1564,- 1988,- 1517,- 1988- ],- "score": 0.38,- "latex": "\\cdot\\mathrm{Cu}_{2}\\mathrm{O}"- },- {- "category_id": 13,- "poly": [- 819,- 208,- 888,- 208,- 888,- 232,- 819,- 232- ],- "score": 0.33,- "latex": "\\mathsf{w t}\\%\\mathrm{TiO}_{2}"- }- ],- "page_info": {- "page_no": 9,- "height": 2205,- "width": 1654- }- },- {- "layout_dets": [- {- "category_id": 1,- "poly": [- 90.40060424804688,- 183.71102905273438,- 789.5450439453125,- 183.71102905273438,- 789.5450439453125,- 382.33282470703125,- 90.40060424804688,- 382.33282470703125- ],- "score": 0.9999990463256836- },- {- "category_id": 1,- "poly": [- 836.6307373046875,- 184.17138671875,- 1536.8868408203125,- 184.17138671875,- 1536.8868408203125,- 382.59735107421875,- 836.6307373046875,- 382.59735107421875- ],- "score": 0.999998927116394- },- {- "category_id": 2,- "poly": [- 90.23284149169922,- 131.502197265625,- 124.1571044921875,- 131.502197265625,- 124.1571044921875,- 149.82269287109375,- 90.23284149169922,- 149.82269287109375- ],- "score": 0.9999933242797852- },- {- "category_id": 2,- "poly": [- 500.88983154296875,- 131.4154052734375,- 1124.84375,- 131.4154052734375,- 1124.84375,- 152.89871215820312,- 500.88983154296875,- 152.89871215820312- ],- "score": 0.9999567866325378- },- {- "category_id": 13,- "poly": [- 293,- 361,- 335,- 361,- 335,- 384,- 293,- 384- ],- "score": 0.47,- "latex": "\\mathrm{SiO}_{2}"- },- {- "category_id": 13,- "poly": [- 230,- 361,- 335,- 361,- 335,- 384,- 230,- 384- ],- "score": 0.32,- "latex": "6061\\mathrm{~-~}\\mathrm{TiO}_{2}"- }- ],- "page_info": {- "page_no": 10,- "height": 2205,- "width": 1654- }- }-]\ No newline at end of filediff --git a/tests/test_cli/pdf_dev/academic_literature_f7904bc37cc2e25c1e3e412978854b10_model.json b/tests/test_cli/pdf_dev/academic_literature_f7904bc37cc2e25c1e3e412978854b10_model.jsondeleted file mode 100644index 50d29e07..00000000--- a/tests/test_cli/pdf_dev/academic_literature_f7904bc37cc2e25c1e3e412978854b10_model.json+++ /dev/null@@ -1,2029 +0,0 @@-[- {- "layout_dets": [- {- "category_id": 2,- "poly": [- 126.50015258789062,- 128.93304443359375,- 540.679931640625,- 128.93304443359375,- 540.679931640625,- 226.92637634277344,- 126.50015258789062,- 226.92637634277344- ],- "score": 0.9999887347221375- },- {- "category_id": 0,- "poly": [- 130.72247314453125,- 532.6777954101562,- 1501.8043212890625,- 532.6777954101562,- 1501.8043212890625,- 690.7334594726562,- 130.72247314453125,- 690.7334594726562- ],- "score": 0.9999832510948181- },- {- "category_id": 1,- "poly": [- 854.5001831054688,- 1298.847412109375,- 1522.951904296875,- 1298.847412109375,- 1522.951904296875,- 1908.7020263671875,- 854.5001831054688,- 1908.7020263671875- ],- "score": 0.9999802112579346- },- {- "category_id": 1,- "poly": [- 854.1588134765625,- 1057.34716796875,- 1522.5185546875,- 1057.34716796875,- 1522.5185546875,- 1296.958251953125,- 854.1588134765625,- 1296.958251953125- ],- "score": 0.999922513961792- },- {- "category_id": 1,- "poly": [- 129.9320526123047,- 995.6026611328125,- 811.706298828125,- 995.6026611328125,- 811.706298828125,- 1205.6361083984375,- 129.9320526123047,- 1205.6361083984375- ],- "score": 0.9998705387115479- },- {- "category_id": 1,- "poly": [- 854.8023071289062,- 1914.2344970703125,- 1523.3448486328125,- 1914.2344970703125,- 1523.3448486328125,- 2062.06005859375,- 854.8023071289062,- 2062.06005859375- ],- "score": 0.9998676180839539- },- {- "category_id": 1,- "poly": [- 129.7725830078125,- 771.8756713867188,- 1463.919189453125,- 771.8756713867188,- 1463.919189453125,- 829.7714233398438,- 129.7725830078125,- 829.7714233398438- ],- "score": 0.9998531341552734- },- {- "category_id": 1,- "poly": [- 131.63143920898438,- 1848.7064208984375,- 813.7200927734375,- 1848.7064208984375,- 813.7200927734375,- 1908.3885498046875,- 131.63143920898438,- 1908.3885498046875- ],- "score": 0.9997979998588562- },- {- "category_id": 1,- "poly": [- 131.2013702392578,- 711.3101806640625,- 974.0772705078125,- 711.3101806640625,- 974.0772705078125,- 746.839111328125,- 131.2013702392578,- 746.839111328125- ],- "score": 0.9996878504753113- },- {- "category_id": 1,- "poly": [- 129.92178344726562,- 1453.175537109375,- 812.6341552734375,- 1453.175537109375,- 812.6341552734375,- 1632.7532958984375,- 129.92178344726562,- 1632.7532958984375- ],- "score": 0.9996528625488281- },- {- "category_id": 0,- "poly": [- 854.4719848632812,- 997.0496215820312,- 1004.6527099609375,- 997.0496215820312,- 1004.6527099609375,- 1020.6658935546875,- 854.4719848632812,- 1020.6658935546875- ],- "score": 0.99927818775177- },- {- "category_id": 1,- "poly": [- 129.71356201171875,- 1300.873779296875,- 812.8416137695312,- 1300.873779296875,- 812.8416137695312,- 1450.150146484375,- 129.71356201171875,- 1450.150146484375- ],- "score": 0.9991269111633301- },- {- "category_id": 1,- "poly": [- 129.04617309570312,- 1208.1441650390625,- 812.42919921875,- 1208.1441650390625,- 812.42919921875,- 1298.6868896484375,- 129.04617309570312,- 1298.6868896484375- ],- "score": 0.9990298748016357- },- {- "category_id": 1,- "poly": [- 129.8084716796875,- 1636.7369384765625,- 812.437255859375,- 1636.7369384765625,- 812.437255859375,- 1816.5880126953125,- 129.8084716796875,- 1816.5880126953125- ],- "score": 0.9989234805107117- },- {- "category_id": 2,- "poly": [- 133.50637817382812,- 2036.548583984375,- 350.5669860839844,- 2036.548583984375,- 350.5669860839844,- 2059.908203125,- 133.50637817382812,- 2059.908203125- ],- "score": 0.9984697699546814- },- {- "category_id": 2,- "poly": [- 1034.2279052734375,- 131.83363342285156,- 1528.302001953125,- 131.83363342285156,- 1528.302001953125,- 184.0697784423828,- 1034.2279052734375,- 184.0697784423828- ],- "score": 0.9977995753288269- },- {- "category_id": 1,- "poly": [- 129.7623748779297,- 855.4282836914062,- 858.1234741210938,- 855.4282836914062,- 858.1234741210938,- 880.0763549804688,- 129.7623748779297,- 880.0763549804688- ],- "score": 0.9964384436607361- },- {- "category_id": 1,- "poly": [- 131.41041564941406,- 429.4252624511719,- 484.5693054199219,- 429.4252624511719,- 484.5693054199219,- 474.6931457519531,- 131.41041564941406,- 474.6931457519531- ],- "score": 0.8408285975456238- },- {- "category_id": 0,- "poly": [- 131.45191955566406,- 429.0645446777344,- 484.478271484375,- 429.0645446777344,- 484.478271484375,- 474.9486083984375,- 131.45191955566406,- 474.9486083984375- ],- "score": 0.3361666798591614- },- {- "category_id": 13,- "poly": [- 129,- 1329,- 317,- 1329,- 317,- 1361,- 129,- 1361- ],- "score": 0.88,- "latex": "10{\\cdot}300\\,\\upmu\\mathrm{mol}/\\mathrm{kg})"- },- {- "category_id": 13,- "poly": [- 408,- 1605,- 499,- 1605,- 499,- 1634,- 408,- 1634- ],- "score": 0.86,- "latex": "(l7\\pm4)"- },- {- "category_id": 13,- "poly": [- 450,- 1574,- 542,- 1574,- 542,- 1604,- 450,- 1604- ],- "score": 0.8,- "latex": "(\\mathsf{p}\\!\\!<\\!\\!0.01)"- },- {- "category_id": 13,- "poly": [- 126,- 1605,- 173,- 1605,- 173,- 1634,- 126,- 1634- ],- "score": 0.68,- "latex": "\\pm\\nobreakspace2\\nobreakspace"- },- {- "category_id": 13,- "poly": [- 487,- 1358,- 616,- 1358,- 616,- 1391,- 487,- 1391- ],- "score": 0.65,- "latex": "(^{51}\\mathrm{CrEDTA})"- },- {- "category_id": 13,- "poly": [- 127,- 203,- 149,- 203,- 149,- 225,- 127,- 225- ],- "score": 0.53,- "latex": "\\copyright"- }- ],- "page_info": {- "page_no": 0,- "height": 2181,- "width": 1653- }- },- {- "layout_dets": [- {- "category_id": 0,- "poly": [- 131.0747528076172,- 1646.9365234375,- 232.2142333984375,- 1646.9365234375,- 232.2142333984375,- 1674.91015625,- 131.0747528076172,- 1674.91015625- ],- "score": 0.999990701675415- },- {- "category_id": 1,- "poly": [- 854.1908569335938,- 457.566650390625,- 1522.8731689453125,- 457.566650390625,- 1522.8731689453125,- 716.369873046875,- 854.1908569335938,- 716.369873046875- ],- "score": 0.9999818801879883- },- {- "category_id": 1,- "poly": [- 854.4945678710938,- 199.6878662109375,- 1523.6170654296875,- 199.6878662109375,- 1523.6170654296875,- 327.42291259765625,- 854.4945678710938,- 327.42291259765625- ],- "score": 0.999980628490448- },- {- "category_id": 1,- "poly": [- 853.7386474609375,- 843.7147216796875,- 1524.1510009765625,- 843.7147216796875,- 1524.1510009765625,- 1494.796630859375,- 853.7386474609375,- 1494.796630859375- ],- "score": 0.9999773502349854- },- {- "category_id": 1,- "poly": [- 129.98367309570312,- 1775.478271484375,- 798.7672119140625,- 1775.478271484375,- 798.7672119140625,- 2061.471923828125,- 129.98367309570312,- 2061.471923828125- ],- "score": 0.9999737739562988- },- {- "category_id": 1,- "poly": [- 854.2423706054688,- 1623.10107421875,- 1523.447998046875,- 1623.10107421875,- 1523.447998046875,- 1828.6688232421875,- 854.2423706054688,- 1828.6688232421875- ],- "score": 0.9999676942825317- },- {- "category_id": 2,- "poly": [- 1117.2716064453125,- 131.07754516601562,- 1525.3043212890625,- 131.07754516601562,- 1525.3043212890625,- 153.0941925048828,- 1117.2716064453125,- 153.0941925048828- ],- "score": 0.999963641166687- },- {- "category_id": 1,- "poly": [- 129.4814910888672,- 200.13360595703125,- 798.3907470703125,- 200.13360595703125,- 798.3907470703125,- 748.1752319335938,- 129.4814910888672,- 748.1752319335938- ],- "score": 0.9999613761901855- },- {- "category_id": 1,- "poly": [- 854.3500366210938,- 1960.907470703125,- 1521.8297119140625,- 1960.907470703125,- 1521.8297119140625,- 2059.875732421875,- 854.3500366210938,- 2059.875732421875- ],- "score": 0.9999498128890991- },- {- "category_id": 0,- "poly": [- 855.2539672851562,- 785.2300415039062,- 1112.8525390625,- 785.2300415039062,- 1112.8525390625,- 809.8038940429688,- 855.2539672851562,- 809.8038940429688- ],- "score": 0.9999380111694336- },- {- "category_id": 1,- "poly": [- 129.95936584472656,- 1060.7459716796875,- 798.635986328125,- 1060.7459716796875,- 798.635986328125,- 1576.5565185546875,- 129.95936584472656,- 1576.5565185546875- ],- "score": 0.9999300837516785- },- {- "category_id": 0,- "poly": [- 854.482666015625,- 396.4778137207031,- 1104.807373046875,- 396.4778137207031,- 1104.807373046875,- 421.73834228515625,- 854.482666015625,- 421.73834228515625- ],- "score": 0.9999269247055054- },- {- "category_id": 0,- "poly": [- 854.3327026367188,- 1897.323486328125,- 1061.5657958984375,- 1897.323486328125,- 1061.5657958984375,- 1925.312255859375,- 854.3327026367188,- 1925.312255859375- ],- "score": 0.9999227523803711- },- {- "category_id": 1,- "poly": [- 130.46299743652344,- 752.8681030273438,- 798.3680419921875,- 752.8681030273438,- 798.3680419921875,- 1056.0352783203125,- 130.46299743652344,- 1056.0352783203125- ],- "score": 0.9999172687530518- },- {- "category_id": 0,- "poly": [- 854.9552001953125,- 1562.7789306640625,- 1080.6656494140625,- 1562.7789306640625,- 1080.6656494140625,- 1591.3477783203125,- 854.9552001953125,- 1591.3477783203125- ],- "score": 0.9999111890792847- },- {- "category_id": 2,- "poly": [- 130.90972900390625,- 130.28379821777344,- 167.29371643066406,- 130.28379821777344,- 167.29371643066406,- 150.61325073242188,- 130.90972900390625,- 150.61325073242188- ],- "score": 0.9997210502624512- },- {- "category_id": 0,- "poly": [- 130.5743408203125,- 1713.660888671875,- 219.01223754882812,- 1713.660888671875,- 219.01223754882812,- 1739.568115234375,- 130.5743408203125,- 1739.568115234375- ],- "score": 0.9326722025871277- },- {- "category_id": 13,- "poly": [- 852,- 224,- 973,- 224,- 973,- 252,- 852,- 252- ],- "score": 0.89,- "latex": "300\\,\\upmu\\mathrm{mol}/\\mathrm{kg}"- },- {- "category_id": 13,- "poly": [- 1009,- 1286,- 1069,- 1286,- 1069,- 1313,- 1009,- 1313- ],- "score": 0.89,- "latex": "100\\,\\upmu\\mathrm{l}"- },- {- "category_id": 13,- "poly": [- 881,- 1649,- 925,- 1649,- 925,- 1675,- 881,- 1675- ],- "score": 0.89,- "latex": "\\mathrm{CO}_{2}"- },- {- "category_id": 13,- "poly": [- 975,- 1208,- 1025,- 1208,- 1025,- 1235,- 975,- 1235- ],- "score": 0.87,- "latex": "50\\,\\upmu\\mathrm{l}"- },- {- "category_id": 13,- "poly": [- 1179,- 1700,- 1235,- 1700,- 1235,- 1725,- 1179,- 1725- ],- "score": 0.87,- "latex": "0.9\\,\\%"- },- {- "category_id": 13,- "poly": [- 1375,- 1025,- 1425,- 1025,- 1425,- 1052,- 1375,- 1052- ],- "score": 0.86,- "latex": "50\\,\\upmu\\mathrm{l}"- },- {- "category_id": 13,- "poly": [- 127,- 1800,- 225,- 1800,- 225,- 1827,- 127,- 1827- ],- "score": 0.86,- "latex": "_{200-250\\mathrm{g}}"- },- {- "category_id": 13,- "poly": [- 958,- 586,- 1007,- 586,- 1007,- 610,- 958,- 610- ],- "score": 0.85,- "latex": "10\\,\\%"- },- {- "category_id": 13,- "poly": [- 1042,- 1313,- 1091,- 1313,- 1091,- 1337,- 1042,- 1337- ],- "score": 0.85,- "latex": "10\\,\\%"- },- {- "category_id": 13,- "poly": [- 1325,- 1155,- 1391,- 1155,- 1391,- 1182,- 1325,- 1182- ],- "score": 0.83,- "latex": "\\mathrm{{MgCl}}_{2}"- },- {- "category_id": 13,- "poly": [- 1003,- 894,- 1064,- 894,- 1064,- 921,- 1003,- 921- ],- "score": 0.82,- "latex": "\\mathrm{CaCl}_{2}"- },- {- "category_id": 13,- "poly": [- 984,- 225,- 1044,- 225,- 1044,- 249,- 984,- 249- ],- "score": 0.81,- "latex": "\\mathbf{\\tilde{n}}=8\\mathbf{\\tilde{\\ n}}"- },- {- "category_id": 13,- "poly": [- 1285,- 1779,- 1354,- 1779,- 1354,- 1803,- 1285,- 1803- ],- "score": 0.81,- "latex": "{>}5\\,\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 1441,- 1287,- 1518,- 1287,- 1518,- 1313,- 1441,- 1313- ],- "score": 0.81,- "latex": "1\\,\\mathrm{mg/ml}"- },- {- "category_id": 13,- "poly": [- 1451,- 843,- 1482,- 843,- 1482,- 869,- 1451,- 869- ],- "score": 0.8,- "latex": "1\\,\\mathrm{g}"- },- {- "category_id": 13,- "poly": [- 1037,- 480,- 1098,- 480,- 1098,- 508,- 1037,- 508- ],- "score": 0.8,- "latex": "10\\upmu\\mathrm{Ci}"- },- {- "category_id": 13,- "poly": [- 1148,- 1390,- 1199,- 1390,- 1199,- 1417,- 1148,- 1417- ],- "score": 0.76,- "latex": "50\\,\\upmu\\mathrm{l}"- },- {- "category_id": 13,- "poly": [- 1048,- 1182,- 1134,- 1182,- 1134,- 1207,- 1048,- 1207- ],- "score": 0.76,- "latex": "0.25\\,\\mathrm{mM}"- },- {- "category_id": 13,- "poly": [- 1464,- 481,- 1525,- 481,- 1525,- 506,- 1464,- 506- ],- "score": 0.74,- "latex": "0.5\\,\\mathrm{ml}"- },- {- "category_id": 13,- "poly": [- 851,- 1182,- 926,- 1182,- 926,- 1207,- 851,- 1207- ],- "score": 0.72,- "latex": "2.5\\,\\mathrm{mM}"- },- {- "category_id": 13,- "poly": [- 1152,- 869,- 1196,- 869,- 1196,- 893,- 1152,- 893- ],- "score": 0.69,- "latex": "4\\,\\mathrm{{m}l}"- },- {- "category_id": 13,- "poly": [- 1122,- 974,- 1229,- 974,- 1229,- 1000,- 1122,- 1000- ],- "score": 0.68,- "latex": "13{,}000\\,\\mathrm{rpm}"- },- {- "category_id": 13,- "poly": [- 852,- 1338,- 938,- 1338,- 938,- 1364,- 852,- 1364- ],- "score": 0.67,- "latex": "0.25\\,\\mathrm{mM}"- },- {- "category_id": 13,- "poly": [- 1095,- 1156,- 1164,- 1156,- 1164,- 1180,- 1095,- 1180- ],- "score": 0.65,- "latex": "50\\,\\mathrm{mM}"- },- {- "category_id": 13,- "poly": [- 1260,- 1313,- 1326,- 1313,- 1326,- 1339,- 1260,- 1339- ],- "score": 0.64,- "latex": "\\mathrm{{MgCl}}_{2}"- },- {- "category_id": 13,- "poly": [- 1214,- 1182,- 1309,- 1182,- 1309,- 1207,- 1214,- 1207- ],- "score": 0.6,- "latex": "20\\;0.05\\,\\%"- },- {- "category_id": 13,- "poly": [- 973,- 1418,- 1045,- 1418,- 1045,- 1442,- 973,- 1442- ],- "score": 0.6,- "latex": "405\\,\\mathrm{nm}"- },- {- "category_id": 13,- "poly": [- 960,- 1779,- 1028,- 1779,- 1028,- 1803,- 960,- 1803- ],- "score": 0.6,- "latex": "{\\tt\\le}5\\,\\mathrm{mm}"- },- {- "category_id": 13,- "poly": [- 1450,- 869,- 1519,- 869,- 1519,- 893,- 1450,- 893- ],- "score": 0.57,- "latex": "50\\,\\mathrm{mM}"- },- {- "category_id": 13,- "poly": [- 1266,- 894,- 1353,- 894,- 1353,- 919,- 1266,- 919- ],- "score": 0.56,- "latex": "0.25\\,\\mathrm{mM}"- },- {- "category_id": 13,- "poly": [- 1235,- 1155,- 1314,- 1155,- 1314,- 1180,- 1235,- 1180- ],- "score": 0.54,- "latex": "150\\,\\mathrm{mM}"- },- {- "category_id": 13,- "poly": [- 1478,- 1443,- 1526,- 1443,- 1526,- 1471,- 1478,- 1471- ],- "score": 0.54,- "latex": "\\mathrm{mg/l}"- },- {- "category_id": 13,- "poly": [- 1331,- 922,- 1440,- 922,- 1440,- 947,- 1331,- 947- ],- "score": 0.54,- "latex": "_{20,000\\,\\mathrm{rpm}}"- },- {- "category_id": 13,- "poly": [- 690,- 2035,- 801,- 2035,- 801,- 2063,- 690,- 2063- ],- "score": 0.52,- "latex": "60\\,\\upmu\\mathrm{mol}/\\mathrm{mol}"- },- {- "category_id": 13,- "poly": [- 664,- 1453,- 788,- 1453,- 788,- 1486,- 664,- 1486- ],- "score": 0.52,- "latex": "^{51}\\mathrm{CrEDTA})"- },- {- "category_id": 13,- "poly": [- 1396,- 1155,- 1470,- 1155,- 1470,- 1181,- 1396,- 1181- ],- "score": 0.47,- "latex": "0.5\\,\\mathrm{mM}"- },- {- "category_id": 13,- "poly": [- 912,- 894,- 991,- 894,- 991,- 920,- 912,- 920- ],- "score": 0.46,- "latex": "150\\,\\mathrm{mM}"- },- {- "category_id": 13,- "poly": [- 1070,- 894,- 1138,- 894,- 1138,- 920,- 1070,- 920- ],- "score": 0.41,- "latex": "10\\,\\mathrm{mM}"- },- {- "category_id": 13,- "poly": [- 1029,- 509,- 1073,- 509,- 1073,- 532,- 1029,- 532- ],- "score": 0.39,- "latex": "1\\,\\mathrm{mol}"- },- {- "category_id": 13,- "poly": [- 947,- 1338,- 1021,- 1338,- 1021,- 1365,- 947,- 1365- ],- "score": 0.34,- "latex": "\\mathrm{pH}\\ 9.6)"- },- {- "category_id": 13,- "poly": [- 1102,- 479,- 1204,- 479,- 1204,- 507,- 1102,- 507- ],- "score": 0.33,- "latex": "^{51}\\mathrm{CrEDTA}"- },- {- "category_id": 13,- "poly": [- 663,- 1453,- 704,- 1453,- 704,- 1484,- 663,- 1484- ],- "score": 0.31,- "latex": "^{51}\\mathrm{C}"- },- {- "category_id": 13,- "poly": [- 1260,- 1312,- 1405,- 1312,- 1405,- 1339,- 1260,- 1339- ],- "score": 0.28,- "latex": "\\mathrm{MgCl_{2}\\ 0.5\\,m M}"- },- {- "category_id": 13,- "poly": [- 1198,- 1290,- 1212,- 1290,- 1212,- 1313,- 1198,- 1313- ],- "score": 0.27,- "latex": "\\mathrm{\\bfp}"- }- ],- "page_info": {- "page_no": 1,- "height": 2181,- "width": 1653- }- },- {- "layout_dets": [- {- "category_id": 3,- "poly": [- 854.8114624023438,- 1000.0735473632812,- 1526.2498779296875,- 1000.0735473632812,- 1526.2498779296875,- 1602.6619873046875,- 854.8114624023438,- 1602.6619873046875- ],- "score": 0.9999911189079285- },- {- "category_id": 4,- "poly": [- 849.4373779296875,- 817.45849609375,- 1530.512451171875,- 817.45849609375,- 1530.512451171875,- 956.3124389648438,- 849.4373779296875,- 956.3124389648438- ],- "score": 0.9999908208847046- },- {- "category_id": 4,- "poly": [- 127.44953918457031,- 1929.2335205078125,- 801.6481323242188,- 1929.2335205078125,- 801.6481323242188,- 2066.464599609375,- 127.44953918457031,- 2066.464599609375- ],- "score": 0.9999856948852539- },- {- "category_id": 1,- "poly": [- 128.18153381347656,- 321.1024169921875,- 802.0577392578125,- 321.1024169921875,- 802.0577392578125,- 506.3064270019531,- 128.18153381347656,- 506.3064270019531- ],- "score": 0.9999765753746033- },- {- "category_id": 4,- "poly": [- 850.1302490234375,- 1621.6951904296875,- 1530.3858642578125,- 1621.6951904296875,- 1530.3858642578125,- 1736.14794921875,- 850.1302490234375,- 1736.14794921875- ],- "score": 0.9999746680259705- },- {- "category_id": 1,- "poly": [- 127.43219757080078,- 625.2225952148438,- 801.4795532226562,- 625.2225952148438,- 801.4795532226562,- 903.7083129882812,- 127.43219757080078,- 903.7083129882812- ],- "score": 0.9999739527702332- },- {- "category_id": 1,- "poly": [- 127.66834259033203,- 1022.7542724609375,- 802.6483764648438,- 1022.7542724609375,- 802.6483764648438,- 1180.9302978515625,- 127.66834259033203,- 1180.9302978515625- ],- "score": 0.999945342540741- },- {- "category_id": 0,- "poly": [- 852.8805541992188,- 1816.059326171875,- 981.3207397460938,- 1816.059326171875,- 981.3207397460938,- 1848.59228515625,- 852.8805541992188,- 1848.59228515625- ],- "score": 0.9999176263809204- },- {- "category_id": 3,- "poly": [- 861.9379272460938,- 198.4549560546875,- 1519.971923828125,- 198.4549560546875,- 1519.971923828125,- 801.3720703125,- 861.9379272460938,- 801.3720703125- ],- "score": 0.9999100565910339- },- {- "category_id": 3,- "poly": [- 129.3984375,- 1296.743408203125,- 801.4290771484375,- 1296.743408203125,- 801.4290771484375,- 1911.7489013671875,- 129.3984375,- 1911.7489013671875- ],- "score": 0.9999092817306519- },- {- "category_id": 1,- "poly": [- 850.8916015625,- 1877.3216552734375,- 1527.890625,- 1877.3216552734375,- 1527.890625,- 2067.06494140625,- 850.8916015625,- 2067.06494140625- ],- "score": 0.9998919367790222- },- {- "category_id": 2,- "poly": [- 124.14147186279297,- 130.1715850830078,- 1190.90234375,- 130.1715850830078,- 1190.90234375,- 157.70138549804688,- 124.14147186279297,- 157.70138549804688- ],- "score": 0.9996301531791687- },- {- "category_id": 2,- "poly": [- 1487.102294921875,- 128.76255798339844,- 1524.0087890625,- 128.76255798339844,- 1524.0087890625,- 152.51942443847656,- 1487.102294921875,- 152.51942443847656- ],- "score": 0.9978102445602417- },- {- "category_id": 1,- "poly": [- 128.83859252929688,- 260.12615966796875,- 385.3800964355469,- 260.12615966796875,- 385.3800964355469,- 292.27276611328125,- 128.83859252929688,- 292.27276611328125- ],- "score": 0.9885663986206055- },- {- "category_id": 0,- "poly": [- 128.97781372070312,- 963.9873657226562,- 418.56024169921875,- 963.9873657226562,- 418.56024169921875,- 992.4894409179688,- 128.97781372070312,- 992.4894409179688- ],- "score": 0.9732756614685059- },- {- "category_id": 0,- "poly": [- 128.39158630371094,- 567.232421875,- 392.3690185546875,- 567.232421875,- 392.3690185546875,- 596.4879150390625,- 128.39158630371094,- 596.4879150390625- ],- "score": 0.830464243888855- },- {- "category_id": 0,- "poly": [- 129.43605041503906,- 198.31634521484375,- 217.4158477783203,- 198.31634521484375,- 217.4158477783203,- 229.57237243652344,- 129.43605041503906,- 229.57237243652344- ],- "score": 0.6879984140396118- },- {- "category_id": 4,- "poly": [- 129.5968475341797,- 198.34027099609375,- 217.13697814941406,- 198.34027099609375,- 217.13697814941406,- 229.41558837890625,- 129.5968475341797,- 229.41558837890625- ],- "score": 0.3450572192668915- },- {- "category_id": 1,- "poly": [- 129.5113983154297,- 198.30056762695312,- 217.10781860351562,- 198.30056762695312,- 217.10781860351562,- 229.45274353027344,- 129.5113983154297,- 229.45274353027344- ],- "score": 0.32501277327537537- },- {- "category_id": 1,- "poly": [- 128.48004150390625,- 567.8143310546875,- 392.4095153808594,- 567.8143310546875,- 392.4095153808594,- 596.3490600585938,- 128.48004150390625,- 596.3490600585938- ],- "score": 0.23228876292705536- },- {- "category_id": 13,- "poly": [- 161,- 748,- 304,- 748,- 304,- 780,- 161,- 780- ],- "score": 0.91,- "latex": "300\\,\\upmu\\mathrm{mol}/\\mathrm{kg}"- },- {- "category_id": 13,- "poly": [- 415,- 1054,- 585,- 1054,- 585,- 1085,- 415,- 1085- ],- "score": 0.89,- "latex": "0{-}100\\,\\upmu\\mathrm{mol}/\\mathrm{kg}"- },- {- "category_id": 13,- "poly": [- 127,- 656,- 258,- 656,- 258,- 688,- 127,- 688- ],- "score": 0.89,- "latex": "30\\,\\upmu\\mathrm{mol}/\\mathrm{kg}"- },- {- "category_id": 13,- "poly": [- 1389,- 1702,- 1509,- 1702,- 1509,- 1730,- 1389,- 1730- ],- "score": 0.88,- "latex": "300\\,\\upmu\\mathrm{mol}/\\mathrm{kg}"- },- {- "category_id": 13,- "poly": [- 403,- 687,- 545,- 687,- 545,- 719,- 403,- 719- ],- "score": 0.88,- "latex": "100\\,\\upmu\\mathrm{mol}/\\mathrm{kg}"- },- {- "category_id": 13,- "poly": [- 407,- 1086,- 554,- 1086,- 554,- 1116,- 407,- 1116- ],- "score": 0.87,- "latex": "300\\,\\upmu\\mathrm{mol}/\\mathrm{kg})"- },- {- "category_id": 13,- "poly": [- 665,- 412,- 770,- 412,- 770,- 444,- 665,- 444- ],- "score": 0.83,- "latex": "\\mathrm{(p>}0.05)"- },- {- "category_id": 13,- "poly": [- 583,- 718,- 686,- 718,- 686,- 750,- 583,- 750- ],- "score": 0.82,- "latex": "\\left(\\mathrm{p}<\\!\\!0.05\\right)"- },- {- "category_id": 13,- "poly": [- 476,- 810,- 578,- 810,- 578,- 842,- 476,- 842- ],- "score": 0.82,- "latex": "({\\tt p}<\\!0.01)"- },- {- "category_id": 13,- "poly": [- 205,- 1146,- 319,- 1146,- 319,- 1178,- 205,- 1178- ],- "score": 0.8,- "latex": "(\\mathfrak{p}\\!<\\!0.001)"- },- {- "category_id": 13,- "poly": [- 131,- 412,- 244,- 412,- 244,- 444,- 131,- 444- ],- "score": 0.76,- "latex": "\\scriptstyle(\\mathtt{p}<0.001)"- },- {- "category_id": 13,- "poly": [- 755,- 1085,- 803,- 1085,- 803,- 1114,- 755,- 1114- ],- "score": 0.38,- "latex": "10-"- }- ],- "page_info": {- "page_no": 2,- "height": 2181,- "width": 1653- }- },- {- "layout_dets": [- {- "category_id": 1,- "poly": [- 849.5838623046875,- 878.706787109375,- 1529.954833984375,- 878.706787109375,- 1529.954833984375,- 2062.25048828125,- 849.5838623046875,- 2062.25048828125- ],- "score": 0.9999964237213135- },- {- "category_id": 1,- "poly": [- 851.5059204101562,- 197.32901000976562,- 1526.1309814453125,- 197.32901000976562,- 1526.1309814453125,- 412.517578125,- 851.5059204101562,- 412.517578125- ],- "score": 0.9999958276748657- },- {- "category_id": 1,- "poly": [- 127.03380584716797,- 320.2677307128906,- 802.3373413085938,- 320.2677307128906,- 802.3373413085938,- 778.7638549804688,- 127.03380584716797,- 778.7638549804688- ],- "score": 0.9999817609786987- },- {- "category_id": 0,- "poly": [- 854.364990234375,- 817.7249755859375,- 983.921875,- 817.7249755859375,- 983.921875,- 848.59765625,- 854.364990234375,- 848.59765625- ],- "score": 0.999971866607666- },- {- "category_id": 1,- "poly": [- 126.02391815185547,- 1573.8297119140625,- 802.7295532226562,- 1573.8297119140625,- 802.7295532226562,- 2063.943603515625,- 126.02391815185547,- 2063.943603515625- ],- "score": 0.9999658465385437- },- {- "category_id": 1,- "poly": [- 126.4128189086914,- 779.7554321289062,- 801.98388671875,- 779.7554321289062,- 801.98388671875,- 1236.2952880859375,- 126.4128189086914,- 1236.2952880859375- ],- "score": 0.9999641180038452- },- {- "category_id": 1,- "poly": [- 128.8470001220703,- 198.27818298339844,- 801.576416015625,- 198.27818298339844,- 801.576416015625,- 320.2906799316406,- 128.8470001220703,- 320.2906799316406- ],- "score": 0.9999555349349976- },- {- "category_id": 1,- "poly": [- 852.162841796875,- 411.9776916503906,- 1527.426513671875,- 411.9776916503906,- 1527.426513671875,- 627.5949096679688,- 852.162841796875,- 627.5949096679688- ],- "score": 0.9999544024467468- },- {- "category_id": 1,- "poly": [- 126.1973876953125,- 1237.482177734375,- 803.0906372070312,- 1237.482177734375,- 803.0906372070312,- 1573.64111328125,- 126.1973876953125,- 1573.64111328125- ],- "score": 0.9998923540115356- },- {- "category_id": 1,- "poly": [- 852.0659790039062,- 685.3585815429688,- 1526.1573486328125,- 685.3585815429688,- 1526.1573486328125,- 751.5690307617188,- 852.0659790039062,- 751.5690307617188- ],- "score": 0.9998598098754883- },- {- "category_id": 2,- "poly": [- 1116.092041015625,- 129.10800170898438,- 1527.0518798828125,- 129.10800170898438,- 1527.0518798828125,- 154.35687255859375,- 1116.092041015625,- 154.35687255859375- ],- "score": 0.9996548891067505- },- {- "category_id": 2,- "poly": [- 130.6074981689453,- 129.7509765625,- 166.90464782714844,- 129.7509765625,- 166.90464782714844,- 150.73068237304688,- 130.6074981689453,- 150.73068237304688- ],- "score": 0.9994045495986938- },- {- "category_id": 13,- "poly": [- 551,- 840,- 689,- 840,- 689,- 872,- 551,- 872- ],- "score": 0.89,- "latex": "30\\,\\upmu\\mathrm{mol}/\\mathrm{kg})"- },- {- "category_id": 13,- "poly": [- 333,- 1023,- 479,- 1023,- 479,- 1055,- 333,- 1055- ],- "score": 0.87,- "latex": "300\\,\\upmu\\mathrm{mol}/\\mathrm{kg}"- }- ],- "page_info": {- "page_no": 3,- "height": 2181,- "width": 1653- }- },- {- "layout_dets": [- {- "category_id": 1,- "poly": [- 850.2716064453125,- 197.65927124023438,- 1530.317626953125,- 197.65927124023438,- 1530.317626953125,- 641.234619140625,- 850.2716064453125,- 641.234619140625- ],- "score": 0.999996542930603- },- {- "category_id": 1,- "poly": [- 126.53795623779297,- 197.20611572265625,- 801.671875,- 197.20611572265625,- 801.671875,- 672.7994384765625,- 126.53795623779297,- 672.7994384765625- ],- "score": 0.9999955892562866- },- {- "category_id": 2,- "poly": [- 125.36932373046875,- 128.70034790039062,- 1188.8201904296875,- 128.70034790039062,- 1188.8201904296875,- 155.23692321777344,- 125.36932373046875,- 155.23692321777344- ],- "score": 0.9999717473983765- },- {- "category_id": 2,- "poly": [- 1489.344482421875,- 129.5157012939453,- 1526.055419921875,- 129.5157012939453,- 1526.055419921875,- 151.8965606689453,- 1489.344482421875,- 151.8965606689453- ],- "score": 0.9999598264694214- },- {- "category_id": 2,- "poly": [- 587.8172607421875,- 1163.7890625,- 1065.035888671875,- 1163.7890625,- 1065.035888671875,- 1266.2200927734375,- 587.8172607421875,- 1266.2200927734375- ],- "score": 0.9998905658721924- }- ],- "page_info": {- "page_no": 4,- "height": 2181,- "width": 1653- }- }-]\ No newline at end of filediff --git a/tests/test_cli/pdf_dev/academic_literature_fbdb99151e811688574c0c4c67341074_model.json b/tests/test_cli/pdf_dev/academic_literature_fbdb99151e811688574c0c4c67341074_model.jsondeleted file mode 100644index 74179bd6..00000000--- a/tests/test_cli/pdf_dev/academic_literature_fbdb99151e811688574c0c4c67341074_model.json+++ /dev/null@@ -1,2061 +0,0 @@-[- {- "layout_dets": [- {- "category_id": 4,- "poly": [- 863.2782592773438,- 1035.4449462890625,- 1566.4375,- 1035.4449462890625,- 1566.4375,- 1110.1534423828125,- 863.2782592773438,- 1110.1534423828125- ],- "score": 0.9999994039535522- },- {- "category_id": 0,- "poly": [- 374.12786865234375,- 1095.8162841796875,- 595.0630493164062,- 1095.8162841796875,- 595.0630493164062,- 1123.12060546875,- 374.12786865234375,- 1123.12060546875- ],- "score": 0.9999938011169434- },- {- "category_id": 1,- "poly": [- 865.3327026367188,- 1511.36181640625,- 1567.931640625,- 1511.36181640625,- 1567.931640625,- 1908.5230712890625,- 865.3327026367188,- 1908.5230712890625- ],- "score": 0.999992847442627- },- {- "category_id": 3,- "poly": [- 899.0333862304688,- 516.339111328125,- 1500.767578125,- 516.339111328125,- 1500.767578125,- 1002.146240234375,- 899.0333862304688,- 1002.146240234375- ],- "score": 0.9999920725822449- },- {- "category_id": 0,- "poly": [- 140.3105010986328,- 160.29049682617188,- 1558.3450927734375,- 160.29049682617188,- 1558.3450927734375,- 301.54150390625,- 140.3105010986328,- 301.54150390625- ],- "score": 0.9999915361404419- },- {- "category_id": 1,- "poly": [- 132.46669006347656,- 488.9729919433594,- 836.7824096679688,- 488.9729919433594,- 836.7824096679688,- 1014.5713500976562,- 132.46669006347656,- 1014.5713500976562- ],- "score": 0.9999898672103882- },- {- "category_id": 1,- "poly": [- 864.4011840820312,- 1206.3807373046875,- 1566.180419921875,- 1206.3807373046875,- 1566.180419921875,- 1502.9554443359375,- 864.4011840820312,- 1502.9554443359375- ],- "score": 0.9999885559082031- },- {- "category_id": 2,- "poly": [- 46.35005569458008,- 583.8515014648438,- 98.920654296875,- 583.8515014648438,- 98.920654296875,- 1574.2994384765625,- 46.35005569458008,- 1574.2994384765625- ],- "score": 0.9999722242355347- },- {- "category_id": 1,- "poly": [- 133.71018981933594,- 1134.7393798828125,- 837.6100463867188,- 1134.7393798828125,- 837.6100463867188,- 1733.16015625,- 133.71018981933594,- 1733.16015625- ],- "score": 0.9999712705612183- },- {- "category_id": 1,- "poly": [- 863.2889404296875,- 1915.9327392578125,- 1565.4844970703125,- 1915.9327392578125,- 1565.4844970703125,- 2079.54345703125,- 863.2889404296875,- 2079.54345703125- ],- "score": 0.9999582767486572- },- {- "category_id": 1,- "poly": [- 141.26788330078125,- 329.41650390625,- 1547.88134765625,- 329.41650390625,- 1547.88134765625,- 364.2337951660156,- 141.26788330078125,- 364.2337951660156- ],- "score": 0.9995179176330566- },- {- "category_id": 2,- "poly": [- 132.21490478515625,- 1753.2657470703125,- 836.714599609375,- 1753.2657470703125,- 836.714599609375,- 2079.021240234375,- 132.21490478515625,- 2079.021240234375- ],- "score": 0.9935375452041626- },- {- "category_id": 2,- "poly": [- 1548.62744140625,- 67.1996841430664,- 1566.5760498046875,- 67.1996841430664,- 1566.5760498046875,- 91.99691009521484,- 1548.62744140625,- 91.99691009521484- ],- "score": 0.8435658812522888- },- {- "category_id": 0,- "poly": [- 161.2336883544922,- 1031.1558837890625,- 747.5531616210938,- 1031.1558837890625,- 747.5531616210938,- 1057.9443359375,- 161.2336883544922,- 1057.9443359375- ],- "score": 0.8226985335350037- },- {- "category_id": 1,- "poly": [- 161.42782592773438,- 1031.3416748046875,- 747.2906494140625,- 1031.3416748046875,- 747.2906494140625,- 1058.0198974609375,- 161.42782592773438,- 1058.0198974609375- ],- "score": 0.5235136151313782- },- {- "category_id": 13,- "poly": [- 135,- 1400,- 249,- 1400,- 249,- 1432,- 135,- 1432- ],- "score": 0.68,- "latex": "(\\approx1\\,\\mathrm{Tb/s})"- },- {- "category_id": 13,- "poly": [- 280,- 1333,- 420,- 1333,- 420,- 1364,- 280,- 1364- ],- "score": 0.57,- "latex": "\\left(0.1{\\cdot}10\\,\\mathrm{THz}\\right)"- },- {- "category_id": 13,- "poly": [- 347,- 1880,- 366,- 1880,- 366,- 1900,- 347,- 1900- ],- "score": 0.56,- "latex": "@"- },- {- "category_id": 13,- "poly": [- 44,- 815,- 96,- 815,- 96,- 851,- 44,- 851- ],- "score": 0.37,- "latex": "\\cap"- },- {- "category_id": 13,- "poly": [- 345,- 1829,- 365,- 1829,- 365,- 1851,- 345,- 1851- ],- "score": 0.27,- "latex": "@"- }- ],- "page_info": {- "page_no": 0,- "height": 2200,- "width": 1700- }- },- {- "layout_dets": [- {- "category_id": 1,- "poly": [- 894.3416137695312,- 1848.383544921875,- 1566.903564453125,- 1848.383544921875,- 1566.903564453125,- 2079.466064453125,- 894.3416137695312,- 2079.466064453125- ],- "score": 0.9999867677688599- },- {- "category_id": 1,- "poly": [- 866.365234375,- 1705.896484375,- 1564.6666259765625,- 1705.896484375,- 1564.6666259765625,- 1835.31396484375,- 866.365234375,- 1835.31396484375- ],- "score": 0.9999860525131226- },- {- "category_id": 3,- "poly": [- 297.703369140625,- 157.119873046875,- 1303.635009765625,- 157.119873046875,- 1303.635009765625,- 1399.029052734375,- 297.703369140625,- 1399.029052734375- ],- "score": 0.9999844431877136- },- {- "category_id": 1,- "poly": [- 136.4300537109375,- 1705.1046142578125,- 833.2474365234375,- 1705.1046142578125,- 833.2474365234375,- 1902.489990234375,- 136.4300537109375,- 1902.489990234375- ],- "score": 0.9999755620956421- },- {- "category_id": 1,- "poly": [- 135.40646362304688,- 1915.3026123046875,- 833.69091796875,- 1915.3026123046875,- 833.69091796875,- 2079.314453125,- 135.40646362304688,- 2079.314453125- ],- "score": 0.999956488609314- },- {- "category_id": 4,- "poly": [- 134.93357849121094,- 1603.8221435546875,- 969.350830078125,- 1603.8221435546875,- 969.350830078125,- 1631.3472900390625,- 134.93357849121094,- 1631.3472900390625- ],- "score": 0.997449517250061- },- {- "category_id": 2,- "poly": [- 1551.055908203125,- 69.2196273803711,- 1568.1268310546875,- 69.2196273803711,- 1568.1268310546875,- 91.64757537841797,- 1551.055908203125,- 91.64757537841797- ],- "score": 0.9901553392410278- }- ],- "page_info": {- "page_no": 1,- "height": 2200,- "width": 1700- }- },- {- "layout_dets": [- {- "category_id": 1,- "poly": [- 133.6353759765625,- 1413.207275390625,- 836.9700927734375,- 1413.207275390625,- 836.9700927734375,- 1577.2298583984375,- 133.6353759765625,- 1577.2298583984375- ],- "score": 0.9999912977218628- },- {- "category_id": 1,- "poly": [- 133.57623291015625,- 796.8501586914062,- 836.7691650390625,- 796.8501586914062,- 836.7691650390625,- 961.833984375,- 133.57623291015625,- 961.833984375- ],- "score": 0.9999896883964539- },- {- "category_id": 1,- "poly": [- 863.9443969726562,- 1264.5728759765625,- 1567.9918212890625,- 1264.5728759765625,- 1567.9918212890625,- 1857.951904296875,- 863.9443969726562,- 1857.951904296875- ],- "score": 0.9999896287918091- },- {- "category_id": 1,- "poly": [- 864.5279541015625,- 1031.6209716796875,- 1566.75146484375,- 1031.6209716796875,- 1566.75146484375,- 1262.1263427734375,- 864.5279541015625,- 1262.1263427734375- ],- "score": 0.9999868273735046- },- {- "category_id": 1,- "poly": [- 133.58103942871094,- 963.8072509765625,- 836.1664428710938,- 963.8072509765625,- 836.1664428710938,- 1126.9761962890625,- 133.58103942871094,- 1126.9761962890625- ],- "score": 0.9999858736991882- },- {- "category_id": 1,- "poly": [- 915.4673461914062,- 154.09107971191406,- 1566.4822998046875,- 154.09107971191406,- 1566.4822998046875,- 252.11843872070312,- 915.4673461914062,- 252.11843872070312- ],- "score": 0.9999622106552124- },- {- "category_id": 1,- "poly": [- 133.48443603515625,- 297.8970642089844,- 837.02978515625,- 297.8970642089844,- 837.02978515625,- 563.48193359375,- 133.48443603515625,- 563.48193359375- ],- "score": 0.9999534487724304- },- {- "category_id": 1,- "poly": [- 134.178466796875,- 1129.2037353515625,- 835.380615234375,- 1129.2037353515625,- 835.380615234375,- 1326.577392578125,- 134.178466796875,- 1326.577392578125- ],- "score": 0.9999504089355469- },- {- "category_id": 1,- "poly": [- 863.1788940429688,- 1947.821044921875,- 1567.12744140625,- 1947.821044921875,- 1567.12744140625,- 2081.134765625,- 863.1788940429688,- 2081.134765625- ],- "score": 0.9999489188194275- },- {- "category_id": 1,- "poly": [- 133.19537353515625,- 565.38818359375,- 837.0946044921875,- 565.38818359375,- 837.0946044921875,- 795.4552612304688,- 133.19537353515625,- 795.4552612304688- ],- "score": 0.9999396800994873- },- {- "category_id": 1,- "poly": [- 889.4902954101562,- 632.3302001953125,- 1567.4151611328125,- 632.3302001953125,- 1567.4151611328125,- 760.7906494140625,- 889.4902954101562,- 760.7906494140625- ],- "score": 0.9999313354492188- },- {- "category_id": 1,- "poly": [- 864.2963256835938,- 559.0233764648438,- 1565.3338623046875,- 559.0233764648438,- 1565.3338623046875,- 623.64453125,- 864.2963256835938,- 623.64453125- ],- "score": 0.9999247789382935- },- {- "category_id": 0,- "poly": [- 956.4207763671875,- 800.2708740234375,- 1473.8553466796875,- 800.2708740234375,- 1473.8553466796875,- 832.0525512695312,- 956.4207763671875,- 832.0525512695312- ],- "score": 0.9999191164970398- },- {- "category_id": 1,- "poly": [- 890.3426513671875,- 254.0496368408203,- 1567.084228515625,- 254.0496368408203,- 1567.084228515625,- 550.75048828125,- 890.3426513671875,- 550.75048828125- ],- "score": 0.9999065399169922- },- {- "category_id": 0,- "poly": [- 863.724365234375,- 1905.3587646484375,- 1263.0279541015625,- 1905.3587646484375,- 1263.0279541015625,- 1937.046875,- 863.724365234375,- 1937.046875- ],- "score": 0.9998754262924194- },- {- "category_id": 0,- "poly": [- 865.344970703125,- 990.8092651367188,- 1077.787353515625,- 990.8092651367188,- 1077.787353515625,- 1020.8342895507812,- 865.344970703125,- 1020.8342895507812- ],- "score": 0.9998668432235718- },- {- "category_id": 0,- "poly": [- 132.80747985839844,- 1371.076171875,- 476.3838195800781,- 1371.076171875,- 476.3838195800781,- 1401.41552734375,- 132.80747985839844,- 1401.41552734375- ],- "score": 0.9998248815536499- },- {- "category_id": 1,- "poly": [- 158.07598876953125,- 1580.614013671875,- 837.52490234375,- 1580.614013671875,- 837.52490234375,- 2084.036376953125,- 158.07598876953125,- 2084.036376953125- ],- "score": 0.999720573425293- },- {- "category_id": 1,- "poly": [- 864.1918334960938,- 846.3515625,- 1565.4425048828125,- 846.3515625,- 1565.4425048828125,- 941.529541015625,- 864.1918334960938,- 941.529541015625- ],- "score": 0.999374270439148- },- {- "category_id": 1,- "poly": [- 187.75222778320312,- 155.8234405517578,- 763.4747314453125,- 155.8234405517578,- 763.4747314453125,- 187.12890625,- 187.75222778320312,- 187.12890625- ],- "score": 0.9937731623649597- },- {- "category_id": 2,- "poly": [- 1551.6641845703125,- 70.21305084228516,- 1566.66748046875,- 70.21305084228516,- 1566.66748046875,- 90.993408203125,- 1551.6641845703125,- 90.993408203125- ],- "score": 0.9599642753601074- },- {- "category_id": 0,- "poly": [- 187.70907592773438,- 219.8146209716797,- 785.0242309570312,- 219.8146209716797,- 785.0242309570312,- 285.96136474609375,- 187.70907592773438,- 285.96136474609375- ],- "score": 0.5746440887451172- },- {- "category_id": 8,- "poly": [- 187.70443725585938,- 219.90408325195312,- 785.4927978515625,- 219.90408325195312,- 785.4927978515625,- 286.03607177734375,- 187.70443725585938,- 286.03607177734375- ],- "score": 0.5241892337799072- },- {- "category_id": 13,- "poly": [- 1381,- 1430,- 1428,- 1430,- 1428,- 1459,- 1381,- 1459- ],- "score": 0.53,- "latex": "5\\,\\mathrm{m}"- },- {- "category_id": 13,- "poly": [- 864,- 1662,- 910,- 1662,- 910,- 1691,- 864,- 1691- ],- "score": 0.5,- "latex": "2\\,\\mathrm{m}"- },- {- "category_id": 13,- "poly": [- 1193,- 1530,- 1239,- 1530,- 1239,- 1558,- 1193,- 1558- ],- "score": 0.47,- "latex": "_{\\textrm{1m}}"- },- {- "category_id": 13,- "poly": [- 864,- 1729,- 909,- 1729,- 909,- 1758,- 864,- 1758- ],- "score": 0.44,- "latex": "_{\\textrm{1m}}"- }- ],- "page_info": {- "page_no": 2,- "height": 2200,- "width": 1700- }- },- {- "layout_dets": [- {- "category_id": 4,- "poly": [- 864.2838745117188,- 1281.72265625,- 1566.531982421875,- 1281.72265625,- 1566.531982421875,- 1359.263427734375,- 864.2838745117188,- 1359.263427734375- ],- "score": 0.9999990463256836- },- {- "category_id": 1,- "poly": [- 133.01622009277344,- 837.9033813476562,- 835.7518310546875,- 837.9033813476562,- 835.7518310546875,- 1203.0052490234375,- 133.01622009277344,- 1203.0052490234375- ],- "score": 0.9999970197677612- },- {- "category_id": 1,- "poly": [- 863.889892578125,- 1781.8822021484375,- 1566.0186767578125,- 1781.8822021484375,- 1566.0186767578125,- 2081.87939453125,- 863.889892578125,- 2081.87939453125- ],- "score": 0.9999960660934448- },- {- "category_id": 1,- "poly": [- 864.3985595703125,- 1409.9678955078125,- 1565.9906005859375,- 1409.9678955078125,- 1565.9906005859375,- 1710.3426513671875,- 864.3985595703125,- 1710.3426513671875- ],- "score": 0.9999954700469971- },- {- "category_id": 1,- "poly": [- 133.8789825439453,- 1205.3355712890625,- 835.18359375,- 1205.3355712890625,- 835.18359375,- 1634.283935546875,- 133.8789825439453,- 1634.283935546875- ],- "score": 0.9999930262565613- },- {- "category_id": 0,- "poly": [- 135.4618377685547,- 1839.9617919921875,- 331.53729248046875,- 1839.9617919921875,- 331.53729248046875,- 1871.8616943359375,- 135.4618377685547,- 1871.8616943359375- ],- "score": 0.9999902248382568- },- {- "category_id": 4,- "poly": [- 132.88088989257812,- 679.1465454101562,- 838.4302978515625,- 679.1465454101562,- 838.4302978515625,- 785.7191772460938,- 132.88088989257812,- 785.7191772460938- ],- "score": 0.9999885559082031- },- {- "category_id": 3,- "poly": [- 193.83837890625,- 182.79244995117188,- 759.5771484375,- 182.79244995117188,- 759.5771484375,- 653.6824340820312,- 193.83837890625,- 653.6824340820312- ],- "score": 0.9999850988388062- },- {- "category_id": 1,- "poly": [- 134.48211669921875,- 1636.1163330078125,- 834.7794189453125,- 1636.1163330078125,- 834.7794189453125,- 1800.814208984375,- 134.48211669921875,- 1800.814208984375- ],- "score": 0.9999649524688721- },- {- "category_id": 1,- "poly": [- 134.12872314453125,- 1881.7559814453125,- 834.7655029296875,- 1881.7559814453125,- 834.7655029296875,- 1982.255615234375,- 134.12872314453125,- 1982.255615234375- ],- "score": 0.9999020099639893- },- {- "category_id": 0,- "poly": [- 976.8430786132812,- 1740.978515625,- 1452.464111328125,- 1740.978515625,- 1452.464111328125,- 1771.867919921875,- 976.8430786132812,- 1771.867919921875- ],- "score": 0.9998255968093872- },- {- "category_id": 3,- "poly": [- 898.9835815429688,- 175.76722717285156,- 1495.93212890625,- 175.76722717285156,- 1495.93212890625,- 1266.6322021484375,- 898.9835815429688,- 1266.6322021484375- ],- "score": 0.9998016357421875- },- {- "category_id": 1,- "poly": [- 133.10968017578125,- 1982.9735107421875,- 834.5057983398438,- 1982.9735107421875,- 834.5057983398438,- 2080.69677734375,- 133.10968017578125,- 2080.69677734375- ],- "score": 0.9996336698532104- },- {- "category_id": 2,- "poly": [- 1553.209716796875,- 71.55194854736328,- 1565.424560546875,- 71.55194854736328,- 1565.424560546875,- 89.57391357421875,- 1553.209716796875,- 89.57391357421875- ],- "score": 0.9797953367233276- },- {- "category_id": 13,- "poly": [- 1306,- 1282,- 1353,- 1282,- 1353,- 1306,- 1306,- 1306- ],- "score": 0.87,- "latex": "2\\!\\times\\!1"- },- {- "category_id": 13,- "poly": [- 307,- 731,- 367,- 731,- 367,- 755,- 307,- 755- ],- "score": 0.72,- "latex": "\\mathrm{110\\,m}"- },- {- "category_id": 13,- "poly": [- 581,- 731,- 653,- 731,- 653,- 756,- 581,- 756- ],- "score": 0.63,- "latex": "28\\,\\mathrm{GHz}"- },- {- "category_id": 13,- "poly": [- 296,- 1436,- 352,- 1436,- 352,- 1468,- 296,- 1468- ],- "score": 0.34,- "latex": "\\mathbf{gN}\\mathbf{B}"- },- {- "category_id": 13,- "poly": [- 463,- 1668,- 520,- 1668,- 520,- 1700,- 463,- 1700- ],- "score": 0.26,- "latex": "\\mathbf{gN}\\mathbf{B}"- }- ],- "page_info": {- "page_no": 3,- "height": 2200,- "width": 1700- }- },- {- "layout_dets": [- {- "category_id": 1,- "poly": [- 134.3433837890625,- 942.0186157226562,- 834.1826171875,- 942.0186157226562,- 834.1826171875,- 1272.496337890625,- 134.3433837890625,- 1272.496337890625- ],- "score": 0.9999979734420776- },- {- "category_id": 1,- "poly": [- 134.33851623535156,- 1813.447265625,- 834.64990234375,- 1813.447265625,- 834.64990234375,- 2080.197021484375,- 134.33851623535156,- 2080.197021484375- ],- "score": 0.9999959468841553- },- {- "category_id": 1,- "poly": [- 864.8323364257812,- 987.3436889648438,- 1566.8726806640625,- 987.3436889648438,- 1566.8726806640625,- 1783.5870361328125,- 864.8323364257812,- 1783.5870361328125- ],- "score": 0.9999951720237732- },- {- "category_id": 1,- "poly": [- 134.39962768554688,- 1277.7550048828125,- 834.7018432617188,- 1277.7550048828125,- 834.7018432617188,- 1809.951171875,- 134.39962768554688,- 1809.951171875- ],- "score": 0.999994158744812- },- {- "category_id": 3,- "poly": [- 366.1568908691406,- 150.17318725585938,- 1329.7593994140625,- 150.17318725585938,- 1329.7593994140625,- 792.8095092773438,- 366.1568908691406,- 792.8095092773438- ],- "score": 0.9999933242797852- },- {- "category_id": 0,- "poly": [- 866.7418823242188,- 1836.01318359375,- 1017.6839599609375,- 1836.01318359375,- 1017.6839599609375,- 1865.512451171875,- 866.7418823242188,- 1865.512451171875- ],- "score": 0.9999814033508301- },- {- "category_id": 1,- "poly": [- 864.4174194335938,- 1882.203125,- 1564.8563232421875,- 1882.203125,- 1564.8563232421875,- 2079.260498046875,- 864.4174194335938,- 2079.260498046875- ],- "score": 0.9999741315841675- },- {- "category_id": 4,- "poly": [- 134.15469360351562,- 815.9164428710938,- 1562.02392578125,- 815.9164428710938,- 1562.02392578125,- 867.7661743164062,- 134.15469360351562,- 867.7661743164062- ],- "score": 0.9999508857727051- },- {- "category_id": 0,- "poly": [- 865.704833984375,- 942.009033203125,- 1059.95556640625,- 942.009033203125,- 1059.95556640625,- 970.8005981445312,- 865.704833984375,- 970.8005981445312- ],- "score": 0.9999415874481201- },- {- "category_id": 2,- "poly": [- 1552.128173828125,- 71.25533294677734,- 1566.6485595703125,- 71.25533294677734,- 1566.6485595703125,- 89.53498840332031,- 1552.128173828125,- 89.53498840332031- ],- "score": 0.9974276423454285- },- {- "category_id": 13,- "poly": [- 1388,- 1517,- 1445,- 1517,- 1445,- 1550,- 1388,- 1550- ],- "score": 0.3,- "latex": "\\tt g N B"- }- ],- "page_info": {- "page_no": 4,- "height": 2200,- "width": 1700- }- },- {- "layout_dets": [- {- "category_id": 1,- "poly": [- 863.9874877929688,- 1815.5633544921875,- 1566.741455078125,- 1815.5633544921875,- 1566.741455078125,- 2079.217041015625,- 863.9874877929688,- 2079.217041015625- ],- "score": 0.9999942779541016- },- {- "category_id": 1,- "poly": [- 865.5879516601562,- 1316.8531494140625,- 1566.5723876953125,- 1316.8531494140625,- 1566.5723876953125,- 1813.6834716796875,- 865.5879516601562,- 1813.6834716796875- ],- "score": 0.9999927282333374- },- {- "category_id": 1,- "poly": [- 134.6375732421875,- 952.2572021484375,- 834.2245483398438,- 952.2572021484375,- 834.2245483398438,- 1315.1661376953125,- 134.6375732421875,- 1315.1661376953125- ],- "score": 0.9999904036521912- },- {- "category_id": 1,- "poly": [- 134.9095458984375,- 1400.1383056640625,- 834.28173828125,- 1400.1383056640625,- 834.28173828125,- 1697.2962646484375,- 134.9095458984375,- 1697.2962646484375- ],- "score": 0.9999892115592957- },- {- "category_id": 1,- "poly": [- 865.7293090820312,- 155.0264434814453,- 1565.5443115234375,- 155.0264434814453,- 1565.5443115234375,- 383.32318115234375,- 865.7293090820312,- 383.32318115234375- ],- "score": 0.9999874830245972- },- {- "category_id": 1,- "poly": [- 865.7639770507812,- 477.6691589355469,- 1566.436279296875,- 477.6691589355469,- 1566.436279296875,- 1006.602294921875,- 865.7639770507812,- 1006.602294921875- ],- "score": 0.9999862909317017- },- {- "category_id": 1,- "poly": [- 133.97454833984375,- 1782.52880859375,- 835.3529052734375,- 1782.52880859375,- 835.3529052734375,- 2079.283447265625,- 133.97454833984375,- 2079.283447265625- ],- "score": 0.9999849200248718- },- {- "category_id": 1,- "poly": [- 865.3876342773438,- 1127.646728515625,- 1564.5369873046875,- 1127.646728515625,- 1564.5369873046875,- 1225.0914306640625,- 865.3876342773438,- 1225.0914306640625- ],- "score": 0.9999810457229614- },- {- "category_id": 1,- "poly": [- 133.3822021484375,- 338.7093505859375,- 834.5867919921875,- 338.7093505859375,- 834.5867919921875,- 868.1721801757812,- 133.3822021484375,- 868.1721801757812- ],- "score": 0.9999763369560242- },- {- "category_id": 1,- "poly": [- 134.7703857421875,- 156.58360290527344,- 834.59228515625,- 156.58360290527344,- 834.59228515625,- 250.93218994140625,- 134.7703857421875,- 250.93218994140625- ],- "score": 0.9999515414237976- },- {- "category_id": 0,- "poly": [- 134.81646728515625,- 296.1169128417969,- 301.2171936035156,- 296.1169128417969,- 301.2171936035156,- 327.50225830078125,- 134.81646728515625,- 327.50225830078125- ],- "score": 0.9999410510063171- },- {- "category_id": 0,- "poly": [- 865.8960571289062,- 433.5700988769531,- 1040.275634765625,- 433.5700988769531,- 1040.275634765625,- 463.8289489746094,- 865.8960571289062,- 463.8289489746094- ],- "score": 0.9998129606246948- },- {- "category_id": 0,- "poly": [- 865.2048950195312,- 1275.2528076171875,- 1319.10205078125,- 1275.2528076171875,- 1319.10205078125,- 1305.5203857421875,- 865.2048950195312,- 1305.5203857421875- ],- "score": 0.9997825622558594- },- {- "category_id": 0,- "poly": [- 135.78082275390625,- 1740.425048828125,- 598.881591796875,- 1740.425048828125,- 598.881591796875,- 1770.975830078125,- 135.78082275390625,- 1770.975830078125- ],- "score": 0.9997348189353943- },- {- "category_id": 0,- "poly": [- 135.5992889404297,- 911.2128295898438,- 440.9443054199219,- 911.2128295898438,- 440.9443054199219,- 940.1547241210938,- 135.5992889404297,- 940.1547241210938- ],- "score": 0.9996732473373413- },- {- "category_id": 0,- "poly": [- 135.51629638671875,- 1360.5496826171875,- 630.7794189453125,- 1360.5496826171875,- 630.7794189453125,- 1390.0040283203125,- 135.51629638671875,- 1390.0040283203125- ],- "score": 0.9994310140609741- },- {- "category_id": 2,- "poly": [- 1551.8868408203125,- 71.72320556640625,- 1565.9241943359375,- 71.72320556640625,- 1565.9241943359375,- 91.15934753417969,- 1551.8868408203125,- 91.15934753417969- ],- "score": 0.9937852621078491- },- {- "category_id": 0,- "poly": [- 878.8119506835938,- 1049.76806640625,- 1547.8568115234375,- 1049.76806640625,- 1547.8568115234375,- 1112.1201171875,- 878.8119506835938,- 1112.1201171875- ],- "score": 0.9739665389060974- }- ],- "page_info": {- "page_no": 5,- "height": 2200,- "width": 1700- }- },- {- "layout_dets": [- {- "category_id": 1,- "poly": [- 865.1703491210938,- 1749.82861328125,- 1565.8792724609375,- 1749.82861328125,- 1565.8792724609375,- 2080.968017578125,- 865.1703491210938,- 2080.968017578125- ],- "score": 0.9999978542327881- },- {- "category_id": 1,- "poly": [- 863.9318237304688,- 866.5559692382812,- 1567.1939697265625,- 866.5559692382812,- 1567.1939697265625,- 1663.54638671875,- 863.9318237304688,- 1663.54638671875- ],- "score": 0.999996542930603- },- {- "category_id": 1,- "poly": [- 134.32009887695312,- 1563.3734130859375,- 834.4869995117188,- 1563.3734130859375,- 834.4869995117188,- 1926.479248046875,- 134.32009887695312,- 1926.479248046875- ],- "score": 0.9999960660934448- },- {- "category_id": 3,- "poly": [- 374.6717529296875,- 151.7071990966797,- 1326.4266357421875,- 151.7071990966797,- 1326.4266357421875,- 711.5238037109375,- 374.6717529296875,- 711.5238037109375- ],- "score": 0.9999955892562866- },- {- "category_id": 1,- "poly": [- 133.2987060546875,- 911.025634765625,- 834.7653198242188,- 911.025634765625,- 834.7653198242188,- 1473.9681396484375,- 133.2987060546875,- 1473.9681396484375- ],- "score": 0.9999939203262329- },- {- "category_id": 1,- "poly": [- 135.3870086669922,- 2014.2613525390625,- 834.2026977539062,- 2014.2613525390625,- 834.2026977539062,- 2078.903076171875,- 135.3870086669922,- 2078.903076171875- ],- "score": 0.9999884963035583- },- {- "category_id": 0,- "poly": [- 136.2907257080078,- 1521.8297119140625,- 513.5540161132812,- 1521.8297119140625,- 513.5540161132812,- 1552.1356201171875,- 136.2907257080078,- 1552.1356201171875- ],- "score": 0.9999793767929077- },- {- "category_id": 0,- "poly": [- 134.11581420898438,- 1972.88916015625,- 664.4715576171875,- 1972.88916015625,- 664.4715576171875,- 2003.9886474609375,- 134.11581420898438,- 2003.9886474609375- ],- "score": 0.9999605417251587- },- {- "category_id": 4,- "poly": [- 133.239990234375,- 738.7720336914062,- 1567.0321044921875,- 738.7720336914062,- 1567.0321044921875,- 789.1837768554688,- 133.239990234375,- 789.1837768554688- ],- "score": 0.9999586939811707- },- {- "category_id": 0,- "poly": [- 866.1632690429688,- 1708.7288818359375,- 1406.107421875,- 1708.7288818359375,- 1406.107421875,- 1738.577880859375,- 866.1632690429688,- 1738.577880859375- ],- "score": 0.9998884201049805- },- {- "category_id": 0,- "poly": [- 134.7357940673828,- 871.1494140625,- 652.3981323242188,- 871.1494140625,- 652.3981323242188,- 898.2235717773438,- 134.7357940673828,- 898.2235717773438- ],- "score": 0.9853350520133972- },- {- "category_id": 2,- "poly": [- 1553.031494140625,- 70.53016662597656,- 1566.2633056640625,- 70.53016662597656,- 1566.2633056640625,- 89.09037780761719,- 1553.031494140625,- 89.09037780761719- ],- "score": 0.9816321730613708- },- {- "category_id": 13,- "poly": [- 595,- 1727,- 652,- 1727,- 652,- 1760,- 595,- 1760- ],- "score": 0.42,- "latex": "\\mathbf{gN}\\mathbf{B}"- }- ],- "page_info": {- "page_no": 6,- "height": 2200,- "width": 1700- }- },- {- "layout_dets": [- {- "category_id": 3,- "poly": [- 869.9388427734375,- 588.944091796875,- 1061.8564453125,- 588.944091796875,- 1061.8564453125,- 838.3399047851562,- 869.9388427734375,- 838.3399047851562- ],- "score": 0.9999961853027344- },- {- "category_id": 1,- "poly": [- 864.8761596679688,- 156.0197296142578,- 1571.390380859375,- 156.0197296142578,- 1571.390380859375,- 484.4344787597656,- 864.8761596679688,- 484.4344787597656- ],- "score": 0.9999923706054688- },- {- "category_id": 1,- "poly": [- 135.25286865234375,- 1097.9901123046875,- 839.7271728515625,- 1097.9901123046875,- 839.7271728515625,- 2085.473388671875,- 135.25286865234375,- 2085.473388671875- ],- "score": 0.9999918937683105- },- {- "category_id": 1,- "poly": [- 1088.017578125,- 580.5264892578125,- 1568.900634765625,- 580.5264892578125,- 1568.900634765625,- 858.09619140625,- 1088.017578125,- 858.09619140625- ],- "score": 0.9999913573265076- },- {- "category_id": 1,- "poly": [- 1089.640869140625,- 947.9395141601562,- 1567.883056640625,- 947.9395141601562,- 1567.883056640625,- 1198.422607421875,- 1089.640869140625,- 1198.422607421875- ],- "score": 0.9999912977218628- },- {- "category_id": 1,- "poly": [- 131.48910522460938,- 153.96853637695312,- 838.3993530273438,- 153.96853637695312,- 838.3993530273438,- 453.02337646484375,- 131.48910522460938,- 453.02337646484375- ],- "score": 0.9999911189079285- },- {- "category_id": 1,- "poly": [- 131.714111328125,- 541.0372924804688,- 838.0123901367188,- 541.0372924804688,- 838.0123901367188,- 1005.5633544921875,- 131.714111328125,- 1005.5633544921875- ],- "score": 0.9999898672103882- },- {- "category_id": 3,- "poly": [- 863.97900390625,- 1719.6123046875,- 1068.673095703125,- 1719.6123046875,- 1068.673095703125,- 1953.03173828125,- 863.97900390625,- 1953.03173828125- ],- "score": 0.9999892115592957- },- {- "category_id": 0,- "poly": [- 378.59942626953125,- 496.0562744140625,- 593.4119873046875,- 496.0562744140625,- 593.4119873046875,- 527.6988525390625,- 378.59942626953125,- 527.6988525390625- ],- "score": 0.9999885559082031- },- {- "category_id": 0,- "poly": [- 405.65191650390625,- 1052.885498046875,- 564.7144775390625,- 1052.885498046875,- 564.7144775390625,- 1081.0938720703125,- 405.65191650390625,- 1081.0938720703125- ],- "score": 0.9999884366989136- },- {- "category_id": 3,- "poly": [- 863.9266967773438,- 1333.662353515625,- 1069.4085693359375,- 1333.662353515625,- 1069.4085693359375,- 1553.8045654296875,- 863.9266967773438,- 1553.8045654296875- ],- "score": 0.9999866485595703- },- {- "category_id": 1,- "poly": [- 1089.958740234375,- 1313.381591796875,- 1569.0367431640625,- 1313.381591796875,- 1569.0367431640625,- 1591.7625732421875,- 1089.958740234375,- 1591.7625732421875- ],- "score": 0.9999823570251465- },- {- "category_id": 3,- "poly": [- 863.3223876953125,- 990.8128051757812,- 1069.0321044921875,- 990.8128051757812,- 1069.0321044921875,- 1166.51708984375,- 863.3223876953125,- 1166.51708984375- ],- "score": 0.9999755620956421- },- {- "category_id": 1,- "poly": [- 1087.6712646484375,- 1704.9793701171875,- 1568.7255859375,- 1704.9793701171875,- 1568.7255859375,- 1983.8875732421875,- 1087.6712646484375,- 1983.8875732421875- ],- "score": 0.9999744296073914- },- {- "category_id": 2,- "poly": [- 1548.5992431640625,- 68.92752075195312,- 1568.561279296875,- 68.92752075195312,- 1568.561279296875,- 91.09439086914062,- 1548.5992431640625,- 91.09439086914062- ],- "score": 0.9984710216522217- },- {- "category_id": 2,- "poly": [- 862.5369262695312,- 1981.4864501953125,- 1158.696533203125,- 1981.4864501953125,- 1158.696533203125,- 2009.3497314453125,- 862.5369262695312,- 2009.3497314453125- ],- "score": 0.9784647822380066- },- {- "category_id": 4,- "poly": [- 865.48876953125,- 1590.6600341796875,- 975.1014404296875,- 1590.6600341796875,- 975.1014404296875,- 1613.881103515625,- 865.48876953125,- 1613.881103515625- ],- "score": 0.6813311576843262- },- {- "category_id": 1,- "poly": [- 865.5831298828125,- 1590.6781005859375,- 974.7860107421875,- 1590.6781005859375,- 974.7860107421875,- 1613.807861328125,- 865.5831298828125,- 1613.807861328125- ],- "score": 0.45190906524658203- },- {- "category_id": 13,- "poly": [- 1270,- 1706,- 1336,- 1706,- 1336,- 1732,- 1270,- 1732- ],- "score": 0.28,- "latex": "[\\mathbf{M}^{\\prime}00]"- }- ],- "page_info": {- "page_no": 7,- "height": 2200,- "width": 1700- }- },- {- "layout_dets": [- {- "category_id": 3,- "poly": [- 128.92079162597656,- 1207.0789794921875,- 339.8792419433594,- 1207.0789794921875,- 339.8792419433594,- 1404.8714599609375,- 128.92079162597656,- 1404.8714599609375- ],- "score": 0.9999963641166687- },- {- "category_id": 3,- "poly": [- 150.6888427734375,- 161.63258361816406,- 321.2713928222656,- 161.63258361816406,- 321.2713928222656,- 416.30303955078125,- 150.6888427734375,- 416.30303955078125- ],- "score": 0.9999936819076538- },- {- "category_id": 1,- "poly": [- 359.1070251464844,- 1166.5550537109375,- 838.76220703125,- 1166.5550537109375,- 838.76220703125,- 1445.023681640625,- 359.1070251464844,- 1445.023681640625- ],- "score": 0.9999911785125732- },- {- "category_id": 1,- "poly": [- 360.03173828125,- 159.8954315185547,- 837.4935913085938,- 159.8954315185547,- 837.4935913085938,- 434.51287841796875,- 360.03173828125,- 434.51287841796875- ],- "score": 0.999970555305481- },- {- "category_id": 2,- "poly": [- 1551.287841796875,- 69.9497299194336,- 1566.8572998046875,- 69.9497299194336,- 1566.8572998046875,- 90.27826690673828,- 1551.287841796875,- 90.27826690673828- ],- "score": 0.9870278835296631- },- {- "category_id": 13,- "poly": [- 539,- 1168,- 598,- 1168,- 598,- 1194,- 539,- 1194- ],- "score": 0.81,- "latex": "[\\mathrm{F}^{\\prime}09]"- }- ],- "page_info": {- "page_no": 8,- "height": 2200,- "width": 1700- }- }-]\ No newline at end of filediff --git a/tests/test_cli/pdf_dev/annotations/cleaned/cleaned_academic_literature_0b2c9c91f5232541a7ace8984df306b2.md b/tests/test_cli/pdf_dev/annotations/cleaned/cleaned_academic_literature_0b2c9c91f5232541a7ace8984df306b2.mddeleted file mode 100644index d5486b3d..00000000--- a/tests/test_cli/pdf_dev/annotations/cleaned/cleaned_academic_literature_0b2c9c91f5232541a7ace8984df306b2.md+++ /dev/null@@ -1,367 +0,0 @@-# Characterization of severely deformed new composites fabricated by powder metallurgy including a stage of mechanical alloying--H. Ashuri, A. Hassani*<br>Faculty of Materials Science and Engineering, Semnan University, Semnan 35131-19111, Iran--## ARTICLE INFO--## Article history:--Received 11 February 2014--Received in revised form 11 June 2014--Accepted 4 August 2014--Available online 12 August 2014--## Keywords:--Nanocomposite--Mechanical alloying--Twist extrusion--Powder metallurgy---#### Abstract-- Mechanical properties of new composites having a binary matrix of $\mathrm{Al}-4 \mathrm{Cu}$ reinforced with $\mathrm{TiO}_{2}$ nano particles were investigated. The composites which consisted of $2 \mathrm{wt} \%$ and $8 \mathrm{wt} \%$ of $\mathrm{TiO}_{2}$ reinforcement particles, were fabricated using mechanical alloying and a powder metallurgy route. Morphology, phases and compounds formed during ball milling and densification of samples were studied. With increasing percentages of the reinforcement particles, mechanical properties of the composites were enhanced. Microstructural evolution and mechanical properties changes of the composites after application of twist extrusion (TE), as a severe plastic deformation (SPD) process, were also investigated. It was revealed that the more TE passes the higher hardness and yield strength obtained. In addition, increasing TE passes, led to occurrence of a more homogeneous distribution of the reinforcement particles within the structure, and development of an ultrafine-grained nano-structure. The maximum allowable number of TE passes was found to be four, above which the materials failed.----## 1. Introduction--In recent decades, aluminum matrix composites (AMC) with discontinuous reinforcements have vastly been attracted by different industries due to their good mechanical properties. Large number of manufacture routes have been developed to produce these materials among which powder metallurgy (PM) routes have been more considered with several causes. First, in powder metallurgy a controlled phase microstructure can be achieved. On the other hand, lower temperatures used in PM processes make the interphase kinetics be precisely controlled. In PM routes, the powders of elements and alloys are used which might be more inexpensive, and of course, much more effective in reinforcement of the composites. Traditional stages of PM-AMCs fabrication include mixing and blending the powders; degassing the solidified product in vacuum; homogenizing through hot pressing or hot isostatic pressing (HIP) [1].--AMCs are widely used in automotive, aerospace and transport industries because of their light weight, high elastic modulus, improved strength and good wear resistance. Strength and wear resistance of these materials are strongly dependent on volume fraction, size and type of reinforcement particles. They are well established that compared to their un-reinforced matrix alloys show higher wear resistance. AMCs with ceramic particles including $\mathrm{SiC}, \mathrm{TiC}, \mathrm{C}_{4} \mathrm{~B}, \mathrm{TiB}_{2}$ and $\mathrm{Al}_{2} \mathrm{O}_{3}$ are relatively easy to process and, in comparison with fiber-reinforced composites, are nearly isotropic [2].--Particulate AMCs have introduced most wide spread applications and hold the greatest promise for future growth because of their tailored properties, low cost-effectiveness and high volume production methods [3]. Aluminum matrix composites are known to be hard materials exhibiting a low forming capacity through the conventional techniques. Nevertheless, many promising attempts have been made to produce Al composites with a high potential of being formed plastically and even superplastically while their strength is retained [4].--Mechanical alloying (MA) is an interesting powder metallurgy route for producing of powders with high homogeneity and uniformity. This technique is very effective in dispersion of reinforcement particles and enhances grain refinement, which induces an increase of strength and hardness [5].--In recent years, manifestation of severe plastic deformation (SPD) methods in material science has shed light on new prospects in achieving a unique combination of high strength and ductility [6] as well as attaining ultrafine-grained materials with improved properties. SPD is a family of metal forming techniques that use extensive hydrostatic pressure to impose a very high strain on bulk solids, producing exceptional grain refinement without introducing any significant change in the overall dimensions of the sample[7]. Several different SPD techniques are now available; these include high-pressure torsion (HPT) [8], equal channel angular pressing (ECAP) [9], multi-directional forging (MDF) [10], accumulative roll-bonding (ARB) [11], repetitive corrugation and strengthening (RCS) [12], spread extrusion (SE) [13], simple shear extrusion (SSE) [14] and twist extrusion (TE) [15,16]. The SPD products have much higher structural efficiency in comparison with their coarsegrained counterparts. However, high cost-effectiveness of most SPD methods is a central drawback to produce such materials in high quantities. Therefore, development of new SPD methods to tackle cost problem is important.--In 1999, Beygelzimer proposed a severe plastic deformation process that became known as Twist Extrusion (TE) [17]. This process can change the structure of materials, significantly improving some of their physical and mechanical properties and, even in certain cases, gaining new properties. TE works by extruding a prism specimen through a matrix whose profile consists of two prismlike regions separated by a twist passage. The extruded material undergoes an intense shift, with the properties that the final cross-section of the specimen is identical to the initial cross-section [18]. These properties allow for a repeated extrusion that accumulates the value of deformation. TE is carried out under high hydrostatic pressure in the center of deformation which is created by applying anti-pressure (back pressure) to the specimen when it exits the matrix. It is possible to produce more isotropic and homogeneous deformation by turning the samples $90^{\circ}$ in each consecutive deformation or alternatively, make the use of consecutive clockwise-anticlockwise-clockwise twists [19]. A comparison between TE and the two most widely used SPD methods, ECAE and HPT, reveals that firstly, TE provides some advantages over ECAE such as the ability to extrude the hollow parts and the rectangular cross-sections [6]. Secondly, HPT involves order of magnitude higher pressures than in any other SPD process which provides attainment of uniquely high strains and formation of ultrafine grained structures. From another point of view, twist extrusion that combines extrusion with torsion, was introduced to tackle the insufficiency of HPT, that is, its being limited to laboratory conditions due to small size of the samples [19]. There are currently three main application areas of TE: (a) obtaining ultrafine grained crystalline and nano-crystalline structures in bulk specimens, (b) increasing the plasticity of secondary non-ferrous metals and alloys, which allows one to significantly broaden the range of production, (c) obtaining bulk specimens by consolidating porous materials which allows one to create substantially different, new compositions with unique characteristics [20].--In TE, strain distribution along the cross-section of the specimen is inhomogeneous; getting away from the axe, plastic strain increases, thus, the grains being finer. The microstructural inhomogeneity leads to inhomogeneities in the mechanical properties of the composite; the central area of the cross section having lowest strength. It is expected that with increasing the number of TE cycles, the microstructure becomes uniform [21].--In the present study, a powder metallurgy route combined with mechanical alloying was employed to produce some particulate $\mathrm{Al}-\mathrm{Cu} / \mathrm{TiO}_{2}$ composites with low $\mathrm{TiO}_{2}$ contents. The products were then severely deformed by twist extrusion technique. The microstructures, densities, wear resistances, hardness and strengths of the resulted composites, in two different $\mathrm{TiO}_{2}$ reinforcement content of 2 and $8 \mathrm{wt} \%$ and at various TE cycles were examined.--## 2. Experimental procedures--To attain a uniform distribution of the $\mathrm{TiO}_{2}$ reinforcement particles in $\mathrm{Al}-\mathrm{Cu}$ matrix, a high-energy planetary ball-mill machine, manufactured by the authors was utilized and, the powder behavior was studied during the process. Milling time and the effects of volume fraction of the reinforcement and its particle size were also investigated. Aluminum powder with mean grain size of $<45 \mu \mathrm{m}$ and commercial purity of $99.9 \%$ and copper powder of $40 \mu \mathrm{m}$ with $99.0 \%$ purity were supplied. Nano-scale anatase $\mathrm{TiO}_{2}$ powder, as the reinforcement, having a mean size of $50 \mathrm{~nm}$ was also obtained. The powders specifications are shown in Table 1.--The appropriate proportions of $\mathrm{Al}$ and $\mathrm{Cu}$ powders were weighed using a digital balance of $0.001 \mathrm{mg}$ accuracy. Internal surfaces of the cups were wetted with a thin layer of glycerin to prevent sticking the powders mixtures on them. The powders were then mixed and blended in a high energy planetary ball mill to produce the matrix alloy powder. For ball-milling, chromium steel balls with diameters of 17 , $19,22,25$ and $30 \mathrm{~mm}$, ball-to-powder weight ratio of $20: 1$, constant rotational speed of $300 \mathrm{rpm}$ and argon atmosphere were used. Ball milling time was $16 \mathrm{~h}$. To reinforce the product, $2 \mathrm{wt} \%$ and $8 \mathrm{wt} \%$ of $\mathrm{TiO}_{2}$ particles were added and blended to a homogeneous mixture. The mixture was cold compacted into a two-piece die of DIN-1.2344 hot die steel having a hole of $15 \times 15 \times 80 \mathrm{~mm}$ dimensions for $15 \mathrm{~min}$ under $600 \mathrm{MPa}$. Then, to enhance apparent densities of powders, they were put into the die under $100 \mathrm{MPa}$ pressure being heated to temperatures of $550^{\circ} \mathrm{C}, 580^{\circ} \mathrm{C}$ and $640^{\circ} \mathrm{C}$. After reaching these temperatures, the pressure was turned up to $700 \mathrm{MPa}$ at which the samples were kept for 30,60 and $120 \mathrm{~min}$ to obtain three different densities. After sintering, the samples were furnace cooled and homogenized to room temperature at a rate of $21.8^{\circ} \mathrm{C} / \mathrm{h}$.--For twist extrusion testing, the samples were lubricated with $\mathrm{MoS}_{2}$ to reduce friction. Then, they were inserted into the entrance guide of the twist extrusion die being pushed to the distorted channel using a steel plunger with speed of $1.1 \mathrm{~mm} / \mathrm{s}$. The twist extrusion die of $14.6 \times 14.6 \mathrm{~mm}$ internal cross-section with a twist line slope of $\beta=60^{\circ}$ in the counter-clockwise direction was used (Fig. 1). In order to apply a backpressure on the sample, the output channel was built steeped. This channel, itself, acted as a direct extrusion die. Thus, after the specimen passes the twisted channel, enters a straight output passage of $29 \mathrm{~mm}$ length during which its cross-section changed from $14.6 \times 14.6 \mathrm{~mm}$ to $14.2 \times 14.2 \mathrm{~mm}$. In addition, for preventing deviation of the sample to the sides and making sure of upright entering of the sample into the twisted channel, an $80 \mathrm{~mm}$ channel with $15 \times 15 \mathrm{~mm}$ crosssection was developed at the entrance as the sample guide. Also, to inhibit stress concentration, the right angle corners of the die interior walls were blunted. In this research, two sets of $\mathrm{Al}-4 \mathrm{wt} \% \mathrm{Cu} / 2 \mathrm{wt} \% \mathrm{TiO}_{2}$ and $\mathrm{Al}-4 \mathrm{wt} \% \mathrm{Cu} / 8 \mathrm{wt} \% \mathrm{TiO}_{2}$ samples were extruded at velocity of $68.4 \mathrm{~mm} / \mathrm{min}$ (maximum velocity of the available press) for 1,2 and 4 passes. The maximum allowed number of TE passes was found to be four, above which material failure occurred during twist extrusion operation.--To investigate the microstructure changes in the materials due to twist extrusion, the samples were prepared by cutting from the cross-section perpendicular to the axial direction of the extruded billets. The microstructure evolution was then studied in the central, lateral and corner regions of the cross-section using scanning electron microscopy (SEM).--Densities of the compacted powders were determined through Archimedes procedure according to the standard ASTM B93-13 [22]. The microstructures of samples from both composites were studied using SEM model ISI ABT SR-50 equipped with EDX analyzer after their preparation including grinding, polishing and etching with Keller etchant solution. To investigate the formation of deleterious phases like $\mathrm{Al}_{7} \mathrm{Cu}_{2} \mathrm{Fe}$ and $\mathrm{Al}_{4} \mathrm{C}_{3}, \mathrm{X}$-ray diffraction examinations and scanning electron microscopy observations were carried out on the sintered composites. To evaluate grain size and lattice strain, spectroscope system equipped with copper ray lamp (wavelength $1.5405 \AA$ ) was utilized. Williamson-Hall equation was used to determine crystallite size and lattice strain in diffracting domain. For hardness measurements of the sintered samples, Vickers hardness testing machine with the applied force of $1000 \mathrm{~g}$ was utilized.--To evaluate wear resistance of the composite specimens, tribological studies were conducted according to ASTM G99-04 standard [23] using a WAZAU pin-ondisk wear testing machine connected to computer interface from Tribo V4.3L software. The samples were cut from the cross-section perpendicular to the extrusion direction. Hardness testing was performed on the points across cross-section diameter with $1 \mathrm{~mm}$ intervals from one corner to the other. The samples were cut by a Merck lathe from the upper part of the cylindrical samples to make disks of $50 \mathrm{~mm}$ diameter and $4 \mathrm{~mm}$ thickness. To polish the sample surfaces, they were ground against 100,200 , and 500 grit emery papers. As the wearing apparatus, pins of $5 \mathrm{~mm}$ length and $2 \mathrm{~mm}$ diameter from 2160 steel with 60 HRC were prepared. The applied force and sliding distance were selected to be $30 \mathrm{~N}$ and $1000 \mathrm{~m}$, respectively. Wear coefficient, K, was predicted using the Archard equation [24]:--$V=K W L / H$--where $V$ is the lost volume of the worn material, $H$ Brinell hardness, $W$ normal applied load equal to $30 \mathrm{~N}, L$ the sliding distance (m) and $K$ wear coefficient.--Table 1--Specifications of powders used in this study.--| Powder | Particle size | Purity (\%) |-| :--- | :--- | :--- |-| $\mathrm{Al}$ | $<45 \mu \mathrm{m}$ | 99.9 |-| $\mathrm{Cu}$ | $<40 \mu \mathrm{m}$ | 99 |-| $\mathrm{TiO}_{2}$ | $<50 \mathrm{~nm}$ | 99 |----Fig. 1. Twist channel of TE die with $\alpha=90^{\circ}$ and $\beta=60^{\circ}$.--To investigate mechanical properties of the composites and to plot true stresstrue strain relation, compression tests were carried out. The cylindrical compression samples were cut from the centre of the billets for 1,2 and 4 cycles with ratio of $H / D=1$, separately out of the samples containing 2 and $8 \mathrm{wt} \% \mathrm{TiO}_{2}$ and, then were prepared and polished. The tests were conducted at ambient temperature. True stress-true strain relation of samples in each pass were inferred from compressive stress-strain curves.--## 3. Results and discussion--### 3.1. Powders specifications--Firstly, to determine the adequate milling duration, aluminum powder and $4 \mathrm{wt} \% \mathrm{Cu}$ powder were mixed and ball-milled for 5, 6 and $8 \mathrm{~h}$. The XRD patterns are compared in Fig. 2a. As seen, with increasing the milling time, the XRD peak intensities for aluminum and copper phases decreased and the XRD peak intensity of $\mathrm{Al}_{2} \mathrm{Cu}$ phase increased, therefore, it is inferred that after $8 \mathrm{~h}$ milling, the phase $\mathrm{Al}_{2} \mathrm{Cu}$ was formed and alloying process was completed.Now, $2 \mathrm{wt} \% \mathrm{TiO}_{2}$ reinforcement powder was added to the mixture and milled for 4 more hours (two-stage alloying). Next, aluminum, copper and $\mathrm{TiO}_{2}$ powders were mixed together and were milled in two portions for 12 and $16 \mathrm{~h}$ (one-stage alloying). Compressive results are shown in Fig. 2b. In two-stage conditions, as observed in Table 2, the subgrain size is smaller, but formation of $\mathrm{Al}_{7} \mathrm{Cu}_{2} \mathrm{Fe}$ brittle phase occurred that might be due to gradual intrusion of $\mathrm{Fe}$ into the mixture during ball-milling through surface erosion of the balls and cups. On the other hand, the weak signs of the formation of that phase were observed in one-stage milling for $16 \mathrm{~h}$. Therefore, to minimize the possible formation of the deleterious brittle phase of $\mathrm{Al}_{7} \mathrm{Cu}_{2} \mathrm{Fe}$ in the final product, all samples were produced through one-stage, $16 \mathrm{~h}$ ball-milling. In Fig. 2c, the results of X-ray diffraction experiments for milling of $\mathrm{Al}-4 \mathrm{wt} \% \mathrm{Cu}$ powder mixture containing $8 \mathrm{wt} \% \mathrm{TiO}_{2}$ for $16 \mathrm{~h}$ are depicted. The results indicated the formation of $\mathrm{Al}_{2} \mathrm{Cu}$ phase which witnesses that the alloying was performed successfully. The deleterious brittle phase of $\mathrm{Al}_{7} \mathrm{Cu}_{2} \mathrm{Fe}$ was not observed in the final product.----Fig. 2. XRD results (a) for different milling times of Al-4Cu, (b) comparison of results for $12 \mathrm{~h} 2$-stage with $12 \mathrm{~h}$ and $16 \mathrm{~h} 1$-stage mechanical alloying and (c) for $16 \mathrm{~h}$ milling of powder mixture containing $8 \mathrm{wt} \% \mathrm{TiO}_{2}$.--Table 2--A comparison of subgrain size and grain strain in different milling times.--| Sample | Type of milling | Milling time $(\mathrm{h})$ | Subgrain size $(\mathrm{nm})$ | Grain strain |-| :--- | :--- | :--- | :--- | :--- |-| $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{TiO}_{2}$ | Two stage | 12 | 11 | 0.0017 |-| $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{TiO}_{2}$ | One stage | 12 | 33 | 0.0045 |-| $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{TiO}_{2}$ | One stage | 16 | 31.51 | 0.00475 |-| $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{TiO}_{2}$ | One stage | 16 | 28.41 | 0.00481 |--Table 3--Relative densities of samples at 700 Mpa pressure for $30 \mathrm{~min}$ at different temperatures.--| Sample | Theoretical density $\left(\mathrm{g} / \mathrm{cm}^{3}\right)$ | Bulk density $\left(\mathrm{g} / \mathrm{cm}^{3}\right)$ | Temperature $\left({ }^{\circ} \mathrm{C}\right)$ | Relative density $(\%)$ | Porosity percentage $(\%)$ |-| :--- | :--- | :---: | :--- | :--- | :--- |-| $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{TiO}_{2}$ | 2.797 | $2.256 \pm 0.0006$ | 550 | 90.31 | 9.69 |-| | | $2.7095 \pm 0.0004$ | 580 | 96.87 | 3.13 |-| $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{TiO}_{2}$ | 2.856 | $2.7452 \pm 0.003$ | 640 | 98.15 | 1.85 |-| | | $2.759 \pm 0.004$ | 640 | 98.64 | 1.36 |--### 3.2. Evaluation of composites--For hot compacting, the twist extruded samples having $2 \mathrm{wt} \% \mathrm{TiO}_{2}$, first, temperature of $550^{\circ} \mathrm{C}$ and, then $580{ }^{\circ} \mathrm{C}$ were applied. Densities of those samples were calculated using dipping-in-water procedure (Eqs. (2) and (3)) and, since their measured densities at above two temperatures were found to be very low ( $<97 \%)$, higher temperatures were applied. The applied pressure for all samples was fixed at $700 \mathrm{MPa}$ for $30 \mathrm{~min}$. Porosity volume fraction was also determined using Eq. (3); the results are presented in Table 3. For applying a uniform axial pressure, the ratio of height to diameter $(h / d)$ was about 1.5 .--$\rho=\frac{W_{\text {air }}\left\lfloor\rho_{\text {water }}-0.0012\right\rfloor}{0.99983\left\lfloor W_{\text {air }}-W_{\text {water }}\right\rfloor}+0.0012$--$\rho_{T}=\sum_{i=1}^{n} f_{i} \rho_{i}$--$\%$ Porosity $=\frac{\rho_{T}-\rho}{\rho_{T}} \times 100$--where $W_{\text {air }}$ is the measured weight of the sample in air, $W_{\text {water }}$ the weight in water, $\rho$ measured density, $\rho_{\text {water }}$ density in water, $\rho_{T}$ theoretical density.In hot compression test performed on composite, temperature of $640^{\circ} \mathrm{C}$ was applied for the other samples, but their holding time in the furnace increased to 60 and $120 \mathrm{~min}$. The final densities are tabulated in Table 4. In hot compression situations at $640{ }^{\circ} \mathrm{C}$ for $120 \mathrm{~min}$, the density of the sintered sample was nearly equal to the theoretical density of the composite. Therefore, the same conditions were repeated for the mixture powder containing $8 \mathrm{wt} \% \mathrm{TiO}_{2}$ reinforcement. Because the density of $\mathrm{TiO}_{2}$ particles was higher than that of the matrix alloy $\left(4.5 \mathrm{~g} / \mathrm{cm}^{3}\right)$, it was anticipated that with increasing volume fraction of reinforcement particles, the relative density of the composite increased [5] which was consistent with the results depicted in Table 4.----Fig. 4. SEM micrograph of sample $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{wt} \% \mathrm{TiO}_{2}$ showing large agglomerated $\mathrm{TiO}_{2}$ particles.--Table 4--Relative densities of samples at $700 \mathrm{MPa}$ pressure at $640^{\circ} \mathrm{C}$ and different times.--| Sample | Theoretical density $\left(\mathrm{g} / \mathrm{cm}^{3}\right)$ | Bulk density $\left(\mathrm{g} / \mathrm{cm}^{3}\right)$ | Time $(\mathrm{min})$ | Relative density $(\%)$ | Porosity percentage $(\%)$ |-| :--- | :--- | :--- | :--- | :--- | :--- |-| $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{TiO}_{2}$ | 2.797 | $2.252 \pm 0.0008$ | 30 | 98.15 | 1.85 |-| | | $2.757 \pm 0.0005$ | 60 | 98.59 | 1.41 |-| $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{TiO}_{2}$ | 2.856 | $2.769 \pm 0.0003$ | 120 | 99.01 | 0.99 |-| | | $2.833 \pm 0.0004$ | 120 | 99.20 | 0.80 |----Fig. 3. SEM images of samples reinforced with (a) 2 and (b) $8 \mathrm{wt} \% \mathrm{TiO}_{2}$ particles prior to $\mathrm{TE}$.----Fig. 5. (a and b) XRD patterns of composites reinforced with $2 \mathrm{wt} \% \mathrm{TiO}_{2}$ and $8 \mathrm{wt} \% \mathrm{TiO}_{2}$ nano-particles and (c and d) EDX analysis results for those composites, respectively.--Table 5--Weight percentage of elements in $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{wt} \% \mathrm{TiO}_{2}$ and $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{wt} \% \mathrm{TiO}_{2}$ derived from EDX analysis.--| Element | wt\% of element in $\mathrm{Al}-4 \mathrm{Cu} /$ <br> $2 \mathrm{wt} \% \mathrm{TiO}_{2}$ | wt\% of element in $\mathrm{Al}-4 \mathrm{Cu} /$ <br> $8 \mathrm{wt} \% \mathrm{TiO}_{2}$ |-| :---: | :---: | :---: |-| $\mathrm{Al}$ | 84.1 | 77.14 |-| $\mathrm{Cu}$ | 3.88 | 3.68 |-| $\mathrm{Ti}$ | 2.08 | 7.86 |-| 0 | 9.94 | 11.32 |-| Total | 100 | 100 |--Fig. 3 shows SEM micrographs of the samples containing $2 \mathrm{wt} \% \mathrm{TiO}_{2}$ and $8 \mathrm{wt} \% \mathrm{TiO}_{2}$ prior to TE with coarse distinct grains. As seen, the reinforcement particles are distributed uniformly within the matrix. The particles became finer with smooth edges and corners during ball-milling. Uniform distribution of nanoparticles within matrix, because of their high surface to volume ratio, is difficult. In the composites with $8 \mathrm{wt} \% \mathrm{TiO}_{2}$, distribution of these nano-particles was inhomogeneous resulting in formation of their large agglomerates; these usually impair mechanical properties of materials. This is more evident in Fig. 4.----Fig. 6. (a) $\mathrm{SE}$ images of composite reinforced with $2 \mathrm{wt} \% \mathrm{TiO}_{2}$ and $\mathrm{EDX}$ analysis of point $\mathrm{A}$ and $\mathrm{B}$, (b) $\mathrm{SE}$ micrograph of composite reinforced with 8 wt $\% \mathrm{TiO}_{2}$ with $\mathrm{EDX}$ analysis of points $A$ and $B$.----Fig. 7. Compression true stress-true strain curves for annealed samples until beginning of barreling.--According to XRD results shown in Fig. 5a, presence of the brittle phase (i.e. $\mathrm{Al}_{7} \mathrm{Cu}_{2} \mathrm{Fe}$ in the sintered $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{TiO}_{2}$ sample, which causes brittle fracture of the material, is confirmed. However, X-ray diffraction pattern in Fig. $5 \mathrm{~b}$ indicates that in the $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{TiO}_{2}$ sample, the brittle phase is absent. In the next stages of experiments, it will be noticed that with application of severe plastic strains, fracture of latter samples occurred more frequently in comparison with the former ones. For performing quantitative analysis of the existing elements in the samples, EDX was utilized. The results are depicted in Fig. 5(c) and (d) as well as in Table 5. Those results were obtained from surfaces of the samples showing the total weight percentage of the elements in the sintered samples. The analysis showed no contamination.--Fig. 6(a) shows secondary electron (SE) micrograph of a sample with composition of $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{TiO}_{2}$ together with $\mathrm{EDX}$ analyses of points A and B (specified with circles), which are nearly identical. Therefore, it is concluded that the reinforcing particles are uniformly distributed within the matrix, as mentioned earlier. However, EDX analyses of points A and B of SE micrograph of the sample $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{TiO}_{2}$ shown in Fig. 6 (b) are quite dissimilar. It means that a non-uniform distribution of $\mathrm{TiO}_{2}$ nano-particles coupled with their large agglomerates, which usually contribute to deterioration of mechanical properties of the composite, occurred.--Compression true stress-true strain curves of the annealed samples, in the case of $\mathrm{Al}-4 \mathrm{Cu}, \mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{wt} \% \mathrm{TiO}_{2}$ and $\mathrm{Al}-4 \mathrm{Cu} /$ $8 \mathrm{wt} \% \mathrm{TiO}_{2}$ are illustrated and compared in Fig. 7 and the results are shown in Table 6. It is evident that with increasing $\mathrm{TiO}_{2}$ content in the composite, yield stress and Young modulus increase but, ductility decreases. Perhaps, deletion of porosities during hot compression at $640^{\circ} \mathrm{C}$ for $120 \mathrm{~min}$ was effective in enhancement of the sample strength. On the other hand, $\mathrm{TiO}_{2}$ particles are stable thermodynamically, and do not react with the matrix phase at high temperatures. These particles act as barriers against movement of dislocations leading to ductility decrease [25].--Fig. 8 shows variation of lost volume of composites during wear test vs. sliding distance. As previously shown, with increasing the percentage of $\mathrm{TiO}_{2}$ reinforcement, the lost volume decreases. To predict wear coefficient, Eq. (1) was used. The graph in Fig. 9 shows variation of wear coefficient with sliding distance for all samples. As indicated, the lowest wear coefficient belongs to the composite having $8 \mathrm{wt} \% \mathrm{TiO}_{2}$. It is also evident in Table 7 that with increasing weight percentage of $\mathrm{TiO}_{2}$ particles, the hardness of the material increases. Such a hardness increasing can be attributed to the increasing of dislocation densities improving material resistance. Hardness increasing leads to enhancement of wear resistance of the composite [25].----Fig. 8. Variation of lost volume of matrix alloy and composite vs. sliding distance in wear test.----Fig. 9. Variation of wear coefficient for matrix alloy and composites vs. sliding distance at pressure of $30 \mathrm{~N}$.--Table 7--Mean Brinell hardness for different samples.--| Specimen | Hardness (Brinell) |-| :--- | :--- |-| $\mathrm{Al}-4 \mathrm{Cu}$ | 107 |-| $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{TiO}_{2}$ | 138 |-| $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{TiO}_{2}$ | 200 |--Fig. 10 are the backscattered electron BSE images of samples $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{wt} \% \mathrm{TiO}_{2}$ and $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{wt} \% \mathrm{TiO}_{2}$ from central and lateral regions. EDX examinations revealed that the two discrete dark and light regions corresponding to $\mathrm{TiO}_{2}$ clusters and the matrix, respectively. Fig. 10(a), (b), (e) and (f) shows the microstructure of two composites in central area after two passes and four passes of twist extrusion, respectively. It is revealed that grains became finer and the microstructure was more uniform with increasing the number of TE passes and this is same for Fig. 10(c), (d), (g) and (h) that illustrate the microstructure of lateral region of cross-section of both composites after two passes and four passes of TE, respectively. After four passes of TE in both composites, formation of nano-sized grains are evident. Unlike significant effect of billet axial rotations between ECAP passes [26,27], the billet rotations between TE passes have no effect on the plastic flow. This is due to the axial symmetry of the process.--Table 6--Results of uniaxial compression testing for annealed samples.--| Specimen | Young modulus (GPa) | Yield strength (GPa) | Barreling stress (MPa) | Barreling strain (\%) |-| :--- | :--- | :--- | :--- | :--- |-| $\mathrm{Al}-4 \mathrm{Cu}$ | 66 | 256 | 270 | 0.96 |-| $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{TiO}_{2}$ | 70 | 246 | 0.93 | 284|-| $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{TiO}_{2}$ | 79.6 | 278 | 284 | 0.87 |----Fig. 10. BSC images of composites, up: $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{wt} \% \mathrm{TiO}_{2}$ and down: $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{wt} \% \mathrm{TiO}_{2}$, (a, b, e and f) central regions, after 2 and 4 passes, (c, d, $\mathrm{g}$ and $\mathrm{h}$ ) lateral regions, after 2 and 4 passes.----Fig. 11. Grain size measurement for a corner of cross-section of a sample containing $8 \mathrm{wt} \% \mathrm{TiO}_{2}$ extruded for 2 passes.--Clustering of fine particles has been reported by Ritasalo et al. [28]. With increasing twist extrusion passes, $\mathrm{TiO}_{2}$ clusters became smaller having a more homogeneous distribution in the matrix. For the sample $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{wt} \% \mathrm{TiO}_{2}$, as observed, with increasing the number of TE passes, very fine equiaxed grains are formed. It is also evident that in the centre of the sample, the microstructure is less homogeneous and the formation of $\mathrm{TiO}_{2}$ clusters is observed. As indicated, in both types of samples, the microstructures in the corners and edges of the cross-section are more homogenous than those in the centers. This means that the corners experienced larger strains compared to the centre. In each pass of TE process, applying plastic deformation leads to an increase in dislocation density and, consequently formation of subgrains that impede dislocations glide gradually. With accumulation of plastic strains in subsequent passes, misorientation between neighboring grains increases and elongated grains turn to fine equiaxed ones resulting in a recrystallized microstructure [29]. This is the same phenomenon normally observed in SPD processes and is termed dynamic recrystallization [30].--Mishra et al. [29] suggested that when grains become smaller and also when the total area of grain boundaries increases, discrete dislocations emitted by a boundary are absorbed by the opposite grain boundary. Therefore, in higher passes of TE, dislocation density decreases gradually and high angle grain boundaries form. Shape of grains and rate of converting low angle boundaries to high angle ones in TE process depend on twist path and twist angle $(\alpha)$. It is worth noting that strain distribution and the boundary of deformation zones depend strongly on the geometry of die crosssection, i.e. deviation angle $(\beta)$ and twist angle $(\alpha)$, and by varying these factors, one can change strain intensity in different regions.--Grain sizes of the extruded samples were determined after each TE pass using a scaling-measuring utility installed to scanning electron microscope, as shown in Fig. 11 and the results are depicted in Table 8. It is inferred from Table 8 that with increasing TE passes, grain size in the centre and in the corners decreases. However, with increase of passes, the amount of strain that can be imposed on the sample, decreases. Such a decrease is further observed at edge regions. Therefore, uniformity of deformed structure increases and gradually, extent of grain refinement increases in central and lateral regions of the sample. This is due to structure stability brought about by saturation of the mechanical properties after the strain exceeds saturation limit. Such stability and saturation are not confined to TE, but are extended to all deformations based on pure shear like ECAP and so on. Mechanisms of this effect in PSD processes are such that with increasing passes (i.e. with increasing the strains), grain boundary surfaces also increase with a rate proportional to deformation state. During plastic deformation, cells or subgrains form and after a rather large strain, a considerable change does not occur in them. Therefore, with increasing strain, amount of high angle boundaries increases [29]. It is then concluded that with increasing the number of passes, the difference in grain sizes decreases in various regions of the sample. To determine extent of this difference in various passes, a variable index $(V)$ is defined as a ratio of standard deviation, SD to a parameter average value $\bar{x}$ as follows [31]:--$V=\frac{S D}{\bar{x}} \times 100$--Table 8--Mean grain size $(\mu \mathrm{m})$ of centers and corners of cross sections of two composites at various passes of TE.--| Sample | Position | Annealed | 1-pass | 2-pass | 4-pass |-| :--- | :--- | :--- | :--- | :--- | :--- |-| $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{wt} \% \mathrm{TiO}_{2}$ | Corner | $20.9 \mu \mathrm{m}$ | $11 \mu \mathrm{m}$ | $9 \mu \mathrm{m}$ | $7.1 \mu \mathrm{m}$ |-| | Center | $21.7 \mu \mathrm{m}$ | $20 \mu \mathrm{m}$ | $12 \mu \mathrm{m}$ | $8.4 \mu \mathrm{m}$ |-| $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{wt} \% \mathrm{TiO}_{2}$ | Corner | $18.2 \mu \mathrm{m}$ | $10 \mu \mathrm{m}$ | $7.8 \mu \mathrm{m}$ | $5.6 \mu \mathrm{m}$ |-| | Center | $18.8 \mu \mathrm{m}$ | $14 \mu \mathrm{m}$ | $9.8 \mu \mathrm{m}$ | $6.5 \mu \mathrm{m}$ |----Fig. 12. Grain size heterogeneity index for different passes for two composites.--Fig. 12 shows inhomogeneity of grain size for different passes and various $\mathrm{TiO}_{2}$ contents in composites. As indicated, the annealed sample is more homogeneous in grain size and, the sample extruded for one pass shows highest inhomogeneity. It is evident that with increasing the number of passes, the inhomogeneity of grain size decreases to a minimum of $V=\sim 16 \%$ for fourpass TE operation.--Fig. 13(a) shows the effect of $\mathrm{TiO}_{2}$ content on Vickers microhardness of the composites. A more uniform dispersion of $\mathrm{TiO}_{2}$ particle in the matrix impedes dislocation movements resulting in an increase of the hardness [32]. Fig. 13(b) and (c) shows the variation of hardness in the centre and corners of cross-section as well as mean hardness, in different passes of TE, for both types of composites. As seen, during first pass, the hardness increases dramatically, but in next passes, an obvious decrease in the curve slope is observed. This has been attributed to increase in dislocation density resulted from application of severe plastic deformation [29].Since corners get higher plastic strains than the centre, they possess higher hardness. However, with increasing the number of passes and gradual saturation of microstructure with strain due to saturation in dislocation density and, then development of a fine substructure, the heterogeneity in hardness distribution on the cross-section of the sample decreases. Therefore, despite occurrence of heterogeneity in deformation, hardness distribution is homogeneous at higher strains. Zendehdel et al. also reported homogeneity of hardness distribution at higher passes when they investigated influence of $\mathrm{TE}$ process on microstructure and mechanical properties of 6063 aluminum alloy [33]. Fig. 14(a) and (b) illustrates Vickers microhardness measured along diagonal line on cross-section of different samples. As indicated, hardness of samples increased noticeably after first pass compared to the annealed specimens. For the samples containing $2 \mathrm{wt} \% \mathrm{TiO}_{2}$, the hardness increased by $52 \%$ in average, but for the sample having $8 \mathrm{wt} \% \mathrm{TiO}_{2}$, the hardness increasing was $46 \%$. The hardness increase is lower for the central regions that undergoes lower strain levels and, higher for the lateral areas deformed by higher strains; this is due to higher redundant strains $\left(\varepsilon_{\mathrm{r}}\right)$ at the lateral regions [34]. The variation index, $V$, is also defined for description of heterogeneity level in hardness values. Using the variation index, $V$, calculated through Eq. (5) for different passes, Table 9 for the sample $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{wt} \% \mathrm{TiO}_{2}$ and Table 10 for the sample $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{wt} \% \mathrm{TiO}_{2}$ are tabulated. Fig. 15 shows the heterogeneity index of hardness values $(V)$ for different passes of TE. It is inferred from Tables 9 and 10, and Fig. 15 that, in addition to increase in hardness within the central and lateral areas, and also increasing average hardness in whole sample, heterogeneity increased as well. Hardness heterogeneity index value in the sample of $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{TiO}_{2}$ extruded for 4 passes reached to 8.44 from 1.37 for the conditions before TE and, also in the sample of $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{TiO}_{2}$ extruded for 4 passes, $V$ value reached to 12.45 from 1.42 for the conditions before TE. It seems that heterogeneous distribution of hardness within whole sample was not significant due to application of backpressure during the process. Because backpressure is necessary for completion of cinematic conditions of applied plastic flow through tool geometry of $\mathrm{TE}$, and facilitates development of more homogeneous structure and mechanical properties [30].----Fig. 13. (a) Variation of Vickers hardness of composites with different $\mathrm{TiO}_{2}$ contents, prior to TE. (b) Variation of hardness at central and lateral regions of cross-section and mean hardness at different $\mathrm{TE}$ passes for composite $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{wt} \% \mathrm{TiO}_{2}$. (c) Variation of hardness at central and lateral regions of cross-section and mean hardness at different TE passes for composite $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{wt} \% \mathrm{TiO}_{2}$.----Fig. 14. Vickers hardness measured along diagonal line over cross section of (a) sample $\mathrm{Al}-4 \mathrm{Cu} 8 \mathrm{wt} \% \mathrm{TiO}_{2}$ at various passes of $\mathrm{TE}$.----Fig. 15. Heterogeneity index of hardness values for various TE passes.--Table 9--Vickers microhardness values for samples $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{wt} \% \mathrm{TiO}_{2}$ at different passes and their heterogeneity values.--| Sample | Hardness in center (HV) | Mean hardness (HV) | Hardness of edge (HV) | Heterogeneity V (\%) |-| :--- | :--- | :--- | :--- | :--- |-| Annealed | 145 | 146 | 147 | 1.3 |-| 1-pass | 217 | 224 | 231 | 6.25 |-| 2-pass | 225 | 234 | 243 | 7.69 |-| 4-pass | 227 | 237 | 247 | 8.44 |--Table 10--Vickers microhardness values for samples $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{wt} \% \mathrm{TiO}_{2}$ at different passes and their heterogeneity values.--| Sample | Hardness in center (HV) | Mean hardness (HV) | Hardness of edge (HV) | Heterogeneity V (\%) |-| :--- | :--- | :--- | :--- | ---: |-| Annealed | 210 | 211.5 | 213 | 1.42 |-| 1-pass | 296 | 308.5 | 321 | 8.10 |-| 2-pass | 318 | 335.5 | 353 | 10.43 |-| 4-pass | 324 | 345.5 | 367 | 12.45 |----Fig. 16. Results of compression tests: (a) true stress-true strain curves for $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{wt} \% \mathrm{TiO}_{2}$, (b) true stress-true strain curves for $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{wt} \% \mathrm{TiO} \mathrm{O}_{2}$. (c) Variation of yield strength at different passes for both composites.--Table 11--Results of uniaxial compression testing on samples $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{wt} \% \mathrm{TiO}_{2}$ and $\mathrm{Al}-4 \mathrm{Cu} / 8 \mathrm{wt} \% \mathrm{TiO}_{2}$ (Type 1 and Type 2, respectively) at different passes.--<table><thead><tr><th rowspan="2">Sample</th><th colspan="2">Young modulus (GPa)</th><th colspan="2"> Yield strength (MPa)</th><th colspan="2">Barreling strain MPa</th><th colspan="2"> Barreling strain (%)</th></tr><tr><th>Type 1</th><th>Type 2</th><th>Type 1</th><th>Type 2</th><th>Type 1</th><th>Type 2</th><th>Type 1</th><th>Type 2</th></tr></thead><tr><td>Annealed</td><td>70</td><td>79.6</td><td>246</td><td>278</td><td>284</td><td>298</td><td> 0.93</td><td> 0.87</td></tr><tr><td>1-pass</td><td>84</td><td> 94.9</td><td> 304</td><td> 325</td><td>241</td><td>347</td><td>0.80</td><td>0.74</td></tr><tr><td>2-pass</td><td>85</td><td>96.6</td><td>334</td><td>354</td><td>358</td><td>366</td><td>0.66</td><td>0.62</td></tr><tr><td>4-pass</td><td>87.6</td><td>97.2</td><td>368</td><td>372</td><td>383</td><td>391</td><td>0.65</td><td>0.61</td></tr></table>--Fig. 16(a) and (b) shows graphs obtained from compression tests including true stres-true strain curves derived from uniaxial compression test on samples $\mathrm{Al}-4 \mathrm{Cu} / 2 \mathrm{wt} \% \mathrm{TiO}_{2}$ and $\mathrm{Al}-4 \mathrm{Cu} /$ $8 \mathrm{wt} \% \mathrm{TiO}_{2}$ after different TE passes, respectively. The obtained results are compared in Table 11. Fig. 16(c) illustrates variation curves of yield strength for both composites in different TE passes. As indicated, with increasing number of passes, strength increased and ductility decreased. The strength increase extent in the first pass is obviously higher than that in the second and fourth passes which is due to gradual strain saturation in different regions, particularly those closer to the centre. By applying a few number of TE passes, strain exceeds saturation limit and saturation state gradually extends all cross-section area leading to uniformity in changing microstructure and other properties [35].--## 4. Conclusions--Mechanical alloying and powder metallurgy routes were applied to fabricate a new composite with binary matrix of Al$4 \mathrm{Cu}$ and reinforced by $2 \mathrm{wt} \% \mathrm{TiO}_{2}$ nano-particles. The annealed materials were subjected to some of the mechanical tests, and hardness, strength and yield strength were measured. With increasing percentages of the reinforcement particles, hardness, yield strength, Young modulus and wear resistance of the composites increased but ductility decreased. Afterwards, the composites were deformed severely through twist extrusion for 1,2 and 4 passes. The maximum allowable passes of extrusion was four, beyond which the materials did not endure plastic deformation and failed. It was revealed that with increasing the number of passes by 4 , a more homogeneous distribution of reinforcement particles occurred and also an ultrafine-grained nano-structure was obtained.--## References--[1] B. Ogel, R. Gurbuz, Microstructural characterization and tensile properties of hot pressed Al-SiC composites prepared from pure Al and Cu powders, Mater. Sci. Eng. A 301 (2001) 213-220.--[2] J. Onoro, M.D. Salvador, L.E.G. Cambronero, High-temperature mechanica properties of aluminium alloys reinforced with boron carbide particles, Mater. Sci. Eng. A 499 (2009) 421-426.--[3] R. Khorshidi, A. Hassani, Comparative analysis between TOPSIS and PSI methods of materials selection to achieve a desirable combination of strength and workability in Al/SiC composite, Mater. Des. 52 (2013) 999-1010.-[4] A. Hassani, M. Zabihi, High strain rate superplasticity in a nano-structured Al$\mathrm{Mg} / \mathrm{SiCP}$ composite severely deformed by equal channel angular extrusion, J. Mater. Des. 39 (2012) 140-150--[5] H. Kaftelena, M.L. Ovecoglua, H. Heneinb, H. Cimenoglua, $\mathrm{ZrC}$ particle reinforced $\mathrm{Al}-4 \mathrm{wt} \% \mathrm{Cu}$ alloy composites fabricated by mechanical alloying and vacuum hot pressing: microstructural evaluation and mechanical properties, Mater. Sci. Eng. A 527 (2010) 5930-5938,--[6] S.A.A. Akbari Mousavi, A.R. Shahab, M. Mastoori, Computational study of Ti$6 \mathrm{Al}-4 \mathrm{~V}$ flow behaviors during the twist extrusion process, Mater. Des. 29 (2008) 1316-1329.--[7] R.Z. Valiev, Y. Estrin, Z. Horita, T.G. Langdon, M.J. Zehetbauer, Y.T. Zhu, Producing bulk ultrafine-grained materials by severe plastic deformation, JOM 58 (4) (2006) 33-39.--[8] N.A. Smirnova, V.I. Levit, V.I. Pilyugin, R.I. Kuznetsov, L.S. Davydova, V.A. Sazonova, Evolution of structure of fcc single crystals during strong plastic deformation, Phys. Met. Metallogr. 61 (6) (1989) 127-134.--[9] M.V. Segal, V.I. Reznikov, A.E. Drobyshevskiy, V.I. Kopylov, Plastic metal working by simple shear, Izvestia Akademii nauk SSSR. Metally 1 (1981) 115123.--[10] G.A. Salishchev, O.R. Valiakhmetov, R.M. Galeyev, Formation of submicrocrystalline structure in the titanium alloy VT8 and its influence on mechanical properties, J. Mater. Sci. 28 (1993) 2898-2903.--[11] Y. Saito, H. Utsunomiya, N. Tsuji, T. Sakai, Novel ultra-high straining process for bulk materials development of the accumulative roll-bonding (ARB) process, Acta Mater. 47 (2) (1999) 579-583.--[12] J.Y. Huang, Y.T. Zhu, H.G. Jiang, T.C. Lowe, Microstructures and dislocation configurations in nanostructured Cu processed by repetitive corrugation and straightening, Acta Mater. 49 (9) (2001) 1497-1505.--[13] Y. Beygelzimer, V.N. Varyukhin, D.V. Orlov, S.G. Son, Twist extrusion - the accumulation of strain, Donetsk firma naukoemnih Technol. Natl. Acad. Sci. Ukraine (2003) 73-75.--[14] N. Pardis, R. Ebrahimi, Deformation behavior in simple shear extrusion (SSE) as a new severe plastic deformation technique, Mater. Sci. Eng. A 527 (1-2) (2009) 355-360.--[15] V. Varyukhin, Y. Beygelzimer, R. Kulagin, O. Prokofeva, A. Reshetov, Twist extrusion: fundamentals and applications, Mater. Sci. Forum 667-669 (2011) 31-37.--[16] Y. Beygelzimer, D. Orlov, V. Varyukhin, Proceedings of the Second International Symposium on Ultrafine Grained Materials, in: Y.T. Zhu (Ed.), Minerals, Metals, and Materials Society, Warren Dale (PA), 2002, pp. 297-301.--[17] Beygelzimer Y, Varukhin V, Synkov S, Sapronov A, Synkov V. New techniques for accumulating large plastic deformations using hydroextrusion, Fizika i Tekhnika Vusokih Davlenii (High Pressure Physics and Technology, in Russian) 1999; 9(3).--[18] Y. Beygelzimer, V. Varyukhin, D. Orlov, S. Sinkov, Twist extrusion: accumulating deformations 56 (2003) 456-465 (in Russian).--[19] Y. Beygelzimer, D. Prilepoa, R. Kulagina, V. Grishaeva, A. Abramovaa, V. Varyukhina, Planar twist extrusion vs. TWIST extrusion, J. Mater. Process Technol. 211 (2011) 522-529.--[20] V. Varukhin, Y. Beygelzimer, S. Synkov, D. Orlov, Applications of twist extrusion, Mater. Sci. Forum 503-504 (2006) 335-340.--[21] Y. Beygelzimer, V. Varyukhin, S. Synkov, D. Orlov, Useful properties of twist extrusion, Mater. Sci. Eng. A 503 (2009) 14-17.--[22] ASTM B962-13 Standard Test Methods for Density of Compacted or Sintered Powder Metallurgy (PM) Products Using Archimedes' Principle West Conshohocken, PA: ASTM International, 2004.--[23] G99-04 A. Standard test method for wear testing with a Pin-on-Disk apparatus. West Conshohocken, PA: ASTM International, 2004.--[24] J.F. Archard, Contact and rubbing of flat surfaces, J. Appl. Phys. 24 (1953) 981.--[25] C.S. Ramesha, A.R. Anwar Khanb, N. Ravikumar, P. Savanprabhu, Prediction of wear coefficient of $\mathrm{Al}_{6061}-\mathrm{TiO}_{2}$ composites Wear 259 (2005) 602-608.--[26] M. Furukawa, Y. Iwahashi, Z. Horita, M. Nemoto, T.G. Langdon, The shearing characteristics associated with equal-channel angular pressing, Mater. Sci. Eng. A 257 (2) (1998) 328-332.--[27] M.V. Segal, Slip line solutions, deformation mode and loading history during equal channel angular extrusion, Mater. Sci. Eng. A 271 (1-2) (1999) 322-333.--[28] R. Ritasalo, M.E. Cura, X.W. Liu, Y. Ge, T. Kosonen, U. Kanerva, O. Söderberg, S.P. Hannula, Microstructural and mechanical characteristics of $\mathrm{Cu}_{-1} \mathrm{Cu}_{2} \mathrm{O}$ composites compacted with pulsed electric current sintering and hot isostatic pressing, Composites: Part A 45 (2013) 61-69.--[29] A. Mishra, V. Richard, F. Gregori, R.J. Asaro, M.A. Meyers, Microstructural evolution in copper processed by severe plastic deformation, Mater. Sci. Eng. A 290 (2005) 410-411.--[30] D. Orlov, Y. Beygelzimer, S. Synkov, V. Varyukhin, N. Tsuji, Z. Horita, Plastic flow, structure and mechanical properties in pure Al deformed by twist extrusion, Mater. Sci. Eng. A 519 (2009) 105-111.--[31] Y. Beygelzimer, D. Orlov, A. Korshunov, S. Synkov, V. Varyukhin, I. Vedernikova, A. Reshetov, A. Synkov, L. Polyakov, I. Korotchenkova, Features of twist extrusion: method, structures and material properties, Solid State Phenomena 114 (2006) 69-78.--[32] G.S. Kataiah, D.P. Girish, The mechanical properties and fractography of aluminium $6061-\mathrm{TiO}_{2}$ composites, IJPSR I (2010) 17-25.--[33] H. Zendehdel, A. Hassani, Influence of twist extrusion process on microstructure and mechanical properties of 6063 aluminum alloy, Mater. Des. 37 (2012) 13-18.--[34] M.S. Mohebbi, A. Akbarzadeh, Experimental study and FEM analysis of redundant strains in flow forming of tubes, J. Mater. Process Technol. 210 (2010) 389-395--[35] Y. Beygelzimer, A. Reshetov, S. Synkov, O. Prokofeva, R. Kulagin, Kinematics of metal flow during twist extrusion investigated with a new experimental method, J. Mater. Proc. Technol. 209 (2009) 3650-3656.\ No newline at end of filediff --git a/tests/test_cli/pdf_dev/annotations/cleaned/cleaned_academic_literature_f7904bc37cc2e25c1e3e412978854b10.md b/tests/test_cli/pdf_dev/annotations/cleaned/cleaned_academic_literature_f7904bc37cc2e25c1e3e412978854b10.mddeleted file mode 100644index d8c0191e..00000000--- a/tests/test_cli/pdf_dev/annotations/cleaned/cleaned_academic_literature_f7904bc37cc2e25c1e3e412978854b10.md+++ /dev/null@@ -1,150 +0,0 @@-# Research Article--## The effects of AZD3582 [4-(nitroxy)butyl-(2S)-2-(6-methoxy-2naphthyl) propanoate], and naproxen on key pathogenic steps in NSAID-enteropathy in the rat.--M. Walley, G. Sigthorsson, C. Hotz-Behofsits, R. Simpson, I. Bjarnason*--Guy's, King's and St Thomas' School of Medicine, Department of Gastroenterology, King's College Hospital Foundation Trust, Denmark Hill,<br>London SE5 9PJ, London, UK, Tel: ++2032992417, Fax: ++2032996474, e-mail: ingvar.Bjarnason @kcl.ac.uk--Received 9 October 2006; revised 27 January 2007; accepted 1 February 2007---Abstract. Background: The pathogenesis of NSAID-induced enteropathy may involve dual inhibition of the cyclooxygenase (1 and 2 ) and a topical effect with sequential increased intestinal permeability, development of inflammation and ulcers. It has been suggested that nitric-oxide donating drugs cause significantly less gastrointestinal injury by counteracting for NSAID-induced reductions in blood flow.--Aims: To compare the effects of AZD3582 [4-(nitroxy)butyl(2S)-2-(6-methoxy-2-naphthyl) propanoate], and naproxen on key pathogenic steps in NSAID-enteropathy in the rat.--Methods: Single doses of AZD3582, naproxen (dose range $10-300 \mu \mathrm{mol} / \mathrm{kg}$ ) or vehicle were given to male Sprague Dawley rats. Intestinal permeability ( ${ }^{1} \mathrm{CrEDTA}$ ) and intestinal inflammation (granulocyte marker protein) was quantitated and ulcer counts made.--Results: Intestinal permeability (all doses) and inflammation (highest dose of the drugs) increased significantly from control levels following naproxen and AZD3582 and there was no significant difference between the drugs. Median ulcer counts were, however, significantly ( $\mathrm{p}<0.01$ ) lower with AZD3582 (4 $\pm 2$ ) than with naproxen $(17 \pm 4)$.--Conclusions: Naproxen and AZD3582 are equally associated with increased small intestinal permeability and inflammation, which is the consequence of their topical effect. The reduced small bowel ulcer counts with AZD3582 accords with the suggestion that vascular factors are the main driving force for NSAID-induced ulcer formation.--Key words: NSAIDs; CINODs; Nitric oxide; Naproxen; AZD3582[^0]--## Introduction--Nonsteroidal anti-inflammatory drugs (NSAIDs) cause gastrointestinal side effects which involve the stomach as well as the small bowel mucosa (Hawkey and Langman, 2003). Although the serious gastric side effects of bleeding and perforation have attracted the most attention, it is increasingly clear that the small bowel is associated with similar types and prevalence of complications (Bjarnason et al., 1993; Laine et al., 2002)--The pathogenesis of NSAID-induced gastrointestinal damage is uncertain. There is substantial evidence to suggest that NSAID-enteropathy in rodents is caused by various combinations of the selective biochemical effects of NSAIDs including cyclooxygenase (COX)-1 and COX-2 inhibition together with the topical effect (Somasundaram et al., 1995). The topical effect is thought to relate to the physicochemical properties of NSAIDs to act as detergents (Lichtenberger et al., 1995) and uncouplers of mitochondrial oxidative phosphorylation (Somasundaram et al., 1995). Collectively, it is suggested that the topical effect results in increased intestinal permeability with mucosal exposure of luminal aggressive factors and hence inflammation. It is also suggested that NSAID-induced inhibition of COX1, with decreased amounts of vasoactive prostaglandins, drives this inflammation to ulcers (Wallace et al., 2000). Interestingly small bowel damage occurs with long-term COX-2 absence or inhibition (small bowel inflammation and ulcers) although the mechanisms are unclear (Sigthorsson et al., 2002).--One of the more recent suggestions for reducing the intestinal side effects of NSAIDs is to attach a nitric oxide (NO) moiety to the NSAID, in the hope that the NO might counteract the effect of prostaglandin deficiency on the intestinal microcirculation. NO donors have been used in patients with cardiovascular disease for more than a century (Burgaud et al., 2002). NO is recognised as an important modulator of a large number of physiological processes (Wallace and Miller, 2000). More specifically, NO increases mucosal blood flow and mucus secretion and decreases leukocyte adherence (Cirino et al., 1996; Wallace and Miller, 2000). As these actions could, in theory, counteract the effects of mucosal prostaglandin deficiency induced by NSAIDs, a class of COX-inhibiting nitric oxide donors (CINODs) have been developed. CINODs are frequently produced by the addition of a nitroxybutyl moiety to the carboxylic group of the NSAID (which mediates the binding to the COX enzymes) by means of an ester linkage (Fiorucci, 2001). As well as potentially offering improved gastrointestinal tolerability, CINODs may result in enhanced anti-inflammatory, anti-pyretic and analgesic effects when compared to NSAIDs (Fiorucci et al., 2002) or COX-2 selective agents, although this is a controversial issue.--Previous animal studies have indicated that CINODs may offer reduced adverse gastrointestinal effects when compared to the parent compounds (Elliott et al., 1995; Davies et al., 1997). More recently, human studies have demonstrated that NO-aspirin (NCX-4016) maintains COX-1 and platelet inhibition whilst nearly avoiding the short-term gastric damage (Fiorucci, et al., 2003) and that AZD3582 [4-(nitroxy)butyl(2S)-2-(6-methoxy-2-naphthyl) propanoate] reduces gastrointestinal toxicity when compared to naproxen (Hawkey et al., 2003).--The precise reason that these CINODs reduce the gastrointestinal damage of the parent drug is controversial. Their ester linkage to the NSAID abolishes their topical effect and their effect on the COX enzymes. In order to maintain therapeutic efficacy the CINOD needs to undergo hydrolysis yielding the parent NSAID and the NO moiety. If the beneficial effects of CINODs are due to their counteracting or compensating for the vascular effects of prostaglandin deficiency it might be expected that CINODs would be equally associated with the permeability and inflammatory changes of the comparator NSAID (consequence of the topical effect) whilst reducing the number of ulcers. We tested this hypothesis by comparing the effects of AZD3582 with those of naproxen on small bowel permeability (using ${ }^{51} \mathrm{CrEDTA}$ ), intestinal inflammation (quantitated by measurement of granulocyte marker protein (GMP)) and small bowel ulcer counts in rats.--## Methods--## Animals--Male Sprague Dawley rats (Charles Rivers), 6-8 weeks old, weighing $200-250 \mathrm{~g}$ were used throughout these studies. Two groups of animals were used. The first group was used for the measurement of intestinal permeability and ulcer counts while the second group was used to assess intestinal inflammation via the measurement of granulocyte marker protein (GMP) in stool samples. Animals were housed singly in metabolism cages for up to 9 days and fed standard laboratory diet and water. For measurement of intestinal inflammation, stool samples were collected each day from day 2 to day 9 (with the drugs being administered on day 5). Following an overnight fast (day 4), animals received AZD3582 or naproxen diluted in solvent (oil in water emulsion) from $60 \mu \mathrm{mol} / \mathrm{ml}$ emulsions and given by gastric gavage at the doses of $10,30,100$ or $300 \mu \mathrm{mol} / \mathrm{kg}$ ( $\mathrm{n}=8$ in each group). Control animals received solvent only. Ulcer counts were performed 48 hours after administration of the drugs or vehicle. The naproxen and AZD3582 were obtained from AstraZeneca, R\&D Sodertalje, Sweden.--## Intestinal Permeability--One hour after administration of the study drugs or vehicle, the rats were administered $10 \mu \mathrm{Ci}{ }^{51} \mathrm{CrEDTA}$ via a tube in a volume of $0.5 \mathrm{ml}$ water followed by $1 \mathrm{ml}$ of water. Animals were allowed food and fluids 2 hours later. All urine passed during the following 5 hours was collected and the samples were assayed for gamma-radioactivity along with standards ( $10 \%$ of the dose given) in a Wallac 1284 gamma counter (Pharmacia, Sweden) for 1 minute. Results are expressed as percentage of the oral dose that was excreted in urine, which provides a measure of intestinal permeability as previously described (Somasundaram et al., 2000).--## Intestinal Inflammation--Stool samples were collected on each day of the study and $1 \mathrm{~g}$ wet weight of each were added to $4 \mathrm{ml}$ of extraction buffer (Tris $50 \mathrm{mM}$, $\mathrm{NaCl} 150 \mathrm{mM}, \mathrm{CaCl}_{2} 10 \mathrm{mM}$, Thiomersal $0.25 \mathrm{mM}, \mathrm{pH}$ to 8.4$)$. The samples were then homogenized for 30 seconds at $20,000 \mathrm{rpm}$ using an Ultra Turrax homogenizer (IKE Werke, Germany) and spun in a microcentrifuge for 10 minutes at $13,000 \mathrm{rpm}$. The supernatant was decanted off into an eppendorf tube and the samples were assayed for GMP as previously described (Sigthorsson et al., 2002). In short $50 \mu 1$ of a 1:200 dilution in duplicate to 96 well microtitre plates were added. The plates were pre-coated with anti-GMP antibody. Equal volumes of 9 standards were also added to the plates in duplicate. The plates were incubated at room temperature on a plate shaker for 45 minutes, washed 4 times with rinsing buffer (Tris $50 \mathrm{mM}, \mathrm{NaCl} 150 \mathrm{mM}, \mathrm{MgCl}_{2} 0.5 \mathrm{mM}, \mathrm{KCl}$ $2.5 \mathrm{mM}$, Thiomersal $0.25 \mathrm{mM}$, Tween- $200.05 \%, \mathrm{pH}$ to 8.0 ) allowed to dry and then $50 \mu \mathrm{l}$ of alkaline phosphatase (ALP) conjugated anti-GMP (diluted 1:800 in assay buffer) was added to each well. The plates were incubated under the same conditions as before, washed and dried as before and then $100 \mu \mathrm{l}$ of substrate (p-nitrophenyl phosphate, $1 \mathrm{mg} / \mathrm{ml}$, in substrate buffer ( $10 \%$ diethanolamine), $\mathrm{MgCl}_{2} 0.5 \mathrm{mM}$, Thiomersal $0.25 \mathrm{mM}, \mathrm{pH} 9.6$ ) was added to each well. The optical density of the highest standard was monitored and when it read between 1.2-1.8, the reaction was stopped by adding $50 \mu 11 \mathrm{M} \mathrm{NaOH}$ to each well. The plates were read at $405 \mathrm{~nm}$ using an MRX plate reader plus Dynex Revelation software (Dynex Technologies, USA). The results are expressed in $\mathrm{mg} / \mathrm{l}$ of extract.--## Macroscopic studies--To assess ulceration within the small bowel, animals were euthanazed by $\mathrm{CO}_{2}$ inhalation 48 hours after administration of the drugs. The abdomen was opened via a midline incision and the small intestine isolated, removed and gently flushed with $0.9 \%$ saline. The intestinal mucosa was exposed by cutting along the anti-mesenteric side of the intestine. Ulcer counts were performed by noting both the number and size of the ulcers ( $\leq 5 \mathrm{~mm}$ were recorded as pointed, $>5 \mathrm{~mm}$ were recorded as longitudinal).--## Statistical analysis--Results are presented as median and range as not all data was normally distributed. Wilcoxon's rank sum test was used to assess statistical differences between groups and the Wilcoxon's signed rank test for sequential data.--## Results--## Intestinal Permeability--Figure 1 shows that administration of both naproxen and AZD3582 significantly increased intestinal permeability at all doses given when compared with baseline (vehicle only) ( $p<0.001$ ). There was no significant difference ( $p>0.05$ ) in intestinal permeability between AZD3582 and naproxen at any of the doses given.--## Intestinal Inflammation--There was no significant increase in GMP with the 10 or $30 \mu \mathrm{mol} / \mathrm{kg}$ doses of either drug (Figure 2). Rats given AZD3582 at a dose of $100 \mu \mathrm{mol} / \mathrm{kg}$ had GMP values significantly higher than the control group ( $p<0.05$ ). At doses of $300 \mu \mathrm{mol} / \mathrm{kg}$, a significant increase in intestinal inflammation was noted with both naproxen and AZD3582 when compared to the vehicle group ( $\mathrm{p}<0.01$ ). No significant difference was observed between the two drugs at any of the dose range tested.--## Macroscopic examination--On macroscopic examination, no ulcers were seen with either drug over a dose range of $0-100 \mu \mathrm{mol} / \mathrm{kg}$. The mean number of ulcers with naproxen $300 \mu \mathrm{mol} / \mathrm{kg}$ ) was 17.1 (range 10 29). The rats treated with AZD3582 had significantly fewer ulcers ( $\mathrm{p}<0.001$ ) (median 2.5; range 0-12) (Figure 3).----Fig. 1 Urinary excretion of 51 CrEDTA after Naproxen and AZD3582. The white circles represent median (bars represent range) values obtained from rats dosed with naproxen. The black circles represent values obtained from rats dosed with AZD3582. Urinary excretion of $51 \mathrm{CrEDTA}$ was measured 5 hours following dosing.----Fig. 2 GMP concentrations after Naproxen and AZD3582. The white circles represent median (bars represent range) GMP values obtained from rats dosed with naproxen. The black circles represent the GMP values obtained from rats dosed with AZD3582. Data shown is taken from the day following dosing.----Fig. 3 Small bowel ulcer counts after Naproxen and AZD3582. The white circles represent the number of ulcers in rats dosed with naproxen. The black circles represent the number of ulcers in rats dosed with AZD3582. Counts were made 48 hours after dosing with $300 \mu \mathrm{mol} / \mathrm{kg}$.--## Discussion--These studies show that AZD3582 is associated with significantly less small bowel ulcerative damage than naproxen while the postulated consequences of the topical effect, intestinal permeability and inflammation, is equally evident with both drugs. The findings are consistent (assuming that the NO is released prior to or during drug absorption ren-dering intact naproxen) with the aforementioned pathogenic framework for NSAID-induced small bowel damage and the suggestion that the NO maintains vascular perfusion following the administration of naproxen.--A number of studies show that virtually all acidic NSAIDs increase small intestinal permeability, by virtue of their acidity and lipid solubility, and it is suggested that that this is a prerequisite for the development of small intestinal inflammation (Sigthorsson et al., 2000). Unlike non-selective NSAIDs, the NO moiety of AZD3582 renders the molecule non-acidic, and hence it can not exert a topical effect in this form. Nevertheless it is still associated with increased intestinal permeability in the current experiments suggesting hydrolyses of the ester bond, presumably by gastric and more importantly pancreatic esterases (Somasundaram et al., 1997). This raises the possibility that the beneficial action of AZD3582 on the stomach (Hawkey et al., 2003; WilderSmith et al., 2006) may simply be due to its lack of topical toxicity (Rainsford and Whitehouse, 1980).--While both drugs were associated with similar increases in intestinal permeability there were no inflammatory changes following the lower ( 10 or $30 \mu \mathrm{mol} / \mathrm{kg}$ ) doses of the drugs unlike previous studies where inflammation invariably follows the intestinal permeability changes (Somasundaram et al., 1997; Somasundaram et al., 2000). The reasons for this may be that much higher doses of NSAIDs were administered in previous studies. Indeed at the higher doses of 100 and $300 \mu \mathrm{mol} / \mathrm{kg}$, dose dependent inflammation was seen for naproxen and AZD3582, the inflammation being similar for both drugs. It is noteworthy that NO itself, despite its potentially beneficial effect on microvascular blood flow and healing, may be directly toxic to the epithelial cells at high concentrations (Menconi et al., 1998).--The results of studies on AZD3582 can not be extrapolated over to other NO-NSAIDs as their method of production, stability, pharmacokinetics and rate of hydrolyses may differ. A similar study to the current one (Davies et al., 1997) nevertheless found more contrasting degrees of inflammation with naproxen compared to the CINOD. This study used higher drug doses and a much stricter dosing regime (twice daily dosing for over 2 weeks compared to our single dose over 8 days). However, Somasundaram (1997) using nitroxybutyl-flurbiprtofen obtained almost identical results to the current study.--Previous studies have clearly dissociated the consequences of the topical effect (increased intestinal permeability and inflammation) from the COX-1 inhibitory effect, which seems to drive the inflamed mucosa to an ulcerated one (Somasundaram et al., 2000). The ulcerative damage with AZD3582 was significantly less than for naproxen. The precise mechanism for this is nevertheless uncertain. Estimates of the metabolism of CINODs and NO-releasing drugs suggest that the rate of NO release from these compounds both in vitro and in vivo is slow in comparison to other NO donors such as sodium nitroprusside (SNP) and S-nitroso-N-acetyl-D,L-penicillamine (Keeble and Moore, 2002). However NO certainly has the potential to increase microvascular blood flow (Whittle, 2003) and thus reduce the damage (Wallace et al., 2000), but it also increases mucous secretion, reduces secretion and adhesion of neu- trophils and reduces cytokine release from macrophages, all of which may be impaired by COX inhibition (Wallace et al., 2000). It has also been suggested that cytochrome P450 may play a role in the metabolism of CINODs (Grosser and Schroder, 2000). Alternatively the bioavailability of naproxen from a dose of AZD3582 may be lower than from a dose of naproxen.--In summary, AZD3582 is associated with equal changes in increased intestinal permeability and inflammation as equimolar doses of naproxen. At the same time it is associated with significantly less ulcerative small bowel damage. These findings are consistent to the suggestions that NO derived from AZD3582 counteracts the vascular effects of NSAID-induced inhibition of COX.--Acknowledgements. The drugs and solvents were supplied by AstraZeneca, Sweden who supported this project.--## References--Bjarnason, I., Hayllar, J., Macpherson, A. J. et al. (1993). Side effects of nonsteroidal anti-inflammatory drugs on the small and large intestine in humans. Gastroenterology 104: 1832-1847.--Burgaud, J. L., Ongini, E. and Del Soldato, P. (2002). Nitric oxidereleasing drugs - A novel class of effective and safe therapeutic agents. Ann N. Y. Acad. Sci. 962: 360-371.--Cirino, G., Wheeler-Jones, C. P., Wallace, J. L. et al. (1996). Inhibition of inducible nitric oxide synthase expression by novel nonsteroidal anti-inflammatory derivatives with gastrointestinal-sparing properties. Br. J. of Pharmacol. 117: 1421-1426.--Davies, N. M., Roseth, A. G., Appleyard, C. B. et al. (1997). NO-naproxen vs naproxen: Ulcerogenic, analgesic and anti- inflammatory effects. Aliment. Pharmacol. Ther. 11: 69-79.--Elliott, S. N., McKnight, W., Cirino, G. et al. (1995). A Nitric Oxide-Releasing Nonsteroidal Antiinflammatory Drug Accelerates GastricUlcer Healing in Rats. Gastroenterology 109: 524-530.--Fiorucci, S. (2001). NO-releasing NSAIDs are caspase inhibitors. Trends in Immunology 22: 232-235.--Fiorucci, S., Antonelli, E., Mencarelli, A. et al. (2002). A NO-releasing derivative of acetaminophen spares the liver by acting at several checkpoints in the Fas pathway. Br. J. of Pharmacol. 135: 589-599.--Fiorucci, S., Santucci, L., Greasele, P. et al. (2003). Gastrointestinal safety of NO-aspirin (NCX-4016) in healthy human volunteers: a proof of concept endoscopic study. Gastroenterology 124: 600-607.--Grosser, N. and Schroder, H. (2000). A common pathway for nitric oxide release from NO-aspirin and glyceryl trinitrate. Biochem. Biophys. Res. Commun. 274: 255-258.--Hawkey, C. J., Jones, I. J., Atherton, C. T. et al. (2003). Gastrointestinal safety of AZD3582, a cyclooxygenase inhibiting nitric oxide donator: proof of concept study in humans. Gut 52: 1537-1542.--Hawkey, C. J. and Langman, M. J. (2003). Non-steroidal anti-inflammatory drugs: overall risks and management. Complementary roles for COX-2 inhibitors and proton pump inhibitors. Gut 52: 600-608.--Keeble, J. E. and Moore, P. K. (2002). Pharmacology and potential therapeutic applications of nitric oxide-releasing non-steroidal anti-inflammatory and related nitric oxide-donating drugs. $B r . J$. of Pharmacol. 137: 295-310.--Laine, L., Bombardier, C., Hawkey, C. J. et al. (2002). Stratifying the risk of NSAID-related upper gastrointestinal clinical events: Results of a double-blind outcomes study in patients with rheumatoid arthritis. Gastroenterology 123: 1006-1012.--Lichtenberger, L. M., Wang, Z-M., Romero. J. J. et al. (1995) Non-steroidal anti-inflammatory drugs (NSAIDs) associate with zwitterionic phospholipids: Insight into the mechanism and reversal of NSAID-induced gastrointestinal injury. Nat Med 1: 154-158--Menconi, M. J., Unno, N., Smith, M. et al. (1998). Nitric oxide donor-induced hyperpermeability of cultured intestinal epithelial monolayers: role of superoxide radical, hydroxyl radical, and peroxynitrite. Biochim. Biophys. Acta. 1425: 189-203.--Rainsford, K. D. and Whitehouse, M. W. (1980). Anti-inflammatory antipyretic salicylic acid esters, with low gastric ulcerogenic activity. Agents Actions. 10: 451-456.--Sigthorsson, G., Tibble, J., Mahmud, T. et al. (2000). NSAID-Induced gastrointestinal damage: the biochemical consequences of the "ion trapping" hypothesis. Inflammopharmacology 8: 31-41.--Sigthorsson, G., Simpson, R. J., Walley, M. et al. (2002). COX-1 and 2 , intestinal integrity and pathogenesis of NSAID-enteropathy in mice. Gastroenterology 122: 1913-1923.--Somasundaram, S., Hayllar, J., Rafi S. et al. (1995). The biochemical basis of NSAID-induced damage to the gastrointestinal tract: A review and a hypothesis. Scand J Gastroenterology. 30: 289-299.--Somasundaram, S., Rafi, S., Jacob, M. et al. (1997). Intestinal tolerability of nitroxybutyl-flurbiprofen in rats. Gut 40: 608-613.--Somasundaram, S., Sigthorsson, G., Simpson, R. J. et al. (2000). Uncoupling of intestinal mitochondrial oxidative phosphorylation and inhibition of cyclooxygenase are required for the development of NSAID-enteropathy in the rat. Aliment Pharmacol Ther 14: 639650.--Wallace, J. L. and Miller, M. J. S. (2000). Nitric oxide in mucosal defense: A little goes a long way. Gastroenterology 119: 512-520.--Wallace, J. L., McKnight, W., Reuter B. K. et al. (2000). NSAID-induced gastric damage in rats: requirement for inhibition of both cyclooxygenase 1 and 2. Gastroenterology. 119: 706-714.--Wilder-Smith CH, J. B., Fornstedt-Wallin, B., Hedman, A. et al. (2006). Dose-effect comparisons of the CINOD AZD3582 and naproxen on upper gastrointestinal tract mucosal injury in healthy subjects. Scand J Gastroenterol 41: 264-273.--Whittle, B. J. (2003). Nitric oxide and the gut injury induced by nonsteroidalanti-inflammatory drugs. Inflammopharmacology 11:415422.diff --git a/tests/test_cli/pdf_dev/annotations/cleaned/cleaned_academic_literature_fbdb99151e811688574c0c4c67341074.md b/tests/test_cli/pdf_dev/annotations/cleaned/cleaned_academic_literature_fbdb99151e811688574c0c4c67341074.mddeleted file mode 100644index f0db1e9c..00000000--- a/tests/test_cli/pdf_dev/annotations/cleaned/cleaned_academic_literature_fbdb99151e811688574c0c4c67341074.md+++ /dev/null@@ -1,221 +0,0 @@-# Artificial Intelligence for 6G Networks: Technology Advancement and Standardization--Muhammad K. Shehzad, Luca Rose, M. Majid Butt, István Z. Kovács, Mohamad Assaad, and Mohsen Guizani--Abstract—With the deployment of 5G networks, standards organizations have started working on the design phase for sixth-generation ( $6 \mathrm{G}$ ) networks. $6 \mathrm{G}$ networks will be immensely complex, requiring more deployment time, cost and management efforts. On the other hand, mobile network operators demand these networks to be intelligent, self-organizing, and cost-effective to reduce operating expenses (OPEX). Machine learning (ML), a branch of artificial intelligence (AI), is the answer to many of these challenges providing pragmatic solutions, which can entirely change the future of wireless network technologies. By using some case study examples, we briefly examine the most compelling problems, particularly at the physical (PHY) and link layers in cellular networks where ML can bring significant gains. We also review standardization activities in relation to the use of ML in wireless networks and future timeline on readiness of standardization bodies to adapt to these changes. Finally, we highlight major issues in ML use in the wireless technology, and provide potential directions to mitigate some of them in $6 \mathrm{G}$ wireless networks.--Index Terms-AI, ML, Wireless networks, 3GPP, 6G.--## I. INTRODUCTION--Unprecedented growth in the global cellular traffic (as shown in Fig. 1) and immense data rate demands have become a challenge, leading wireless industry to the next-generation, called 6G. 6G-era will bring digital, physical and biological worlds together with the goal to improve human experience and well-being. $6 \mathrm{G}$ will be operating in TeraHertz $(\mathrm{THz})$ frequencies $(0.1-10 \mathrm{THz})$, hence beneficial for multiple use cases in industrial applications, providing immense data rates $(\approx 1 \mathrm{~Tb} / \mathrm{s})$, accelerating internet-of-things, and wider network coverage. AI/ML will pave the way for $\mathrm{THz}$ communications at different layers [2], e.g., supporting channel acquisition [3] and modulation classification [4] at PHY. Similarly, at the link layer, beamforming design and channel allocation can exploit ML [2]. In $\mathrm{THz}$ systems, a channel can significantly vary at a micrometer scale, resulting in a tremendous increase in channel estimation frequency and corresponding overhead. ML algorithms can counter this issue by using, e.g., improved channel prediction techniques [3], [5].----Fig. 1. Estimation of global mobile subscriptions in machine-to-machine (M2M) and mobile broadband (MBB) from 2020 to 2030. Source: ITU-R Report M. $2370-0$ [1].--Recently, fast-growing deployment of $5 \mathrm{G}$ has opened up many challenges, including massive complexity in network architecture, low latency, high cost, power consumption, and deployment of hybrid Long-Term Evolution (LTE) new radio $(\mathrm{NR})$, leading to difficulties in network optimization. In such a complex scenario, the network intelligence has become a major focus as it will play a pivotal role in complex problem solving [6], e.g., self-healing, self-optimization, and self-configuration of a network [7].--Future networks will become "cognitive" in a way that many aspects such as spectrum sensing/sharing, slicing, radio resource management (RRM), and mobility management, will be ML-based. Further, it is expected that ML will impact 6G air interface fundamentally and it will be designed to support ML natively [8]. Several recent research attempts, e.g., [9], propose different road maps for 6G, but they do not address standardization timeline and related issues regarding application of ML in 6G. Albeit, to some extent, [10] gives an overview of ML and standardization; nevertheless, ML-related technical challenges and its applications from an industrial and standardization perspective are not addressed.--Reconfigurable intelligent surface (RIS) and non-orthogonal multiple access (NOMA) are two key technologies for 6G [11]. RIS can re-engineer electromagnetic waves, hence beneficial to deliver the information where obstacles block the destination. RIS can be integrated with ML, allowing RIS to acquire envi-ronmental information by configuring various sensors, while ML can learn dynamic parameters intelligently, reducing the computation cost of RIS-based networks. Similarly, NOMA is a promising access technique for $6 \mathrm{G}$. In ML-empowered NOMA-based networks, gNodeBs ( $\mathrm{gNB}$ ) can intelligently define their control policy and improve decision-making ability.----Fig. 2. An overview of ML paradigms, major tools, and applications in wireless networks.--Today's networks use model-based methods to optimize various network functions providing characteristics of the process involved. However, these models might be too complex to be implemented in a realistic time frame or they include a great level of abstraction to function in a general environment. In contrast, ML-based solutions can adapt to real-time (RT) scenario changes and localized characteristics, learning the specific environment around the transceivers. The contributions of this article are twofold:--- We look at the above-mentioned problems from an industrial perspective and outline the gap between research and practice.-- We review standardization activities in the context of adopting ML in various aspects of wireless communications, e.g., channel acquisition, positioning. Furthermore, we highlight major issues and possible research directions in relation to the use of ML in wireless networks.--## II. OVERVIEW OF ML TECHNIQUES IN WIRELESS NETWORKS--ML is a process of training machines through data without explicit programming. Broadly speaking, ML consists of three paradigms: unsupervised learning, supervised learning, and reinforcement learning (RL). All these paradigms have a training/exploration phase to optimize a learning algorithm that later can be used in prediction/exploitation phase to infer on unknown inputs. As shown in Fig. 2, we briefly summarize them by providing some use cases in wireless networks.--1) Supervised Learning: Supervised learning exploits a labelled data set to learn a (hidden) function that maps an input to an expected output based on the examples. The standard techniques used to solve supervised learning-based problems are artificial neural networks (ANNs), support vector machines (SVMs), Bayesian networks, recurrent neural networks (RNNs), and convolutional neural networks (CNNs).-2) Unsupervised Learning: Unsupervised learning does not learn from labelled data, instead, training is based on an unlabelled data set. K-means and principal component analysis (PCA) are examples of two major tools used for clustering and dimensionality reduction, respectively.-3) Reinforcement Learning: RL is not based on training but rather the agent/decision-maker learns and decides online, maximizing a long-term reward. RL is beneficial in control problems where the agent adapts to changing environmental conditions, e.g., uplink power control.--Motivated by the considerable benefits of ML in various fields, its applications have also been considered in wireless networks almost at all layers of communication. Here, we focus on its impact on radio access networks (RAN), particularly PHY and link layers. Based on ML tools, given in Fig.2, some case studies will be explained later in Section III.--## A. Machine Learning at PHY--At PHY, many optimization problems are non-convex, e.g., sum-rate maximization. ML is a powerful tool to find good solution(s) for such non-convex optimization problems. Based on advanced learning algorithms, 6G networks provide the following major advantages by using ML.--- ML can be effective to deal with network complexity. 6G networks will be more complex due to numerous network topologies, immense growth in the cellular users, staggering data rate demands, complex air interface, vast network coordination methods, etc. Forecasting considerable complexity of $6 \mathrm{G}$ networks, the derivation of optimum performance solutions is nearly infeasible without ML.-- ML can play a vital role to deal with model deficit problems. Current cellular networks are amenable for mathematical derivation, for instance, information theory gives closed-form expressions for various problems such as Shannon theorem. However, the inherent complexity of $6 \mathrm{G}$ networks hinders the possibility of exploiting closed-form analytical expression(s), which can be due, for instance, to non-linearities either in the channel or network devices. ML offers an efficient way to deal with non-linearities, providing feasible solution(s) in a tractable manner.-- ML can cope with algorithm deficit problems. In current cellular networks, many optimal algorithms, although well-characterized, are impractical to be implemented. Considering the example of multiple-input multipleoutput (MIMO) systems where optimal solutions are known (e.g., dirty paper coding), they are overlooked in favour of linear solutions, e.g., linear minimum meansquared error. It is envisaged that ML can pave the way to implement more efficient yet practical solutions.--ML has been used to study various PHY issues, and without being exhaustive, some of the recent areas include:--- CNNs are used for modulation classification in [4].-- An RNN-based wireless channel predictor [5] is used in [3], explained in Section III-C to deal with inaccurate channel state information (CSI).--## III. Wireless Networks: Case Studies--In this section, we present three use cases to demonstrate the use of ML techniques in industrial wireless networks. ML tools utilized for these use cases are depicted in Fig. 2.--## A. UE Positioning--Highly accurate user equipment (UE) positioning is one of the prime considerations for Third Generation Partnership Project (3GPP) studies beyond Release 15. Various angle and time-of-arrival-based methods are used to determine UE positioning in today's cellular networks. All of these methods require triangulation techniques to resolve UE position and suffer from time synchronization errors.--We studied UE position by using radio frequency (RF) fingerprinting and two ML techniques, namely deep learning and decision tree, for an outdoor scenario [12]. Serving cell Reference Signal Received Power (RSRP) as well as neighbor cell RSRP values were used as features to train a deep neural network (DNN). As shown in Fig. 3, nearly $5 \mathrm{~m}$ accuracy is achieved for DNN when only 4 serving cell RSRP values and corresponding beam IDs are considered as a feature input, while it improves to nearly $1 \mathrm{~m}$ when 2 more RSRP values from the strongest neighboring cells, respective cell and beam IDs are added to the input feature set. The decision tree, a less complex algorithm as compared to DNN, provides about $2 \mathrm{~m}$ accuracy using data from both serving and neighboring cell beams as an input feature. The mean accuracy of nearly $1 \mathrm{~m}$ obtained from DNN is comparable to the accuracy level achieved with traditional methods without requiring triangulation and does not suffer from signal timing synchronization issues.--## B. ML-Assisted Proactive Mobility--For seamless and efficient mobility, a well optimized network should reduce the number of Handover (HO) events while avoiding Handover Failures (HOF) and Radio Link Failures (RLF). An emerging approach is to utilize ML-based algorithms, which enable proactive and UE specific mobility actions in the gNB. A relatively simple approach to this is to design an ML-based estimator of the radio measurements, such as RSRP of serving and neighbor cells, with a certain minimum accuracy and within a certain time horizon. Radio measurements are traditionally performed at the UEs side and reported to the serving $\mathrm{gNB}$ (or gNB-Centralized Unit) according to specific Radio Resource Control (RRC) configurations. For ML-based prediction purposes, time-traces of RSRP, or Reference Signal Received Quality (RSRQ) values need to be collected either in the UE and/or serving the gNB.----Fig. 3. Comparison of UE position for both DNN and decision tree techniques. The system level parameters for the network includes 8 sites with Inter-site distance $110 \mathrm{~m}$ and carrier frequency $28 \mathrm{GHz}$. For details of the parameters, please refer to [12].--For example, collected time-series of RSRP values are used as input to the ML-based predictor, which provides at the UE, and/or at the serving $\mathrm{gNB}$, a set of sufficiently accurately estimated RSRP values within a given future time horizon. Then, these signal estimations are used for predictive evaluation of possible $\mathrm{HO}$ conditions, thus can trigger proactive measurement reports from the UE and/or proactive $\mathrm{HO}$ actions at the serving $\mathrm{gNB}$. These two steps are repeated with a time periodicity given, e.g., by the sampling rate and time filtering of the input RSRP measurements [13], or alternatively, the steps can also be triggered by the serving $\mathrm{gNB}$ when certain traffic or mobility Quality-of-Service (QoS) conditions are met.--The outlined ML-based mobility algorithm can be implemented in either the UE or gNB or both, depending on the available ML assistance capabilities in each node. Furthermore, the mechanism can be integrated in self-organizing network-based Mobility Robustness Optimization solutions.--## C. CSI Feedback--CSI feedback in the downlink channel is a major challenge in Release 17 and beyond. Currently, CSI precision is affected by compressing the measurements imposed by the standard.--In our study, summarized in Section II-A, we assumed two RNN-based twin channel predictors at the $\mathrm{gNB}$ and UE [3]. The past CSI is utilized for training the RNN at both ends of the communication system. UE's feedback is evaluated with respect to the predicted channel. Fig. 4 depicts the meansquared error (MSE) between the actual channel versus the acquired channel at the $\mathrm{gNB}$ and the precoding gain when different quantization bits are used to feedback the CSI from the UE. The results are compared with and without using ML for the CSI feedback. A clear benefit of using ML can be observed. We believe that ML-based solutions will improve current performance without increasing signaling overhead.----(a) Trend of MSE.----(b) Trend of precoding gain.--Fig. 4. Performance of MSE and precoding gain. $2 \times 1$ MIMO configuration is considered, and RNN is composed of 1 hidden layer. For parameters' details, refer to [3].--## IV. Role of ML in Standardization--The potential of ML for $5 \mathrm{G}$ has been widely acknowledged in the literature and applications made it even in the standard at higher levels, e.g., for networking and security [7]. 3GPP has introduced a specification, named network data analytics function (NWDAF), in Release 15 and 16, as part of the $5 \mathrm{G}$ Core $(5 \mathrm{GC})$ architecture [7]. NWDAF is responsible for providing network analytics when requested by a network function (NF). Data is collected via application function (AF), operation, administration, and maintenance (OAM), NF, and data repositories. The specifications have also addressed the problem of inter-working for automation and data collection, which analytics vendors previously faced. 3GPP NWDAF framework for $5 \mathrm{G}$ systems is depicted in Fig.55. This automation gives leverage to network vendors for the deployment and testing of non-RT ML-related use cases. In Fig. 5. inward interfaces aggregate data from different network sources, where communication occurs using existing service-based interfaces. Outward interfaces provide decisions (analytics-based, algorithmic) to AF and NF.----Fig. 5. A generalized framework for 5G network automation in Release 16, representing that NWDAF should be able to collect data from the operator OAM, AFs and $5 \mathrm{GC}$ network functions $[7]$.--Regarding PHY, ML techniques lag behind, due to a number of issues. First, PHY makes use of abstractions and mathematical models that are inferred from the physical reality and electromagnetic principles. As long as such models describe the real-world precisely, there is no need for ML. Nevertheless, in practice, models and fixed algorithms are inefficient when facing rapidly changing and heterogeneous environments. For example, using the same channel acquisition scheme to acquire CSI from a laptop in line-of-sight with a $\mathrm{gNB}$, a tablet on a fast train, or a mobile quickly moving in a super densely covered area might not be optimal. Consequently, the standardization efforts of intelligent techniques have gained momentum, and while 3GPP is ready to begin a study item on ML implementations, open-radio access network (O-RAN) will be ML-native, defining a RAN intelligent controller (RIC), which will enhance several RAN functions.--3GPP has started studying the implications of the ML use at layer-1 and a study item on ML for NR air interface has been agreed upon. After the RAN-1 working group studies, protocol aspects will be studied in RAN-2 and subsequently, interoperability and testability aspects will be considered in RAN-4 working group. The remaining part of this section summarizes the status of the standardization of ML techniques for PHY for both 3GPP and O-RAN.--## A. CSI Feedback--CSI feedback for downlink channel in Release 17 is a complex issue in which UE-based beam selection is followed by CSI reference symbols (RS) training and precoding matrix index (PMI) reporting, and lastly by Demodulation Reference Signal (DMRS) and consequent estimation of the precoded channel. Broadly, beam selection aims to establish a sufficiently strong link budget between the UEs and the gNB. The CSI-RS is used for fine channel estimation, which is then fed back to the gNB to compute a precoder (eventually multiuser); finally, DMRS are precoded pilots that the UEs use to implement coherent demodulation. Currently, each of these phases is created following pre-established rules, with little to none room for intelligent behaviour. ML has been envisioned to possibly enhance each phase in a different way. Beam selection can be improved by intelligently correlating the beams with position or identity of the UEs. This would allow for a smart selection of the beams from the gNB side, thus avoiding brute-force selection. The CSI-RS can be enhanced by compressing the pilots and the PMI feedback exploiting ad hoc ML compressors. Furthermore, channel prediction techniques [5] can be used in order to pre-establish a baseline for the CSI feedback [3]. Other aspects that can be improved include frequency of pilots in both CSI-RS and DMRS, power and timing and CSI-RS port selection.--## B. $R S-D M R S$--Roughly speaking, DMRS are RS used for channel estimation to perform coherent demodulation. The correct estimation of the channel using such pilots have a strong impact on the performance in terms of bit-error-rate and thus block-errorrate. The role of the ML in such domain is twofold. First, it can be used to improve the performance of the channel estimation. Second, the ML can provide a smarter positioning of DMRS in order to reduce their frequency, hence reducing the overhead footprint in $6 \mathrm{G}$.--## C. Positioning--A precise positioning is one of the aspects that sees the largest improvement with respect to LTE's observed time difference of arrival (OTDOA) and uplink time difference of arrival (UTDOA), defined in Release 9 onward. Various aspects of $6 \mathrm{G}$ allow for precise positioning of the UE, such as large number of antenna elements at the $\mathrm{gNB}$, millimeter wave transmissions, dense network deployment. However, the methods based on angle-of-arrival and time-of-arrival fall short when non-line-of-sight scenarios are considered, in interference-limited scenarios. ML techniques, see Fig.2, are expected to help in improving the position by exploiting channel charting, hence learning the likely position of a UE based on a report, and multiplexing together information that carries positioning information but are hard to exploit in a classical way, such as CSI report and sounding reference signal maps.--## D. Mobility Enhancements--In 6G, frequent cell-selection, and frequent RSRP measurement could impact UEs' battery life. Furthermore, load balancing algorithms can use intelligent techniques that exploit the UE specific channel prediction, movement trajectory prediction and traffic demands prediction. Furthermore, the scenarios like fast-trains or non-terrestrial networks, will pose challenges to $\mathrm{HO}$ and conditional-HO operations. Novel solutions envisaged, compared to current 3GPP Release 17, include the use of UE specific ML-based predictive algorithms, addressed in Section III-B, designed to reduce paging errors and HO failures; thus, improve the overall QoS.--## E. Standardization for ML Data Collection--3GPP has started working on data collection for running ML algorithms in 5G networks [14]. The scope of such studies include identifying mechanisms to collect data from the network through minimization of drive test framework or further advanced enhancements. Furthermore, studies will focus on discussing hosting of ML models both for training as well as inference purposes at various network entities for various use cases and defining any new interfaces required for transporting data to the models.--## F. Federated Learning Model Collection--Training and prediction based on ML models will put an extra load on networks already transporting a large volume of data. Therefore, it is important to estimate the effect of model training and inference on network traffic, particularly for federated learning (FL) where UEs will act as distributed hosts [15]. The latency in collecting locally trained models is bounded in FL and network links should be able to meet delay budgets. This is particularly challenging in today's networks where a UE's own QoS requirements are already demanding and the FL model training and collection will further incur an extra burden on the network. Similarly, the split inference, where UEs cooperate with each other to perform joint inference, results in increasing the network traffic. 3GPP studies in Release 18 [15] will focus on the above mentioned issues to support training and inference for ML/FL models over wireless links.--## G. O-RAN-RIC--O-RAN alliance, aims to define a RAN network that is non-vendor specific, and that has an innate support for ML as an enabler for automation and OPEX savings. O-RAN alliance has defined interfaces for exchange of information in the protocol stack. To this end, in the O-RAN architecture, ML-assisted RAN intelligent controller (RIC) is included for network automation, for both scenarios, i.e., non-RT and RT. In the non-RT RIC, ML algorithms' training is done by using the data obtained at lower layers. However, the learning process remains slow; therefore, it is called non-RT RIC. Later, the learner is fed into the RT RIC, which utilizes the RT captured data to perform decisions online. Additionally, the functionality of non-RT includes policy management and higher layer procedure optimization. Therefore, the RAN or core-network can deploy such a mechanism based on the collected data.--## V. Open Challenges and Roadmap for Deploying ML TECHNIQUES--Though ML is a potential technology and enabler for nextgeneration wireless networks, several challenges related to its practical use are addressed below.--## A. Data Availability and Benchmarking--One of the foremost challenges in wireless networks is data availability. Data availability concerns the problem of identifying a common and accepted set of data (e.g., channel realizations) with the goal of testing and benchmarking ML algorithms. Such a problem is of a pivotal importance for standardization, where normally algorithms and proposals are tested using agreed underlying physical models (e.g., urban macrocells/microcells channel models), evaluation methodologies and calibrated simulators. Contrary to other fields, cellular networks have no standard data set to train and benchmark an ML algorithm. Therefore, a synthetic data set or software generated data set is of a predominant importance to train and benchmark ML algorithm(s), and to agree on a common evaluation methodology to rank proposition and standard algorithms.--Identifying a set of key performance indicators in wireless networks is another crucial task for ML standardization. It is necessary to design a set of metrics to classify and rank ML algorithms and their performance. Classic approaches such as throughput and signal-to-interference-plus-noise ratio (SINR) might not be sufficient since a small improvement in these values might come at the cost of large complexity augmentation and exacerbated energy consumption.----Fig. 6. Model collection for FL in a wireless network when some of the UEs have large blockage and use D2D communication for model transfer. Cluster-based UE selection is another solution for asynchronous model collection to meet network QoS requirements.--## B. Selection of ML versus Non-ML Solutions--ML tools are regarded as an implementation-oriented tool rather than a standard relevant aspect. The idea behind this relies on the fact that each vendor has the freedom to efficiently implement each aspect of the standard as long as the external interfaces are respected. A simple example of this is given in the CSI feedback, where a UE needs to select a specific PMI, but the standard does not specify any specific way in which this selection is performed. Recently, however, the idea of having ML dedicated message exchanges and performance that only an ML-aided algorithm can achieve has paved the way for standardization of ML algorithms [3]. This opens the door for several issues, e.g., will the standard impose a specific ML structure, classifying minimum performance and implementation structure, or will it remain far from the implementation? With regards to NNs, it is still open if hyperparameters are going to be left to vendor-specific implementation or will they be set by the standard.--## C. Complexity of ML Algorithms--Considering the limited battery life, storage, computational capability, and limited communication bandwidth in most cellular network entities, an ML model's cost-performance tradeoff becomes a fundamental issue. Another issue is the speed/time-steps at which the training and inference needs to be performed. Whereas hard-wired gNB have sufficient computational power to run complex ML algorithms, UEs need to face battery, heating and stringent complexity limits. Possible solutions to such issue include, but not limited to implementation of substitute rule-based algorithms at the UE side, migrating the load all on the $\mathrm{gNB}$ side.--## D. Communication-aware Federated Learning--Traditional ML models support centralized learning. Due to difficulties in collecting large amount of training data from the UEs, privacy issues and bandwidth bottleneck, FL has emerged as a promising solution. In FL, training is performed distributively over network devices, called local model hosts, and an application server on the network side acts as a central host to aggregate local models transmitted by the local learners. Typically, an application server host aggregates models only when updates are available from all the local learners, called synchronous model transfer. However, this is highly inefficient in wireless networks where links are unpredictable, local learners (UEs) are energy limited and have their own QoS requirements. Asynchronous model collection is the most viable solution for FL in wireless networks, where a subset of UEs is selected for a local model update in each round of model collection. However, UE selection in each round is a complex problem because UEs are energy limited and the network bandwidth is scarce, hindering collection of local models from all the UEs to represent independently and identically data collection. These mechanisms are usually vendor proprietary, but standardization still needs to define some common mechanisms for efficient model collection. As shown in Fig. 6. UE clustering and local device-to-device (D2D) communication for asynchronous model collection are possible solutions to decrease network communication and will require standardization support.--## E. Stability and Adaptability of ML Techniques--ML algorithms applied to wireless networks must be adaptive as they will have to deal with parameters that change dynamically. Particularly, the weights of the NN are evaluated online based on the trained data. However, this approach may not be applicable in wireless, and specifically in a standard, where coordination among entities belonging to different operators and provided by different vendors have to coexist, and in which the need for quick response could prevent one or the other solution. Possible solutions include: pre-trained $\mathrm{NN}$, or partially trained $\mathrm{NN}$ (i.e., $\mathrm{NN}$ in which the starting point is pre-set); cloud-based downloadable data set for $\mathrm{NN}$ training; codebook-based $\mathrm{NN}$, in which a codebook of different NNs is used and agreed upon between the gNB and UEs. Another related problem is to detect an outdated ML model with high inference error and replace it. Replacing an outdated model with a new model incurs further delay. Thus, there must be a proactive mechanism to adapt the ML model to network conditions such that network functions suffer minimum performance loss.--## VI. Conclusion--Motivated by the promise of the use of ML algorithms, we presented an overview of ML techniques to be used in 5G-Advanced and 6G wireless networks. Furthermore, we discussed the key roles of ML-based solutions from industrial and standardization perspectives. We also highlighted the practical challenges of deploying ML techniques in wireless networks and how to deal with them. Non-RT and higher layer ML-based solutions can be, and are, applied already in today's networks. Implementing RT ML solutions at PHY/MAC in 6G networks are the next big challenge in the research community. We believe that overcoming these challenges, both in research as well as at standardization levels, will pave the way for next-generation wireless communication to be effective and sustainable.--## REFERENCES--[1] I. Union, "IMT traffic estimates for the years 2020 to 2030," Report ITU, pp. 2370-0, 2015.--[2] A.-A. A. Boulogeorgos, E. Yaqub, M. Di Renzo, A. Alexiou, R. Desai, and R. Klinkenberg, "Machine learning: A catalyst for $\mathrm{THz}$ wireless networks," Frontiers in Communications and Networks, p. 37, 2021.--[3] M. K. Shehzad, L. Rose, and M. Assaad, "Dealing with CSI compression to reduce losses and overhead: An artificial intelligence approach," in 2021 IEEE International Conference on Communications Workshops (ICC Workshops), 2021, pp. 1-6.--[4] T. O'Shea and J. Hoydis, "An introduction to deep learning for the physical layer," IEEE Transactions on Cognitive Communications and Networking, vol. 3, no. 4, pp. 563-575, 2017.--[5] M. K. Shehzad, L. Rose, S. Wesemann, and M. Assaad, "ML-based massive MIMO channel prediction: Does it work on real-world data?" IEEE Wireless Communications Letters, pp. 1-5, 2022.--[6] B. Mao, F. Tang, Y. Kawamoto, and N. Kato, "Optimizing computation offloading in satellite-UAV-served 6G IoT: A deep learning approach," IEEE Network, vol. 35, no. 4, pp. 102-108, 2021.--[7] 3GPP, "Study of enablers for network automation for 5G (Release 16)," https://portal.3gpp.org/desktopmodules/Specifications/ SpecificationDetails.aspx?specificationId=3252, , Technical Report (TR) $23.791,062019$.--[8] J. Hoydis, F. A. Aoudia, A. Valcarce, and H. Viswanathan, "Toward a 6G AI-native air interface," IEEE Communications Magazine, vol. 59, no. 5, pp. 76-81, 2021.--[9] F. Tariq, M. R. Khandaker, K.-K. Wong, M. A. Imran, M. Bennis, and M. Debbah, "A speculative study on 6G," IEEE Wireless Communications, vol. 27, no. 4, pp. 118-125, 2020.--[10] R. Shafin, L. Liu, V. Chandrasekhar, H. Chen, J. Reed, and J. C. Zhang, "Artificial intelligence-enabled cellular networks: A critical path to beyond-5G and 6G," IEEE Wireless Communications, vol. 27, no. 2, pp. 212-217, 2020.--[11] R. Zhong, Y. Liu, X. Mu, Y. Chen, and L. Song, "AI empowered RISassisted NOMA networks: Deep learning or reinforcement learning?" IEEE Journal on Selected Areas in Communications, vol. 40, no. 1, pp. $182-196,2022$.--[12] M. M. Butt, A. Pantelidou, and I. Z. Kovács, "ML-assisted UE positioning: performance analysis and 5G architecture enhancements," IEEE Open Journal of Vehicular Technology, vol. 2, pp. 377-388, 2021.--[13] 3GPP, "NR; Radio Resource Control (RRC); Protocol specification (Release 15)," https://portal.3gpp.org/desktopmodules/Specifications/ SpecificationDetails.aspx?specificationId=3197 , Technical report (TR) TS38.331, 032021.--[14] - , "Study on enhancement for data collection for NR and ENDC (Release 17)," https://portal.3gpp.org/desktopmodules/Specifications/ SpecificationDetails.aspx?specificationId=3817 , Technical report (TR) $37.817,012021$.--[15] -, "5G System (5GS); Study on traffic characteristics and performance requirements for AI/ML model transfer (Release 18)," https://portal.3gpp.org/desktopmodules/Specifications/ SpecificationDetails.aspx?specificationId=3721 , Technical report (TR) $22.874,032021$.----Muhammad K. Shehzad [S'21] is working as a Research Engineer and Ph.D. student at Nokia Bell-Labs and CentraleSupelec, Paris, France, respectively. He received his B.Eng. (Hons.) degree in Electrical and Electronic Engineering from the University of Bradford, Bradford, U.K., in 2016, and M.S. in Electrical Engineering from the National University of Sciences \& Technology (NUST), Islamabad, Pakistan, in 2019. His major research interest is in MIMO communication using Artificial Intelligence (AI)/Machine Learning (ML).----Luca Rose [M'11] is Senior research and standard-ization expert with Nokia Bell-labs. He received his M.Sc. from university of Pisa, Italy, and his Ph.D. in Physics from Centrale-Supelec. He worked with Huawei France research center and Thales Communications and Security, contributing to several standard organizations. He is currently an ITU-R and ETSI delegate and the lead editor of IEEE Communication magazine series on IoT. His interests span from the field of AI/ML to Game theory.----M. Majid Butt [SM'15] is a Senior Specialist at Nokia Bell-Labs, France, and an adjunct Professor at Trinity College Dublin, Ireland. He has authored more than 70 peer-reviewed conference and journal articles and filed over 30 patents. He is IEEE Comsoc distinguished lecturer for the class 2022-23. He frequently gives invited and technical tutorial talks on various topics in IEEE conferences and serves as an associate editor for IEEE Communication Magazine, IEEE Open Journal of the Communication Society and IEEE Open Journal of Vehicular Technology.----István Z. Kovács [M’00] received his B.Sc. from "Politehnica" Technical University of Timişoara, Romania in 1989, his M.Sc.E.E. from École Nationale Supérieure des Télécommunications de Bretagne, France in 1996, and his Ph.D.E.E. in Wireless Communications from Aalborg University, Denmark in 2002. Currently he is senior research engineer at Nokia, Aalborg, Denmark, where he conducts research on machine learning-driven radio resource management and radio connectivity enhancements for non-terrestrial and aerial vehicle communications, in LTE and 5G networks.----Mohamad Assaad [SM'15] is a Professor at CentraleSupelec, France and a researcher at the Laboratory of Signals and Systems (CNRS). He has coauthored 1 book and more than 120 journal and conference papers and serves regularly as TPC cochair for top-tier international conferences. He is currently an Editor for the IEEE Wireless Communications Letters and Journal of Communications and Information Networks. His research interests include 5G and beyond systems, and Machine Learning in wireless networks.----Mohsen Guizani [F'09] is currently a Professor at the Machine Learning Department at the Mohamed Bin Zayed University of Artificial Intelligence (MBZUAI), Abu Dhabi, UAE. His main research interests are wireless communications and IoT security. He was elevated to the IEEE Fellow in 2009. He was listed as a Clarivate Analytics Highly Cited Researcher in Computer Science in 2019, 2020 and 2021. Dr. Guizani has won several research awards. He is the author of ten books and more than 800 publications.diff --git a/tests/test_cli/pdf_dev/annotations/cleaned/cleaned_ordinary_textbook_1d9a847603a5e37e379738316820850d.md b/tests/test_cli/pdf_dev/annotations/cleaned/cleaned_ordinary_textbook_1d9a847603a5e37e379738316820850d.mddeleted file mode 100644index 2143a627..00000000--- a/tests/test_cli/pdf_dev/annotations/cleaned/cleaned_ordinary_textbook_1d9a847603a5e37e379738316820850d.md+++ /dev/null@@ -1,28 +0,0 @@-# 数学新星问题征解--第十五期 (2016.06)--主持: 牟晓生--第一题. 设 $z_{1}, z_{2}, z_{3}$ 是单位复数. 证明存在单位复数 $z$ 使得:--$$-\frac{1}{\left|z-z_{1}\right|^{2}}+\frac{1}{\left|z-z_{2}\right|^{2}}+\frac{1}{\left|z-z_{3}\right|^{2}} \leq \frac{9}{4}-$$--(湖北武钢三中学生 王逸轩, 上海大学冷岗松 供题)--第二题. 如图, $D$ 是正三角形 $A B C$ 的边 $B C$ 上一点, $B D>C D$. 记 $O_{1}, I_{1}$ 为 $\triangle A B D$ 的外心与内心, $O_{2}, I_{2}$ 为 $\triangle A C D$ 的外心与内心. 圆 $I_{1}$ 与圆 $I_{2}$ 除 $B C$外的另一条外公切线交 $A B, A C$ 于 $P, Q$. 设直线 $P I_{1}$与 $Q I_{2}$ 交于 $R$, 而直线 $O_{1} I_{1}$ 与 $O_{2} I_{2}$ 交于 $T$. 证明: $A T^{2}=A R^{2}+A D \cdot B C$.--(广西钦州 卢圣 供题)----第三题. 给定正整数 $m, n$, 考虑在 $m \times n$ 白棋盘上先将一些格染成黑色. 在之后的每一时刻, 若存在一个白格至少与两个黑格相邻, 则可将它也染成黑色. 求最初至少要染多少个黑色格才能在某一时刻染黑整个棋盘?--(哈佛大学 牟晓生 供题)--第四题. $A B C$ 是一个三角形, 而 $P, Q, R$ 分别是 $B C, C A, A B$ 上的点。证明 $\triangle P Q R$ 的周长不小于 $\triangle A Q R, \triangle B R P, \triangle C P Q$ 周长的最小值.--(哈佛大学 牟晓生 供题)-diff --git a/tests/test_cli/pdf_dev/ordinary_textbook_1d9a847603a5e37e379738316820850d_model.json b/tests/test_cli/pdf_dev/ordinary_textbook_1d9a847603a5e37e379738316820850d_model.jsondeleted file mode 100644index a1487228..00000000--- a/tests/test_cli/pdf_dev/ordinary_textbook_1d9a847603a5e37e379738316820850d_model.json+++ /dev/null@@ -1,1288 +0,0 @@-[- {- "layout_dets": [- {- "category_id": 1,- "poly": [- 245.17965698242188,- 1408.162841796875,- 1409.9876708984375,- 1408.162841796875,- 1409.9876708984375,- 1576.8612060546875,- 245.17965698242188,- 1576.8612060546875- ],- "score": 0.9999911189079285- },- {- "category_id": 1,- "poly": [- 625.3294067382812,- 753.8365478515625,- 1410.015380859375,- 753.8365478515625,- 1410.015380859375,- 797.5187377929688,- 625.3294067382812,- 797.5187377929688- ],- "score": 0.9999904632568359- },- {- "category_id": 1,- "poly": [- 243.91610717773438,- 900.430419921875,- 1029.7550048828125,- 900.430419921875,- 1029.7550048828125,- 1246.8853759765625,- 243.91610717773438,- 1246.8853759765625- ],- "score": 0.9999890327453613- },- {- "category_id": 1,- "poly": [- 244.826171875,- 575.121826171875,- 1113.444091796875,- 575.121826171875,- 1113.444091796875,- 624.2438354492188,- 244.826171875,- 624.2438354492188- ],- "score": 0.9999887347221375- },- {- "category_id": 1,- "poly": [- 698.5866088867188,- 1262.7681884765625,- 1032.8016357421875,- 1262.7681884765625,- 1032.8016357421875,- 1304.719970703125,- 698.5866088867188,- 1304.719970703125- ],- "score": 0.9999858736991882- },- {- "category_id": 1,- "poly": [- 1047.3941650390625,- 1589.7156982421875,- 1407.320556640625,- 1589.7156982421875,- 1407.320556640625,- 1635.564453125,- 1047.3941650390625,- 1635.564453125- ],- "score": 0.9999785423278809- },- {- "category_id": 0,- "poly": [- 586.237060546875,- 268.1336669921875,- 1070.578857421875,- 268.1336669921875,- 1070.578857421875,- 333.3851623535156,- 586.237060546875,- 333.3851623535156- ],- "score": 0.9999648332595825- },- {- "category_id": 3,- "poly": [- 1064.586669921875,- 891.74169921875,- 1405.2781982421875,- 891.74169921875,- 1405.2781982421875,- 1323.926513671875,- 1064.586669921875,- 1323.926513671875- ],- "score": 0.9999620318412781- },- {- "category_id": 1,- "poly": [- 245.0867156982422,- 1737.461181640625,- 1407.4088134765625,- 1737.461181640625,- 1407.4088134765625,- 1844.520751953125,- 245.0867156982422,- 1844.520751953125- ],- "score": 0.9999591112136841- },- {- "category_id": 1,- "poly": [- 728.7286376953125,- 464.164306640625,- 925.77294921875,- 464.164306640625,- 925.77294921875,- 507.0546875,- 728.7286376953125,- 507.0546875- ],- "score": 0.9999172687530518- },- {- "category_id": 1,- "poly": [- 671.8990478515625,- 403.32611083984375,- 982.4508666992188,- 403.32611083984375,- 982.4508666992188,- 447.346435546875,- 671.8990478515625,- 447.346435546875- ],- "score": 0.9999128580093384- },- {- "category_id": 1,- "poly": [- 1050.064697265625,- 1859.377197265625,- 1406.635009765625,- 1859.377197265625,- 1406.635009765625,- 1901.196533203125,- 1050.064697265625,- 1901.196533203125- ],- "score": 0.9998365640640259- },- {- "category_id": 8,- "poly": [- 559.9688720703125,- 640.2896728515625,- 1096.220458984375,- 640.2896728515625,- 1096.220458984375,- 732.165283203125,- 559.9688720703125,- 732.165283203125- ],- "score": 0.9991127252578735- },- {- "category_id": 13,- "poly": [- 409,- 581,- 530,- 581,- 530,- 621,- 409,- 621- ],- "score": 0.93,- "latex": "z_{1},z_{2},z_{3}"- },- {- "category_id": 13,- "poly": [- 539,- 963,- 627,- 963,- 627,- 1005,- 539,- 1005- ],- "score": 0.93,- "latex": "O_{1},I_{1}"- },- {- "category_id": 13,- "poly": [- 754,- 1741,- 864,- 1741,- 864,- 1783,- 754,- 1783- ],- "score": 0.93,- "latex": "P,Q,R"- },- {- "category_id": 13,- "poly": [- 725,- 1144,- 798,- 1144,- 798,- 1185,- 725,- 1185- ],- "score": 0.92,- "latex": "O_{2}I_{2}"- },- {- "category_id": 13,- "poly": [- 738,- 1413,- 836,- 1413,- 836,- 1451,- 738,- 1451- ],- "score": 0.92,- "latex": "m\\times n"- },- {- "category_id": 13,- "poly": [- 602,- 1144,- 674,- 1144,- 674,- 1184,- 602,- 1184- ],- "score": 0.92,- "latex": "O_{1}I_{1}"- },- {- "category_id": 13,- "poly": [- 246,- 1023,- 332,- 1023,- 332,- 1065,- 246,- 1065- ],- "score": 0.92,- "latex": "O_{2},I_{2}"- },- {- "category_id": 13,- "poly": [- 304,- 963,- 470,- 963,- 470,- 1002,- 304,- 1002- ],- "score": 0.92,- "latex": "B D\\,>\\,C D"- },- {- "category_id": 13,- "poly": [- 289,- 1144,- 350,- 1144,- 350,- 1186,- 289,- 1186- ],- "score": 0.91,- "latex": "Q I_{2}"- },- {- "category_id": 14,- "poly": [- 557,- 640,- 1093,- 640,- 1093,- 729,- 557,- 729- ],- "score": 0.91,- "latex": "\\frac{1}{|z-z_{1}|^{2}}+\\frac{1}{|z-z_{2}|^{2}}+\\frac{1}{|z-z_{3}|^{2}}\\leq\\frac{9}{4}."- },- {- "category_id": 13,- "poly": [- 767,- 1083,- 835,- 1083,- 835,- 1125,- 767,- 1125- ],- "score": 0.91,- "latex": "P,Q"- },- {- "category_id": 13,- "poly": [- 597,- 1082,- 720,- 1082,- 720,- 1124,- 597,- 1124- ],- "score": 0.9,- "latex": "A B,A C"- },- {- "category_id": 13,- "poly": [- 988,- 1740,- 1176,- 1740,- 1176,- 1783,- 988,- 1783- ],- "score": 0.9,- "latex": "B C,C A,A B"- },- {- "category_id": 13,- "poly": [- 968,- 1084,- 1026,- 1084,- 1026,- 1123,- 968,- 1123- ],- "score": 0.9,- "latex": "P I_{1}"- },- {- "category_id": 13,- "poly": [- 546,- 1414,- 615,- 1414,- 615,- 1453,- 546,- 1453- ],- "score": 0.9,- "latex": "m,n"- },- {- "category_id": 13,- "poly": [- 570,- 1800,- 921,- 1800,- 921,- 1843,- 570,- 1843- ],- "score": 0.89,- "latex": "\\triangle A Q R,\\triangle B R P,\\triangle C P Q"- },- {- "category_id": 13,- "poly": [- 771,- 1024,- 806,- 1024,- 806,- 1064,- 771,- 1064- ],- "score": 0.88,- "latex": "I_{1}"- },- {- "category_id": 13,- "poly": [- 887,- 1024,- 921,- 1024,- 921,- 1063,- 887,- 1063- ],- "score": 0.88,- "latex": "I_{2}"- },- {- "category_id": 13,- "poly": [- 996,- 585,- 1021,- 585,- 1021,- 616,- 996,- 616- ],- "score": 0.82,- "latex": "z"- },- {- "category_id": 13,- "poly": [- 475,- 904,- 510,- 904,- 510,- 941,- 475,- 941- ],- "score": 0.81,- "latex": "D"- },- {- "category_id": 13,- "poly": [- 437,- 1145,- 467,- 1145,- 467,- 1181,- 437,- 1181- ],- "score": 0.8,- "latex": "R"- },- {- "category_id": 13,- "poly": [- 884,- 1145,- 914,- 1145,- 914,- 1181,- 884,- 1181- ],- "score": 0.8,- "latex": "T"- },- {- "category_id": 14,- "poly": [- 246,- 1203,- 593,- 1203,- 593,- 1244,- 246,- 1244- ],- "score": 0.78,- "latex": "A T^{2}=A R^{2}+A D\\cdot B C."- },- {- "category_id": 13,- "poly": [- 883,- 903,- 943,- 903,- 943,- 942,- 883,- 942- ],- "score": 0.74,- "latex": "B C"- },- {- "category_id": 13,- "poly": [- 969,- 1024,- 1028,- 1024,- 1028,- 1061,- 969,- 1061- ],- "score": 0.73,- "latex": "B C"- },- {- "category_id": 13,- "poly": [- 380,- 1023,- 494,- 1023,- 494,- 1062,- 380,- 1062- ],- "score": 0.67,- "latex": "\\triangle A C D"- },- {- "category_id": 13,- "poly": [- 246,- 1800,- 360,- 1800,- 360,- 1842,- 246,- 1842- ],- "score": 0.6,- "latex": "\\triangle P Q R"- },- {- "category_id": 13,- "poly": [- 677,- 963,- 793,- 963,- 793,- 1002,- 677,- 1002- ],- "score": 0.52,- "latex": "\\triangle A B D"- },- {- "category_id": 13,- "poly": [- 710,- 902,- 795,- 902,- 795,- 942,- 710,- 942- ],- "score": 0.41,- "latex": "A B C"- },- {- "category_id": 13,- "poly": [- 379,- 1740,- 463,- 1740,- 463,- 1780,- 379,- 1780- ],- "score": 0.31,- "latex": "A B C"- },- {- "category_id": 13,- "poly": [- 1381,- 1166,- 1393,- 1166,- 1393,- 1178,- 1381,- 1178- ],- "score": 0.26,- "latex": "c"- },- {- "category_id": 15,- "poly": [- 254.0,- 1476.0,- 1400.0,- 1476.0,- 1400.0,- 1511.0,- 254.0,- 1511.0- ],- "score": 0.99,- "text": "的每一时刻,若存在一个白格至少与两个黑格相邻,则可将它也染成黑色.求最初"- },- {- "category_id": 15,- "poly": [- 256.0,- 1537.0,- 1031.0,- 1537.0,- 1031.0,- 1572.0,- 256.0,- 1572.0- ],- "score": 0.98,- "text": "至少要染多少个黑色格才能在某一时刻染黑整个棋盘?"- },- {- "category_id": 15,- "poly": [- 837.0,- 1418.0,- 1403.0,- 1418.0,- 1403.0,- 1452.0,- 837.0,- 1452.0- ],- "score": 0.99,- "text": "白棋盘上先将一些格染成黑色.在之后"- },- {- "category_id": 15,- "poly": [- 254.0,- 1418.0,- 545.0,- 1418.0,- 545.0,- 1452.0,- 254.0,- 1452.0- ],- "score": 1.0,- "text": "第三题.给定正整数"- },- {- "category_id": 15,- "poly": [- 616.0,- 1418.0,- 737.0,- 1418.0,- 737.0,- 1452.0,- 616.0,- 1452.0- ],- "score": 0.94,- "text": ",考虑在"- },- {- "category_id": 15,- "poly": [- 645.0,- 763.0,- 1400.0,- 763.0,- 1400.0,- 797.0,- 645.0,- 797.0- ],- "score": 0.98,- "text": "(湖北武钢三中学生 王逸轩,上海大学冷岗松 供题)"- },- {- "category_id": 15,- "poly": [- 675.0,- 1150.0,- 724.0,- 1150.0,- 724.0,- 1184.0,- 675.0,- 1184.0- ],- "score": 1.0,- "text": "与"- },- {- "category_id": 15,- "poly": [- 251.0,- 970.0,- 303.0,- 970.0,- 303.0,- 1004.0,- 251.0,- 1004.0- ],- "score": 0.99,- "text": "点,"- },- {- "category_id": 15,- "poly": [- 471.0,- 970.0,- 538.0,- 970.0,- 538.0,- 1004.0,- 471.0,- 1004.0- ],- "score": 0.71,- "text": ".记"- },- {- "category_id": 15,- "poly": [- 254.0,- 1150.0,- 288.0,- 1150.0,- 288.0,- 1184.0,- 254.0,- 1184.0- ],- "score": 1.0,- "text": "与"- },- {- "category_id": 15,- "poly": [- 251.0,- 1089.0,- 596.0,- 1089.0,- 596.0,- 1123.0,- 251.0,- 1123.0- ],- "score": 1.0,- "text": "外的另一条外公切线交"- },- {- "category_id": 15,- "poly": [- 721.0,- 1089.0,- 766.0,- 1089.0,- 766.0,- 1123.0,- 721.0,- 1123.0- ],- "score": 1.0,- "text": "于"- },- {- "category_id": 15,- "poly": [- 836.0,- 1089.0,- 967.0,- 1089.0,- 967.0,- 1123.0,- 836.0,- 1123.0- ],- "score": 0.97,- "text": ".设直线"- },- {- "category_id": 15,- "poly": [- 807.0,- 1026.0,- 886.0,- 1023.0,- 886.0,- 1065.0,- 807.0,- 1067.0- ],- "score": 1.0,- "text": "与圆"- },- {- "category_id": 15,- "poly": [- 251.0,- 906.0,- 474.0,- 906.0,- 474.0,- 940.0,- 251.0,- 940.0- ],- "score": 0.95,- "text": "第二题.如图,"- },- {- "category_id": 15,- "poly": [- 351.0,- 1150.0,- 436.0,- 1150.0,- 436.0,- 1184.0,- 351.0,- 1184.0- ],- "score": 1.0,- "text": "交于"- },- {- "category_id": 15,- "poly": [- 468.0,- 1150.0,- 601.0,- 1150.0,- 601.0,- 1184.0,- 468.0,- 1184.0- ],- "score": 1.0,- "text": ",而直线"- },- {- "category_id": 15,- "poly": [- 799.0,- 1150.0,- 883.0,- 1150.0,- 883.0,- 1184.0,- 799.0,- 1184.0- ],- "score": 1.0,- "text": "交于"- },- {- "category_id": 15,- "poly": [- 915.0,- 1150.0,- 1024.0,- 1150.0,- 1024.0,- 1184.0,- 915.0,- 1184.0- ],- "score": 0.86,- "text": ".证明:"- },- {- "category_id": 15,- "poly": [- 944.0,- 906.0,- 1019.0,- 906.0,- 1019.0,- 940.0,- 944.0,- 940.0- ],- "score": 0.99,- "text": "上一"- },- {- "category_id": 15,- "poly": [- 922.0,- 1026.0,- 968.0,- 1023.0,- 968.0,- 1065.0,- 922.0,- 1067.0- ],- "score": 1.0,- "text": "除"- },- {- "category_id": 15,- "poly": [- 333.0,- 1026.0,- 379.0,- 1023.0,- 379.0,- 1065.0,- 333.0,- 1067.0- ],- "score": 1.0,- "text": "为"- },- {- "category_id": 15,- "poly": [- 495.0,- 1026.0,- 770.0,- 1023.0,- 770.0,- 1065.0,- 495.0,- 1067.0- ],- "score": 0.99,- "text": "的外心与内心.圆"- },- {- "category_id": 15,- "poly": [- 628.0,- 970.0,- 676.0,- 970.0,- 676.0,- 1004.0,- 628.0,- 1004.0- ],- "score": 1.0,- "text": "为"- },- {- "category_id": 15,- "poly": [- 794.0,- 970.0,- 1024.0,- 970.0,- 1024.0,- 1004.0,- 794.0,- 1004.0- ],- "score": 0.97,- "text": "的外心与内心,"- },- {- "category_id": 15,- "poly": [- 511.0,- 906.0,- 709.0,- 906.0,- 709.0,- 940.0,- 511.0,- 940.0- ],- "score": 1.0,- "text": "是正三角形"- },- {- "category_id": 15,- "poly": [- 796.0,- 906.0,- 882.0,- 906.0,- 882.0,- 940.0,- 796.0,- 940.0- ],- "score": 1.0,- "text": "的边"- },- {- "category_id": 15,- "poly": [- 251.0,- 582.0,- 408.0,- 582.0,- 408.0,- 624.0,- 251.0,- 624.0- ],- "score": 1.0,- "text": "第一题.设"- },- {- "category_id": 15,- "poly": [- 531.0,- 582.0,- 995.0,- 582.0,- 995.0,- 624.0,- 531.0,- 624.0- ],- "score": 1.0,- "text": "是单位复数.证明存在单位复数"- },- {- "category_id": 15,- "poly": [- 1022.0,- 582.0,- 1105.0,- 582.0,- 1105.0,- 624.0,- 1022.0,- 624.0- ],- "score": 0.98,- "text": "使得:"- },- {- "category_id": 15,- "poly": [- 704.0,- 1267.0,- 1026.0,- 1267.0,- 1026.0,- 1308.0,- 704.0,- 1308.0- ],- "score": 0.95,- "text": "(广西钦州 卢圣 供题)"- },- {- "category_id": 15,- "poly": [- 1053.0,- 1596.0,- 1405.0,- 1596.0,- 1405.0,- 1637.0,- 1053.0,- 1637.0- ],- "score": 0.96,- "text": "(哈佛大学 牟晓生 供题)"- },- {- "category_id": 15,- "poly": [- 596.0,- 278.0,- 1058.0,- 278.0,- 1058.0,- 329.0,- 596.0,- 329.0- ],- "score": 1.0,- "text": "数学新星问题征解"- },- {- "category_id": 15,- "poly": [- 865.0,- 1745.0,- 987.0,- 1745.0,- 987.0,- 1786.0,- 865.0,- 1786.0- ],- "score": 1.0,- "text": "分别是"- },- {- "category_id": 15,- "poly": [- 1177.0,- 1745.0,- 1405.0,- 1745.0,- 1405.0,- 1786.0,- 1177.0,- 1786.0- ],- "score": 1.0,- "text": "上的点。证明"- },- {- "category_id": 15,- "poly": [- 922.0,- 1808.0,- 1130.0,- 1808.0,- 1130.0,- 1842.0,- 922.0,- 1842.0- ],- "score": 1.0,- "text": "周长的最小值"- },- {- "category_id": 15,- "poly": [- 361.0,- 1808.0,- 569.0,- 1808.0,- 569.0,- 1842.0,- 361.0,- 1842.0- ],- "score": 1.0,- "text": "的周长不小于"- },- {- "category_id": 15,- "poly": [- 251.0,- 1745.0,- 378.0,- 1745.0,- 378.0,- 1786.0,- 251.0,- 1786.0- ],- "score": 0.97,- "text": "第四题."- },- {- "category_id": 15,- "poly": [- 464.0,- 1745.0,- 753.0,- 1745.0,- 753.0,- 1786.0,- 464.0,- 1786.0- ],- "score": 1.0,- "text": "是一个三角形,而"- },- {- "category_id": 15,- "poly": [- 729.0,- 465.0,- 923.0,- 465.0,- 923.0,- 509.0,- 729.0,- 509.0- ],- "score": 1.0,- "text": "主持:牟晓生"- },- {- "category_id": 15,- "poly": [- 672.0,- 404.0,- 982.0,- 404.0,- 982.0,- 453.0,- 672.0,- 453.0- ],- "score": 1.0,- "text": "第十五期 (2016.06)"- },- {- "category_id": 15,- "poly": [- 1049.0,- 1856.0,- 1408.0,- 1862.0,- 1407.0,- 1910.0,- 1048.0,- 1905.0- ],- "score": 0.97,- "text": "(哈佛大学 牟晓生 供题)"- }- ],- "page_info": {- "page_no": 0,- "height": 2339,- "width": 1654- }- }-]\ No newline at end of filediff --git a/tests/test_cli/pdf_dev/pdf/academic_literature_0b2c9c91f5232541a7ace8984df306b2.pdf b/tests/test_cli/pdf_dev/pdf/academic_literature_0b2c9c91f5232541a7ace8984df306b2.pdfdeleted file mode 100644index e7a72b99..00000000Binary files a/tests/test_cli/pdf_dev/pdf/academic_literature_0b2c9c91f5232541a7ace8984df306b2.pdf and /dev/null differdiff --git a/tests/test_cli/pdf_dev/pdf/academic_literature_f7904bc37cc2e25c1e3e412978854b10.pdf b/tests/test_cli/pdf_dev/pdf/academic_literature_f7904bc37cc2e25c1e3e412978854b10.pdfdeleted file mode 100644index 37a2caea..00000000Binary files a/tests/test_cli/pdf_dev/pdf/academic_literature_f7904bc37cc2e25c1e3e412978854b10.pdf and /dev/null differdiff --git a/tests/test_cli/pdf_dev/pdf/academic_literature_fbdb99151e811688574c0c4c67341074.pdf b/tests/test_cli/pdf_dev/pdf/academic_literature_fbdb99151e811688574c0c4c67341074.pdfdeleted file mode 100644index d21604a8..00000000Binary files a/tests/test_cli/pdf_dev/pdf/academic_literature_fbdb99151e811688574c0c4c67341074.pdf and /dev/null differdiff --git a/tests/test_cli/pdf_dev/pdf/ordinary_textbook_1d9a847603a5e37e379738316820850d.pdf b/tests/test_cli/pdf_dev/pdf/ordinary_textbook_1d9a847603a5e37e379738316820850d.pdfdeleted file mode 100644index a93f8c36..00000000Binary files a/tests/test_cli/pdf_dev/pdf/ordinary_textbook_1d9a847603a5e37e379738316820850d.pdf and /dev/null differdiff --git a/tests/test_cli/pdf_dev/research_report_1f978cd81fb7260c8f7644039ec2c054_model.json b/tests/test_cli/pdf_dev/research_report_1f978cd81fb7260c8f7644039ec2c054_model.jsondeleted file mode 100644index f80aba12..00000000--- a/tests/test_cli/pdf_dev/research_report_1f978cd81fb7260c8f7644039ec2c054_model.json+++ /dev/null@@ -1,1472 +0,0 @@-[- {- "layout_dets": [- {- "category_id": 1,- "poly": [- 578.199951171875,- 672.8836669921875,- 1579.9771728515625,- 672.8836669921875,- 1579.9771728515625,- 1034.6820068359375,- 578.199951171875,- 1034.6820068359375- ],- "score": 0.9999963641166687- },- {- "category_id": 1,- "poly": [- 583.6012573242188,- 1067.112548828125,- 1579.8231201171875,- 1067.112548828125,- 1579.8231201171875,- 1537.1314697265625,- 583.6012573242188,- 1537.1314697265625- ],- "score": 0.9999961853027344- },- {- "category_id": 1,- "poly": [- 585.4329223632812,- 1568.2215576171875,- 1578.5496826171875,- 1568.2215576171875,- 1578.5496826171875,- 1931.5169677734375,- 585.4329223632812,- 1931.5169677734375- ],- "score": 0.9999949336051941- },- {- "category_id": 1,- "poly": [- 578.48388671875,- 532.0015869140625,- 1577.96337890625,- 532.0015869140625,- 1577.96337890625,- 641.0133056640625,- 578.48388671875,- 641.0133056640625- ],- "score": 0.999992847442627- },- {- "category_id": 1,- "poly": [- 66.4359359741211,- 1776.6947021484375,- 530.4816284179688,- 1776.6947021484375,- 530.4816284179688,- 1883.12841796875,- 66.4359359741211,- 1883.12841796875- ],- "score": 0.9999925494194031- },- {- "category_id": 3,- "poly": [- 70.23741149902344,- 818.9378662109375,- 517.8241577148438,- 818.9378662109375,- 517.8241577148438,- 1076.58251953125,- 70.23741149902344,- 1076.58251953125- ],- "score": 0.9999912977218628- },- {- "category_id": 1,- "poly": [- 64.99989318847656,- 651.9586791992188,- 436.51446533203125,- 651.9586791992188,- 436.51446533203125,- 723.5755615234375,- 64.99989318847656,- 723.5755615234375- ],- "score": 0.9999803900718689- },- {- "category_id": 0,- "poly": [- 556.2784423828125,- 270.2118835449219,- 1577.8243408203125,- 270.2118835449219,- 1577.8243408203125,- 408.96875,- 556.2784423828125,- 408.96875- ],- "score": 0.9999694228172302- },- {- "category_id": 1,- "poly": [- 67.8554458618164,- 1342.222900390625,- 530.5653686523438,- 1342.222900390625,- 530.5653686523438,- 1447.843017578125,- 67.8554458618164,- 1447.843017578125- ],- "score": 0.999964714050293- },- {- "category_id": 1,- "poly": [- 65.74972534179688,- 1631.3668212890625,- 530.32763671875,- 1631.3668212890625,- 530.32763671875,- 1772.4139404296875,- 65.74972534179688,- 1772.4139404296875- ],- "score": 0.9999628067016602- },- {- "category_id": 1,- "poly": [- 588.5555419921875,- 2068.548828125,- 1525.326416015625,- 2068.548828125,- 1525.326416015625,- 2103.8896484375,- 588.5555419921875,- 2103.8896484375- ],- "score": 0.9999607801437378- },- {- "category_id": 1,- "poly": [- 586.5614013671875,- 1963.109619140625,- 1556.57763671875,- 1963.109619140625,- 1556.57763671875,- 2034.810302734375,- 586.5614013671875,- 2034.810302734375- ],- "score": 0.9999467730522156- },- {- "category_id": 5,- "poly": [- 59.963104248046875,- 1110.6282958984375,- 529.9212646484375,- 1110.6282958984375,- 529.9212646484375,- 1225.2918701171875,- 59.963104248046875,- 1225.2918701171875- ],- "score": 0.9999458193778992- },- {- "category_id": 2,- "poly": [- 70.253173828125,- 103.42188262939453,- 420.4876708984375,- 103.42188262939453,- 420.4876708984375,- 223.3950653076172,- 70.253173828125,- 223.3950653076172- ],- "score": 0.9999403953552246- },- {- "category_id": 2,- "poly": [- 1081.0198974609375,- 2244.876220703125,- 1554.6702880859375,- 2244.876220703125,- 1554.6702880859375,- 2275.28662109375,- 1081.0198974609375,- 2275.28662109375- ],- "score": 0.9999216794967651- },- {- "category_id": 1,- "poly": [- 68.85406494140625,- 345.90887451171875,- 307.9100646972656,- 345.90887451171875,- 307.9100646972656,- 409.0101013183594,- 68.85406494140625,- 409.0101013183594- ],- "score": 0.9999182224273682- },- {- "category_id": 0,- "poly": [- 65.58615112304688,- 1295.93701171875,- 180.41529846191406,- 1295.93701171875,- 180.41529846191406,- 1328.8675537109375,- 65.58615112304688,- 1328.8675537109375- ],- "score": 0.9998924136161804- },- {- "category_id": 2,- "poly": [- 1245.0789794921875,- 108.83450317382812,- 1576.3145751953125,- 108.83450317382812,- 1576.3145751953125,- 219.29098510742188,- 1245.0789794921875,- 219.29098510742188- ],- "score": 0.9995979070663452- },- {- "category_id": 1,- "poly": [- 65.7517318725586,- 483.5211181640625,- 428.60296630859375,- 483.5211181640625,- 428.60296630859375,- 586.8902587890625,- 65.7517318725586,- 586.8902587890625- ],- "score": 0.9993292689323425- },- {- "category_id": 0,- "poly": [- 65.02902221679688,- 445.0223083496094,- 208.32994079589844,- 445.0223083496094,- 208.32994079589844,- 476.65191650390625,- 65.02902221679688,- 476.65191650390625- ],- "score": 0.9992275238037109- },- {- "category_id": 0,- "poly": [- 556.9666748046875,- 453.0841369628906,- 673.0485229492188,- 453.0841369628906,- 673.0485229492188,- 490.6045227050781,- 556.9666748046875,- 490.6045227050781- ],- "score": 0.9949869513511658- },- {- "category_id": 1,- "poly": [- 66.26496124267578,- 1524.239013671875,- 530.25537109375,- 1524.239013671875,- 530.25537109375,- 1627.5289306640625,- 66.26496124267578,- 1627.5289306640625- ],- "score": 0.9919456839561462- },- {- "category_id": 7,- "poly": [- 62.55642318725586,- 1227.4195556640625,- 380.1070556640625,- 1227.4195556640625,- 380.1070556640625,- 1252.86181640625,- 62.55642318725586,- 1252.86181640625- ],- "score": 0.9918301105499268- },- {- "category_id": 1,- "poly": [- 66.80264282226562,- 1451.476806640625,- 527.379150390625,- 1451.476806640625,- 527.379150390625,- 1519.5836181640625,- 66.80264282226562,- 1519.5836181640625- ],- "score": 0.9883919954299927- },- {- "category_id": 0,- "poly": [- 65.35992431640625,- 605.3745727539062,- 181.2437286376953,- 605.3745727539062,- 181.2437286376953,- 637.0079956054688,- 65.35992431640625,- 637.0079956054688- ],- "score": 0.9870822429656982- },- {- "category_id": 0,- "poly": [- 178.8284149169922,- 264.662109375,- 396.5289611816406,- 264.662109375,- 396.5289611816406,- 315.4195251464844,- 178.8284149169922,- 315.4195251464844- ],- "score": 0.9779264330863953- },- {- "category_id": 4,- "poly": [- 66.15017700195312,- 767.2459106445312,- 181.25796508789062,- 767.2459106445312,- 181.25796508789062,- 799.7833251953125,- 66.15017700195312,- 799.7833251953125- ],- "score": 0.8933500051498413- },- {- "category_id": 13,- "poly": [- 590,- 747,- 688,- 747,- 688,- 778,- 590,- 778- ],- "score": 0.91,- "latex": "+24.4\\%"- },- {- "category_id": 13,- "poly": [- 1433,- 855,- 1492,- 855,- 1492,- 886,- 1433,- 886- ],- "score": 0.86,- "latex": "30\\%"- },- {- "category_id": 13,- "poly": [- 238,- 689,- 264,- 689,- 264,- 717,- 238,- 717- ],- "score": 0.34,- "latex": "@"- },- {- "category_id": 13,- "poly": [- 702,- 1002,- 722,- 1002,- 722,- 1026,- 702,- 1026- ],- "score": 0.33,- "latex": "^+"- },- {- "category_id": 13,- "poly": [- 177,- 1154,- 223,- 1154,- 223,- 1185,- 177,- 1185- ],- "score": 0.28,- "latex": "(\\%)"- }- ],- "page_info": {- "page_no": 0,- "height": 2339,- "width": 1654- }- },- {- "layout_dets": [- {- "category_id": 2,- "poly": [- 88.00835418701172,- 31.891786575317383,- 300.7422180175781,- 31.891786575317383,- 300.7422180175781,- 113.60026550292969,- 88.00835418701172,- 113.60026550292969- ],- "score": 0.9999986886978149- },- {- "category_id": 2,- "poly": [- 771.0192260742188,- 2213.478759765625,- 827.4277954101562,- 2213.478759765625,- 827.4277954101562,- 2239.4013671875,- 771.0192260742188,- 2239.4013671875- ],- "score": 0.9999961853027344- },- {- "category_id": 7,- "poly": [- 544.297119140625,- 488.5483703613281,- 988.39990234375,- 488.5483703613281,- 988.39990234375,- 541.063232421875,- 544.297119140625,- 541.063232421875- ],- "score": 0.9999918341636658- },- {- "category_id": 2,- "poly": [- 1082.88330078125,- 82.37212371826172,- 1519.426513671875,- 82.37212371826172,- 1519.426513671875,- 114.92091369628906,- 1082.88330078125,- 114.92091369628906- ],- "score": 0.9999634623527527- },- {- "category_id": 2,- "poly": [- 1009.1594848632812,- 2210.946533203125,- 1535.924560546875,- 2210.946533203125,- 1535.924560546875,- 2241.8310546875,- 1009.1594848632812,- 2241.8310546875- ],- "score": 0.9999324679374695- },- {- "category_id": 5,- "poly": [- 537.3482666015625,- 156.8837432861328,- 1584.9873046875,- 156.8837432861328,- 1584.9873046875,- 485.2989501953125,- 537.3482666015625,- 485.2989501953125- ],- "score": 0.9985944628715515- },- {- "category_id": 7,- "poly": [- 62.69691848754883,- 443.4039611816406,- 249.91006469726562,- 443.4039611816406,- 249.91006469726562,- 467.46136474609375,- 62.69691848754883,- 467.46136474609375- ],- "score": 0.9873790740966797- },- {- "category_id": 5,- "poly": [- 61.37367248535156,- 138.51014709472656,- 528.3062744140625,- 138.51014709472656,- 528.3062744140625,- 443.5386962890625,- 61.37367248535156,- 443.5386962890625- ],- "score": 0.9232067465782166- },- {- "category_id": 6,- "poly": [- 548.1131591796875,- 148.73146057128906,- 797.3046875,- 148.73146057128906,- 797.3046875,- 180.74632263183594,- 548.1131591796875,- 180.74632263183594- ],- "score": 0.6074692606925964- },- {- "category_id": 13,- "poly": [- 864,- 455,- 922,- 455,- 922,- 482,- 864,- 482- ],- "score": 0.74,- "latex": "6.0\\%"- },- {- "category_id": 13,- "poly": [- 850,- 418,- 922,- 418,- 922,- 445,- 850,- 445- ],- "score": 0.64,- "latex": "35.3\\%"- },- {- "category_id": 13,- "poly": [- 1501,- 270,- 1571,- 270,- 1571,- 298,- 1501,- 298- ],- "score": 0.54,- "latex": "13.8\\%"- },- {- "category_id": 13,- "poly": [- 1013,- 454,- 1083,- 454,- 1083,- 482,- 1013,- 482- ],- "score": 0.52,- "latex": "15.0\\%"- },- {- "category_id": 13,- "poly": [- 1012,- 417,- 1083,- 417,- 1083,- 444,- 1012,- 444- ],- "score": 0.52,- "latex": "33.7\\%"- },- {- "category_id": 13,- "poly": [- 689,- 456,- 725,- 456,- 725,- 482,- 689,- 482- ],- "score": 0.48,- "latex": "(\\%)"- },- {- "category_id": 13,- "poly": [- 850,- 344,- 922,- 344,- 922,- 372,- 850,- 372- ],- "score": 0.4,- "latex": "83.8\\%"- },- {- "category_id": 13,- "poly": [- 863,- 270,- 922,- 270,- 922,- 298,- 863,- 298- ],- "score": 0.4,- "latex": "4.5\\%"- },- {- "category_id": 13,- "poly": [- 1334,- 270,- 1406,- 270,- 1406,- 298,- 1334,- 298- ],- "score": 0.35,- "latex": "37.2\\%"- },- {- "category_id": 13,- "poly": [- 618,- 419,- 656,- 419,- 656,- 446,- 618,- 446- ],- "score": 0.35,- "latex": "(\\%)"- }- ],- "page_info": {- "page_no": 1,- "height": 2339,- "width": 1654- }- },- {- "layout_dets": [- {- "category_id": 2,- "poly": [- 87.90370178222656,- 31.597869873046875,- 300.9918518066406,- 31.597869873046875,- 300.9918518066406,- 113.40574645996094,- 87.90370178222656,- 113.40574645996094- ],- "score": 0.9999939799308777- },- {- "category_id": 2,- "poly": [- 1008.9932250976562,- 2209.250732421875,- 1534.93310546875,- 2209.250732421875,- 1534.93310546875,- 2242.773193359375,- 1008.9932250976562,- 2242.773193359375- ],- "score": 0.9999377727508545- },- {- "category_id": 2,- "poly": [- 770.6605224609375,- 2212.857666015625,- 827.4124145507812,- 2212.857666015625,- 827.4124145507812,- 2239.771484375,- 770.6605224609375,- 2239.771484375- ],- "score": 0.9998394250869751- },- {- "category_id": 2,- "poly": [- 1082.0982666015625,- 82.25032043457031,- 1518.9271240234375,- 82.25032043457031,- 1518.9271240234375,- 114.52558898925781,- 1082.0982666015625,- 114.52558898925781- ],- "score": 0.9996459484100342- },- {- "category_id": 7,- "poly": [- 95.3975601196289,- 1846.637939453125,- 564.4164428710938,- 1846.637939453125,- 564.4164428710938,- 1899.2098388671875,- 95.3975601196289,- 1899.2098388671875- ],- "score": 0.9908689260482788- },- {- "category_id": 6,- "poly": [- 95.46688842773438,- 173.42837524414062,- 470.2196960449219,- 173.42837524414062,- 470.2196960449219,- 217.74642944335938,- 95.46688842773438,- 217.74642944335938- ],- "score": 0.9438199400901794- },- {- "category_id": 5,- "poly": [- 854.114501953125,- 1043.93505859375,- 1592.0174560546875,- 1043.93505859375,- 1592.0174560546875,- 1846.166015625,- 854.114501953125,- 1846.166015625- ],- "score": 0.884392499923706- },- {- "category_id": 5,- "poly": [- 92.02899169921875,- 1331.891845703125,- 814.2921752929688,- 1331.891845703125,- 814.2921752929688,- 1842.61962890625,- 92.02899169921875,- 1842.61962890625- ],- "score": 0.8743516206741333- },- {- "category_id": 5,- "poly": [- 851.83984375,- 224.9954833984375,- 1592.4066162109375,- 224.9954833984375,- 1592.4066162109375,- 1018.7108154296875,- 851.83984375,- 1018.7108154296875- ],- "score": 0.8650234937667847- },- {- "category_id": 5,- "poly": [- 91.79834747314453,- 224.1070556640625,- 816.58203125,- 224.1070556640625,- 816.58203125,- 1248.4244384765625,- 91.79834747314453,- 1248.4244384765625- ],- "score": 0.8604705333709717- },- {- "category_id": 5,- "poly": [- 85.1959228515625,- 220.71908569335938,- 1602.307373046875,- 220.71908569335938,- 1602.307373046875,- 1844.490234375,- 85.1959228515625,- 1844.490234375- ],- "score": 0.6637970209121704- },- {- "category_id": 13,- "poly": [- 737,- 704,- 804,- 704,- 804,- 730,- 737,- 730- ],- "score": 0.56,- "latex": "\\pmb{26.5\\%}"- },- {- "category_id": 13,- "poly": [- 738,- 673,- 804,- 673,- 804,- 699,- 738,- 699- ],- "score": 0.48,- "latex": "\\pmb{16.2\\%}"- },- {- "category_id": 13,- "poly": [- 736,- 767,- 805,- 767,- 805,- 795,- 736,- 795- ],- "score": 0.48,- "latex": "\\mathbf{\\lambda_{23.7\\%}}"- },- {- "category_id": 13,- "poly": [- 231,- 611,- 268,- 611,- 268,- 638,- 231,- 638- ],- "score": 0.47,- "latex": "(\\%)"- },- {- "category_id": 13,- "poly": [- 749,- 736,- 804,- 736,- 804,- 763,- 749,- 763- ],- "score": 0.41,- "latex": "\\pmb{9.2\\%}"- },- {- "category_id": 13,- "poly": [- 737,- 641,- 804,- 641,- 804,- 668,- 737,- 668- ],- "score": 0.41,- "latex": "{\\bf38.0\\%}"- },- {- "category_id": 13,- "poly": [- 748,- 577,- 805,- 577,- 805,- 606,- 748,- 606- ],- "score": 0.35,- "latex": "0.1\\%"- },- {- "category_id": 13,- "poly": [- 187,- 800,- 222,- 800,- 222,- 827,- 187,- 827- ],- "score": 0.32,- "latex": "(\\%)"- },- {- "category_id": 13,- "poly": [- 738,- 830,- 805,- 830,- 805,- 857,- 738,- 857- ],- "score": 0.28,- "latex": "\\mathbf{13.8\\%}"- },- {- "category_id": 13,- "poly": [- 737,- 862,- 805,- 862,- 805,- 889,- 737,- 889- ],- "score": 0.27,- "latex": "\\mathbf{31.9\\%}"- },- {- "category_id": 13,- "poly": [- 736,- 955,- 804,- 955,- 804,- 983,- 736,- 983- ],- "score": 0.26,- "latex": "\\pmb{65.3\\%}"- }- ],- "page_info": {- "page_no": 2,- "height": 2339,- "width": 1654- }- },- {- "layout_dets": [- {- "category_id": 2,- "poly": [- 86.30094909667969,- 32.05949783325195,- 303.6516418457031,- 32.05949783325195,- 303.6516418457031,- 114.77470397949219,- 86.30094909667969,- 114.77470397949219- ],- "score": 0.9999954104423523- },- {- "category_id": 1,- "poly": [- 108.4946060180664,- 590.2034912109375,- 1536.75146484375,- 590.2034912109375,- 1536.75146484375,- 688.491455078125,- 108.4946060180664,- 688.491455078125- ],- "score": 0.9999933242797852- },- {- "category_id": 0,- "poly": [- 95.94879913330078,- 1205.413818359375,- 252.92385864257812,- 1205.413818359375,- 252.92385864257812,- 1246.00146484375,- 95.94879913330078,- 1246.00146484375- ],- "score": 0.9999929666519165- },- {- "category_id": 1,- "poly": [- 106.48407745361328,- 338.2734680175781,- 1568.8638916015625,- 338.2734680175781,- 1568.8638916015625,- 437.8475341796875,- 106.48407745361328,- 437.8475341796875- ],- "score": 0.9999896883964539- },- {- "category_id": 2,- "poly": [- 767.6920776367188,- 2212.26904296875,- 830.787353515625,- 2212.26904296875,- 830.787353515625,- 2239.28466796875,- 767.6920776367188,- 2239.28466796875- ],- "score": 0.9999850988388062- },- {- "category_id": 0,- "poly": [- 96.18524932861328,- 508.3636474609375,- 291.44244384765625,- 508.3636474609375,- 291.44244384765625,- 549.4661254882812,- 96.18524932861328,- 549.4661254882812- ],- "score": 0.9999837875366211- },- {- "category_id": 2,- "poly": [- 1082.2711181640625,- 81.18756103515625,- 1520.2156982421875,- 81.18756103515625,- 1520.2156982421875,- 116.55754089355469,- 1082.2711181640625,- 116.55754089355469- ],- "score": 0.99994957447052- },- {- "category_id": 0,- "poly": [- 96.45137786865234,- 157.9286346435547,- 319.2138671875,- 157.9286346435547,- 319.2138671875,- 213.84323120117188,- 96.45137786865234,- 213.84323120117188- ],- "score": 0.9999274611473083- },- {- "category_id": 0,- "poly": [- 96.99203491210938,- 257.65087890625,- 483.64617919921875,- 257.65087890625,- 483.64617919921875,- 301.5384216308594,- 96.99203491210938,- 301.5384216308594- ],- "score": 0.999910295009613- },- {- "category_id": 2,- "poly": [- 1008.87890625,- 2208.611328125,- 1536.04736328125,- 2208.611328125,- 1536.04736328125,- 2243.415283203125,- 1008.87890625,- 2243.415283203125- ],- "score": 0.999893069267273- },- {- "category_id": 1,- "poly": [- 108.4665298461914,- 1288.0936279296875,- 1546.7523193359375,- 1288.0936279296875,- 1546.7523193359375,- 1383.8436279296875,- 108.4665298461914,- 1383.8436279296875- ],- "score": 0.9997895956039429- },- {- "category_id": 1,- "poly": [- 107.81368255615234,- 1678.247802734375,- 1227.883056640625,- 1678.247802734375,- 1227.883056640625,- 1711.3719482421875,- 107.81368255615234,- 1711.3719482421875- ],- "score": 0.999572217464447- },- {- "category_id": 5,- "poly": [- 109.7546157836914,- 810.016357421875,- 1579.9564208984375,- 810.016357421875,- 1579.9564208984375,- 1171.63818359375,- 109.7546157836914,- 1171.63818359375- ],- "score": 0.999454140663147- },- {- "category_id": 1,- "poly": [- 106.4626235961914,- 1548.298828125,- 1540.339111328125,- 1548.298828125,- 1540.339111328125,- 1676.6796875,- 106.4626235961914,- 1676.6796875- ],- "score": 0.9886388778686523- },- {- "category_id": 1,- "poly": [- 107.5276107788086,- 1386.3994140625,- 1540.8876953125,- 1386.3994140625,- 1540.8876953125,- 1447.81298828125,- 107.5276107788086,- 1447.81298828125- ],- "score": 0.9709202647209167- },- {- "category_id": 1,- "poly": [- 107.66427612304688,- 1451.8365478515625,- 1537.991943359375,- 1451.8365478515625,- 1537.991943359375,- 1546.6905517578125,- 107.66427612304688,- 1546.6905517578125- ],- "score": 0.9589993953704834- },- {- "category_id": 6,- "poly": [- 95.90386199951172,- 728.28564453125,- 328.19708251953125,- 728.28564453125,- 328.19708251953125,- 768.121826171875,- 95.90386199951172,- 768.121826171875- ],- "score": 0.6999472379684448- },- {- "category_id": 1,- "poly": [- 106.67626953125,- 1371.860595703125,- 1544.8497314453125,- 1371.860595703125,- 1544.8497314453125,- 1678.673095703125,- 106.67626953125,- 1678.673095703125- ],- "score": 0.5646986961364746- },- {- "category_id": 0,- "poly": [- 95.94149780273438,- 728.2644653320312,- 328.195068359375,- 728.2644653320312,- 328.195068359375,- 768.1664428710938,- 95.94149780273438,- 768.1664428710938- ],- "score": 0.30706164240837097- },- {- "category_id": 13,- "poly": [- 1247,- 887,- 1353,- 887,- 1353,- 914,- 1247,- 914- ],- "score": 0.91,- "latex": "5\\%{\\sim}20\\%"- },- {- "category_id": 13,- "poly": [- 1181,- 923,- 1290,- 923,- 1290,- 950,- 1181,- 950- ],- "score": 0.9,- "latex": "-5\\%{+}5\\%"- },- {- "category_id": 13,- "poly": [- 1416,- 1047,- 1469,- 1047,- 1469,- 1077,- 1416,- 1077- ],- "score": 0.87,- "latex": "10\\%"- },- {- "category_id": 13,- "poly": [- 1254,- 963,- 1296,- 963,- 1296,- 991,- 1254,- 991- ],- "score": 0.86,- "latex": "5\\%"- },- {- "category_id": 13,- "poly": [- 1373,- 1003,- 1428,- 1003,- 1428,- 1032,- 1373,- 1032- ],- "score": 0.86,- "latex": "10\\%"- },- {- "category_id": 13,- "poly": [- 1332,- 1047,- 1388,- 1047,- 1388,- 1076,- 1332,- 1076- ],- "score": 0.86,- "latex": "\\cdot10\\%"- },- {- "category_id": 13,- "poly": [- 1373,- 1112,- 1428,- 1112,- 1428,- 1141,- 1373,- 1141- ],- "score": 0.85,- "latex": "10\\%"- },- {- "category_id": 13,- "poly": [- 1248,- 854,- 1302,- 854,- 1302,- 880,- 1248,- 880- ],- "score": 0.85,- "latex": "z0\\%"- }- ],- "page_info": {- "page_no": 3,- "height": 2339,- "width": 1654- }- }-]\ No newline at end of filediff --git a/tests/test_cli/test_bench.py b/tests/test_cli/test_bench.pyindex fb6cb00f..23e7bdfd 100644--- a/tests/test_cli/test_bench.py+++ b/tests/test_cli/test_bench.py@@ -37,9 +37,9 @@ class TestBench():now_simscore = now_score["average_sim_score"]now_editdistance = now_score["average_edit_distance"]now_bleu = now_score["average_bleu_score"]- #assert last_simscore <= now_simscore- #assert last_editdistance <= now_editdistance- #assert last_bleu <= now_bleu+ assert last_simscore <= now_simscore+ assert last_editdistance <= now_editdistance+ assert last_bleu <= now_bleudef get_score():diff --git a/tests/test_cli/test_cli.py b/tests/test_cli/test_cli.pydeleted file mode 100644index ebf78bbb..00000000--- a/tests/test_cli/test_cli.py+++ /dev/null@@ -1,75 +0,0 @@-import pytest-import os-from conf import conf-import os-import json-from magic_pdf.pipe.UNIPipe import UNIPipe-from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter-from lib import common--pdf_res_path = conf.conf["pdf_res_path"]-code_path = conf.conf["code_path"]-pdf_dev_path = conf.conf["pdf_dev_path"]-class TestCli:- """- test cli- """- def test_pdf_sdk(self):- """- pdf sdk 方式解析- """- demo_names = list()- pdf_path = os.path.join(pdf_dev_path, "pdf")- for pdf_file in os.listdir(pdf_path):- if pdf_file.endswith('.pdf'):- demo_names.append(pdf_file.split('.')[0])- for demo_name in demo_names:- model_path = os.path.join(pdf_dev_path, f"{demo_name}_model.json")- pdf_path = os.path.join(pdf_dev_path, "pdf", f"{demo_name}.pdf")- pdf_bytes = open(pdf_path, "rb").read()- model_json = json.loads(open(model_path, "r", encoding="utf-8").read())- image_writer = DiskReaderWriter(pdf_dev_path)- image_dir = str(os.path.basename(pdf_dev_path))- jso_useful_key = {"_pdf_type": "", "model_list": model_json}- pipe = UNIPipe(pdf_bytes, jso_useful_key, image_writer)- pipe.pipe_classify()- pipe.pipe_parse()- md_content = pipe.pipe_mk_markdown(image_dir, drop_mode="none")- dir_path = os.path.join(pdf_dev_path, "mineru")- if not os.path.exists(dir_path):- os.makedirs(dir_path, exist_ok=True)- res_path = os.path.join(dir_path, f"{demo_name}.md")- with open(res_path, "w+", encoding="utf-8") as f:- f.write(md_content)- common.count_folders_and_check_contents(res_path)-- # def test_pdf_specify_jsonl(self):- # """- # 输入jsonl, 默认方式解析- # """- # cmd = "cd %s && export PYTHONPATH=. && python magic_pdf/cli/magicpdf.py json-command --json 's3://llm-process-pperf/ebook_index_textbook_40k/中高考&竞赛知识点/part-663f1ef5e7c1-009416.jsonl?bytes=0,1133972'" % (code_path)- # logging.info(cmd)- # common.check_shell(cmd)- # #common.count_folders_and_check_contents(pdf_res_path)-- # def test_pdf_specify_jsonl_txt(self):- # """- # 输入jsonl, txt方式解析- # """- # cmd = "cd %s && export PYTHONPATH=. && python magic_pdf/cli/magicpdf.py json-command --json 's3://llm-process-pperf/ebook_index_textbook_40k/中高考&竞赛知识点/part-663f1ef5e7c1-009416.jsonl?bytes=0,1133972' --method txt" % (code_path)- # logging.info(cmd)- # common.check_shell(cmd)- # #common.count_folders_and_check_contents(pdf_res_path)- #- # def test_pdf_specify_jsonl_ocr(self):- # """- # 输入jsonl, ocr方式解析- # """- # cmd = "cd %s && export PYTHONPATH=. && python magic_pdf/cli/magicpdf.py json-command --json 's3://llm-process-pperf/ebook_index_textbook_40k/中高考&竞赛知识点/part-663f1ef5e7c1-009416.jsonl?bytes=0,1133972' --method ocr" % (code_path)- # logging.info(cmd)- # common.check_shell(cmd)- # #common.count_folders_and_check_contents(pdf_res_path)---if __name__ == "__main__":- pytest.main()diff --git a/tests/test_cli/test_cli_sdk.py b/tests/test_cli/test_cli_sdk.pynew file mode 100644index 00000000..3b0b1eb7--- /dev/null+++ b/tests/test_cli/test_cli_sdk.py@@ -0,0 +1,183 @@+"""test cli and sdk."""+import logging+import os++import pytest+from conf import conf+from lib import common++import magic_pdf.model as model_config+from magic_pdf.pipe.UNIPipe import UNIPipe+from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter++model_config.__use_inside_model__ = True+pdf_res_path = conf.conf['pdf_res_path']+code_path = conf.conf['code_path']+pdf_dev_path = conf.conf['pdf_dev_path']+++class TestCli:+ """test cli."""++ @pytest.mark.P0+ def test_pdf_auto_sdk(self):+ """pdf sdk auto test."""+ demo_names = list()+ pdf_path = os.path.join(pdf_dev_path, 'pdf')+ for pdf_file in os.listdir(pdf_path):+ if pdf_file.endswith('.pdf'):+ demo_names.append(pdf_file.split('.')[0])+ for demo_name in demo_names:+ pdf_path = os.path.join(pdf_dev_path, 'pdf', f'{demo_name}.pdf')+ print(pdf_path)+ pdf_bytes = open(pdf_path, 'rb').read()+ local_image_dir = os.path.join(pdf_dev_path, 'pdf', 'images')+ image_dir = str(os.path.basename(local_image_dir))+ image_writer = DiskReaderWriter(local_image_dir)+ model_json = list()+ jso_useful_key = {'_pdf_type': '', 'model_list': model_json}+ pipe = UNIPipe(pdf_bytes, jso_useful_key, image_writer)+ pipe.pipe_classify()+ if len(model_json) == 0:+ if model_config.__use_inside_model__:+ pipe.pipe_analyze()+ else:+ exit(1)+ pipe.pipe_parse()+ md_content = pipe.pipe_mk_markdown(image_dir, drop_mode='none')+ dir_path = os.path.join(pdf_dev_path, 'mineru')+ if not os.path.exists(dir_path):+ os.makedirs(dir_path, exist_ok=True)+ res_path = os.path.join(dir_path, f'{demo_name}.md')+ common.delete_file(res_path)+ with open(res_path, 'w+', encoding='utf-8') as f:+ f.write(md_content)+ common.sdk_count_folders_and_check_contents(res_path)++ @pytest.mark.P0+ def test_pdf_ocr_sdk(self):+ """pdf sdk ocr test."""+ demo_names = list()+ pdf_path = os.path.join(pdf_dev_path, 'pdf')+ for pdf_file in os.listdir(pdf_path):+ if pdf_file.endswith('.pdf'):+ demo_names.append(pdf_file.split('.')[0])+ for demo_name in demo_names:+ pdf_path = os.path.join(pdf_dev_path, 'pdf', f'{demo_name}.pdf')+ print(pdf_path)+ pdf_bytes = open(pdf_path, 'rb').read()+ local_image_dir = os.path.join(pdf_dev_path, 'pdf', 'images')+ image_dir = str(os.path.basename(local_image_dir))+ image_writer = DiskReaderWriter(local_image_dir)+ model_json = list()+ jso_useful_key = {'_pdf_type': 'ocr', 'model_list': model_json}+ pipe = UNIPipe(pdf_bytes, jso_useful_key, image_writer)+ pipe.pipe_classify()+ if len(model_json) == 0:+ if model_config.__use_inside_model__:+ pipe.pipe_analyze()+ else:+ exit(1)+ pipe.pipe_parse()+ md_content = pipe.pipe_mk_markdown(image_dir, drop_mode='none')+ dir_path = os.path.join(pdf_dev_path, 'mineru')+ if not os.path.exists(dir_path):+ os.makedirs(dir_path, exist_ok=True)+ res_path = os.path.join(dir_path, f'{demo_name}.md')+ common.delete_file(res_path)+ with open(res_path, 'w+', encoding='utf-8') as f:+ f.write(md_content)+ common.sdk_count_folders_and_check_contents(res_path)++ @pytest.mark.P0+ def test_pdf_txt_sdk(self):+ """pdf sdk txt test."""+ demo_names = list()+ pdf_path = os.path.join(pdf_dev_path, 'pdf')+ for pdf_file in os.listdir(pdf_path):+ if pdf_file.endswith('.pdf'):+ demo_names.append(pdf_file.split('.')[0])+ for demo_name in demo_names:+ pdf_path = os.path.join(pdf_dev_path, 'pdf', f'{demo_name}.pdf')+ print(pdf_path)+ pdf_bytes = open(pdf_path, 'rb').read()+ local_image_dir = os.path.join(pdf_dev_path, 'pdf', 'images')+ image_dir = str(os.path.basename(local_image_dir))+ image_writer = DiskReaderWriter(local_image_dir)+ model_json = list()+ jso_useful_key = {'_pdf_type': 'txt', 'model_list': model_json}+ pipe = UNIPipe(pdf_bytes, jso_useful_key, image_writer)+ pipe.pipe_classify()+ if len(model_json) == 0:+ if model_config.__use_inside_model__:+ pipe.pipe_analyze()+ else:+ exit(1)+ pipe.pipe_parse()+ md_content = pipe.pipe_mk_markdown(image_dir, drop_mode='none')+ dir_path = os.path.join(pdf_dev_path, 'mineru')+ if not os.path.exists(dir_path):+ os.makedirs(dir_path, exist_ok=True)+ res_path = os.path.join(dir_path, f'{demo_name}.md')+ common.delete_file(res_path)+ with open(res_path, 'w+', encoding='utf-8') as f:+ f.write(md_content)+ common.sdk_count_folders_and_check_contents(res_path)++ @pytest.mark.P0+ def test_pdf_cli_auto(self):+ """magic_pdf cli test auto."""+ demo_names = []+ pdf_path = os.path.join(pdf_dev_path, 'pdf')+ for pdf_file in os.listdir(pdf_path):+ if pdf_file.endswith('.pdf'):+ demo_names.append(pdf_file.split('.')[0])+ for demo_name in demo_names:+ res_path = os.path.join(pdf_dev_path, 'mineru')+ common.delete_file(res_path)+ cmd = 'magic-pdf -p %s -o %s -m %s' % (os.path.join(+ pdf_path, f'{demo_name}.pdf'), res_path, 'auto')+ logging.info(cmd)+ os.system(cmd)+ common.cli_count_folders_and_check_contents(+ os.path.join(res_path, demo_name, 'auto'))++ @pytest.mark.P0+ def test_pdf_clit_txt(self):+ """magic_pdf cli test txt."""+ demo_names = []+ pdf_path = os.path.join(pdf_dev_path, 'pdf')+ for pdf_file in os.listdir(pdf_path):+ if pdf_file.endswith('.pdf'):+ demo_names.append(pdf_file.split('.')[0])+ for demo_name in demo_names:+ res_path = os.path.join(pdf_dev_path, 'mineru')+ common.delete_file(res_path)+ cmd = 'magic-pdf -p %s -o %s -m %s' % (os.path.join(+ pdf_path, f'{demo_name}.pdf'), res_path, 'txt')+ logging.info(cmd)+ os.system(cmd)+ common.cli_count_folders_and_check_contents(+ os.path.join(res_path, demo_name, 'txt'))++ @pytest.mark.P0+ def test_pdf_clit_ocr(self):+ """magic_pdf cli test ocr."""+ demo_names = []+ pdf_path = os.path.join(pdf_dev_path, 'pdf')+ for pdf_file in os.listdir(pdf_path):+ if pdf_file.endswith('.pdf'):+ demo_names.append(pdf_file.split('.')[0])+ for demo_name in demo_names:+ res_path = os.path.join(pdf_dev_path, 'mineru')+ common.delete_file(res_path)+ cmd = 'magic-pdf -p %s -o %s -m %s' % (os.path.join(+ pdf_path, f'{demo_name}.pdf'), res_path, 'ocr')+ logging.info(cmd)+ os.system(cmd)+ common.cli_count_folders_and_check_contents(+ os.path.join(res_path, demo_name, 'ocr'))+++if __name__ == '__main__':+ pytest.main()diff --git a/tests/test_integrations/test_rag/assets/middle.json b/tests/test_integrations/test_rag/assets/middle.jsonnew file mode 100644index 00000000..44d3e06c--- /dev/null+++ b/tests/test_integrations/test_rag/assets/middle.json@@ -0,0 +1,2302 @@+{+ "pdf_info": [+ {+ "preproc_blocks": [+ {+ "type": "text",+ "bbox": [+ 47,+ 57,+ 299,+ 93+ ],+ "lines": [+ {+ "bbox": [+ 47,+ 57,+ 299,+ 68+ ],+ "spans": [+ {+ "bbox": [+ 49,+ 57,+ 298,+ 68+ ],+ "score": 0.98,+ "content": "of the synthetic stereo scene from a single camera perspective",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 71,+ 299,+ 80+ ],+ "spans": [+ {+ "bbox": [+ 49,+ 71,+ 299,+ 80+ ],+ "score": 0.96,+ "content": "along with the ground truth disparity,occlusion map,and",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 82,+ 123,+ 93+ ],+ "spans": [+ {+ "bbox": [+ 49,+ 82,+ 123,+ 93+ ],+ "score": 0.99,+ "content": "discontinuitymap.",+ "type": "text"+ }+ ]+ }+ ]+ },+ {+ "type": "image",+ "bbox": [+ 47,+ 100,+ 301,+ 535+ ],+ "blocks": [+ {+ "bbox": [+ 51,+ 100,+ 292,+ 484+ ],+ "type": "image_body",+ "lines": [+ {+ "bbox": [+ 51,+ 100,+ 292,+ 484+ ],+ "spans": [+ {+ "bbox": [+ 51,+ 100,+ 292,+ 484+ ],+ "score": 0.9999815225601196,+ "type": "image",+ "image_path": "b07d74524eac6f46b5505b48b1e10db23f2b45cb2d21d5fec72e967e61255811.jpg"+ }+ ]+ }+ ]+ },+ {+ "bbox": [+ 47,+ 488,+ 301,+ 535+ ],+ "type": "image_caption",+ "lines": [+ {+ "bbox": [+ 49,+ 490,+ 299,+ 499+ ],+ "spans": [+ {+ "bbox": [+ 49,+ 490,+ 299,+ 499+ ],+ "score": 1.0,+ "content": "Figure2:Twosampleframesfromthesyntheticvideose-",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 48,+ 501,+ 300,+ 512+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 501,+ 300,+ 512+ ],+ "score": 1.0,+ "content": "quence (1st row), along with their corresponding ground truth",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 48,+ 513,+ 299,+ 523+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 513,+ 299,+ 523+ ],+ "score": 0.98,+ "content": "disparity (2nd row), occlusion map (3rd row), and discontinuity",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 48,+ 525,+ 110,+ 535+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 525,+ 110,+ 535+ ],+ "score": 0.99,+ "content": "map (4th row).",+ "type": "text"+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "type": "text",+ "bbox": [+ 47,+ 549,+ 299,+ 678+ ],+ "lines": [+ {+ "bbox": [+ 58,+ 549,+ 299,+ 558+ ],+ "spans": [+ {+ "bbox": [+ 58,+ 549,+ 298,+ 558+ ],+ "score": 0.98,+ "content": "Theresultsof temporalstereomatching aregiveninFigure",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 561,+ 299,+ 570+ ],+ "spans": [+ {+ "bbox": [+ 47,+ 561,+ 298,+ 570+ ],+ "score": 0.98,+ "content": "3foruniformadditivenoiseconfinedtotherangesof±O",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 573,+ 299,+ 582+ ],+ "spans": [+ {+ "bbox": [+ 49,+ 573,+ 299,+ 582+ ],+ "score": 0.96,+ "content": "±20, and ±40. Each performance plot is given as a function",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 585,+ 299,+ 594+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 585,+ 299,+ 594+ ],+ "score": 0.95,+ "content": "of the feedback coefficient X. As with the majority of temporal",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 597,+ 299,+ 606+ ],+ "spans": [+ {+ "bbox": [+ 49,+ 597,+ 299,+ 606+ ],+ "score": 0.99,+ "content": "stereomatching methods,improvements are negligible when",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 609,+ 299,+ 618+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 609,+ 299,+ 618+ ],+ "score": 0.97,+ "content": "no noise is added to the images [1o], [19]. This is largely due",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 621,+ 299,+ 629+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 621,+ 299,+ 629+ ],+ "score": 1.0,+ "content": "tothefactthatthevideousedtoevaluatethesemethodsis",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 633,+ 299,+ 641+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 633,+ 299,+ 641+ ],+ "score": 1.0,+ "content": "computergeneratedwithverylittlenoisetostartwith,thus",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 644,+ 299,+ 654+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 644,+ 299,+ 654+ ],+ "score": 0.98,+ "content": "the noise suppression achieved with temporal stereo matching",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 657,+ 299,+ 666+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 657,+ 299,+ 666+ ],+ "score": 0.98,+ "content": "showslittletonoimprovementovermethodsthatoperate on",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 669,+ 113,+ 678+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 669,+ 113,+ 678+ ],+ "score": 1.0,+ "content": "pairsofimages.",+ "type": "text"+ }+ ]+ }+ ]+ },+ {+ "type": "text",+ "bbox": [+ 47,+ 680,+ 299,+ 725+ ],+ "lines": [+ {+ "bbox": [+ 58,+ 680,+ 299,+ 690+ ],+ "spans": [+ {+ "bbox": [+ 59,+ 680,+ 298,+ 690+ ],+ "score": 0.97,+ "content": "Significantimprovementsin accuracy canbeseenin Figure",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 692,+ 299,+ 701+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 692,+ 298,+ 701+ ],+ "score": 0.97,+ "content": "3 when the noise has ranges of ±20, and ±40.In this scenario",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 703,+ 299,+ 714+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 703,+ 299,+ 714+ ],+ "score": 0.98,+ "content": "the effect of noise in the current frame is reduced by increasing",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 716,+ 299,+ 725+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 716,+ 299,+ 725+ ],+ "score": 0.96,+ "content": "thefeedbackcoefficientX.Thisincreasing ofXhas theeffect",+ "type": "text"+ }+ ]+ }+ ]+ },+ {+ "type": "image",+ "bbox": [+ 310,+ 55,+ 564,+ 371+ ],+ "blocks": [+ {+ "bbox": [+ 314,+ 55,+ 538,+ 305+ ],+ "type": "image_body",+ "lines": [+ {+ "bbox": [+ 314,+ 55,+ 538,+ 305+ ],+ "spans": [+ {+ "bbox": [+ 314,+ 55,+ 538,+ 305+ ],+ "score": 0.9999905824661255,+ "type": "image",+ "image_path": "c7539af438972442d0f86aa46409e6684338ddfd1fbfd6bdacf02220853ccb55.jpg"+ }+ ]+ }+ ]+ },+ {+ "bbox": [+ 310,+ 311,+ 564,+ 371+ ],+ "type": "image_caption",+ "lines": [+ {+ "bbox": [+ 312,+ 313,+ 562,+ 322+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 313,+ 562,+ 322+ ],+ "score": 0.97,+ "content": "Figure 3: Performance of temporal matching at different levels",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 312,+ 325,+ 561,+ 334+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 325,+ 561,+ 334+ ],+ "score": 0.98,+ "content": "of uniformly distributed image noise{±0,±20,±40}.Mean",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 311,+ 336,+ 563,+ 347+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 336,+ 563,+ 347+ ],+ "score": 0.99,+ "content": "squared error (MSE) of disparities is plotted versus the values",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 311,+ 348,+ 561,+ 358+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 348,+ 561,+ 358+ ],+ "score": 0.96,+ "content": "of the feedback coefficient X. Dashed lines correspond to the",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 311,+ 360,+ 535,+ 371+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 360,+ 535,+ 371+ ],+ "score": 0.96,+ "content": "values of MSE obtained without temporal aggregation.",+ "type": "text"+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "type": "image",+ "bbox": [+ 310,+ 418,+ 563,+ 666+ ],+ "blocks": [+ {+ "bbox": [+ 314,+ 418,+ 549,+ 623+ ],+ "type": "image_body",+ "lines": [+ {+ "bbox": [+ 314,+ 418,+ 549,+ 623+ ],+ "spans": [+ {+ "bbox": [+ 314,+ 418,+ 549,+ 623+ ],+ "score": 0.9999067783355713,+ "type": "image",+ "image_path": "9ac4db9197801de4a20dbc9ea17bc0c53afb7290dc8b5b45d9e92e830566cb14.jpg"+ }+ ]+ }+ ]+ },+ {+ "bbox": [+ 310,+ 630,+ 563,+ 666+ ],+ "type": "image_caption",+ "lines": [+ {+ "bbox": [+ 312,+ 631,+ 562,+ 641+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 631,+ 562,+ 641+ ],+ "score": 0.94,+ "content": "Figure 4:Optimal values of the feedback coefficient \\ cor-",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 312,+ 644,+ 561,+ 652+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 644,+ 561,+ 652+ ],+ "score": 0.97,+ "content": "responding to the smallest mean squared error (MSE)of the",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 312,+ 655,+ 513,+ 665+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 655,+ 513,+ 665+ ],+ "score": 0.97,+ "content": "disparity estimates for a range of noise strengths.",+ "type": "text"+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "type": "text",+ "bbox": [+ 311,+ 692,+ 563,+ 725+ ],+ "lines": [+ {+ "bbox": [+ 311,+ 692,+ 563,+ 702+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 692,+ 562,+ 702+ ],+ "score": 0.95,+ "content": "of averaging out noise in the per-pixel costs by selecting",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 311,+ 704,+ 563,+ 713+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 704,+ 562,+ 713+ ],+ "score": 0.98,+ "content": "matches based more heavily upon the auxiliary cost, which",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 311,+ 716,+ 563,+ 725+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 716,+ 563,+ 725+ ],+ "score": 0.97,+ "content": "is essentially a much more stable running average of the cost",+ "type": "text"+ }+ ]+ }+ ]+ }+ ],+ "layout_bboxes": [+ {+ "layout_bbox": [+ 47,+ 55,+ 301,+ 726+ ],+ "layout_label": "V",+ "sub_layout": []+ },+ {+ "layout_bbox": [+ 310,+ 55,+ 564,+ 726+ ],+ "layout_label": "V",+ "sub_layout": []+ }+ ],+ "page_idx": 0,+ "page_size": [+ 612.0,+ 792.0+ ],+ "_layout_tree": [+ {+ "layout_bbox": [+ 0,+ 55,+ 612.0,+ 726+ ],+ "layout_label": "V",+ "sub_layout": [+ {+ "layout_bbox": [+ 47,+ 55,+ 564,+ 726+ ],+ "layout_label": "H",+ "sub_layout": [+ {+ "layout_bbox": [+ 47,+ 55,+ 301,+ 726+ ],+ "layout_label": "V",+ "sub_layout": []+ },+ {+ "layout_bbox": [+ 310,+ 55,+ 564,+ 726+ ],+ "layout_label": "V",+ "sub_layout": []+ }+ ]+ }+ ]+ }+ ],+ "images": [+ {+ "type": "image",+ "bbox": [+ 47,+ 100,+ 301,+ 535+ ],+ "blocks": [+ {+ "bbox": [+ 51,+ 100,+ 292,+ 484+ ],+ "type": "image_body",+ "lines": [+ {+ "bbox": [+ 51,+ 100,+ 292,+ 484+ ],+ "spans": [+ {+ "bbox": [+ 51,+ 100,+ 292,+ 484+ ],+ "score": 0.9999815225601196,+ "type": "image",+ "image_path": "b07d74524eac6f46b5505b48b1e10db23f2b45cb2d21d5fec72e967e61255811.jpg"+ }+ ]+ }+ ]+ },+ {+ "bbox": [+ 47,+ 488,+ 301,+ 535+ ],+ "type": "image_caption",+ "lines": [+ {+ "bbox": [+ 49,+ 490,+ 299,+ 499+ ],+ "spans": [+ {+ "bbox": [+ 49,+ 490,+ 299,+ 499+ ],+ "score": 1.0,+ "content": "Figure2:Twosampleframesfromthesyntheticvideose-",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 48,+ 501,+ 300,+ 512+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 501,+ 300,+ 512+ ],+ "score": 1.0,+ "content": "quence (1st row), along with their corresponding ground truth",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 48,+ 513,+ 299,+ 523+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 513,+ 299,+ 523+ ],+ "score": 0.98,+ "content": "disparity (2nd row), occlusion map (3rd row), and discontinuity",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 48,+ 525,+ 110,+ 535+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 525,+ 110,+ 535+ ],+ "score": 0.99,+ "content": "map (4th row).",+ "type": "text"+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "type": "image",+ "bbox": [+ 310,+ 55,+ 564,+ 371+ ],+ "blocks": [+ {+ "bbox": [+ 314,+ 55,+ 538,+ 305+ ],+ "type": "image_body",+ "lines": [+ {+ "bbox": [+ 314,+ 55,+ 538,+ 305+ ],+ "spans": [+ {+ "bbox": [+ 314,+ 55,+ 538,+ 305+ ],+ "score": 0.9999905824661255,+ "type": "image",+ "image_path": "c7539af438972442d0f86aa46409e6684338ddfd1fbfd6bdacf02220853ccb55.jpg"+ }+ ]+ }+ ]+ },+ {+ "bbox": [+ 310,+ 311,+ 564,+ 371+ ],+ "type": "image_caption",+ "lines": [+ {+ "bbox": [+ 312,+ 313,+ 562,+ 322+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 313,+ 562,+ 322+ ],+ "score": 0.97,+ "content": "Figure 3: Performance of temporal matching at different levels",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 312,+ 325,+ 561,+ 334+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 325,+ 561,+ 334+ ],+ "score": 0.98,+ "content": "of uniformly distributed image noise{±0,±20,±40}.Mean",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 311,+ 336,+ 563,+ 347+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 336,+ 563,+ 347+ ],+ "score": 0.99,+ "content": "squared error (MSE) of disparities is plotted versus the values",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 311,+ 348,+ 561,+ 358+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 348,+ 561,+ 358+ ],+ "score": 0.96,+ "content": "of the feedback coefficient X. Dashed lines correspond to the",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 311,+ 360,+ 535,+ 371+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 360,+ 535,+ 371+ ],+ "score": 0.96,+ "content": "values of MSE obtained without temporal aggregation.",+ "type": "text"+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "type": "image",+ "bbox": [+ 310,+ 418,+ 563,+ 666+ ],+ "blocks": [+ {+ "bbox": [+ 314,+ 418,+ 549,+ 623+ ],+ "type": "image_body",+ "lines": [+ {+ "bbox": [+ 314,+ 418,+ 549,+ 623+ ],+ "spans": [+ {+ "bbox": [+ 314,+ 418,+ 549,+ 623+ ],+ "score": 0.9999067783355713,+ "type": "image",+ "image_path": "9ac4db9197801de4a20dbc9ea17bc0c53afb7290dc8b5b45d9e92e830566cb14.jpg"+ }+ ]+ }+ ]+ },+ {+ "bbox": [+ 310,+ 630,+ 563,+ 666+ ],+ "type": "image_caption",+ "lines": [+ {+ "bbox": [+ 312,+ 631,+ 562,+ 641+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 631,+ 562,+ 641+ ],+ "score": 0.94,+ "content": "Figure 4:Optimal values of the feedback coefficient \\ cor-",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 312,+ 644,+ 561,+ 652+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 644,+ 561,+ 652+ ],+ "score": 0.97,+ "content": "responding to the smallest mean squared error (MSE)of the",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 312,+ 655,+ 513,+ 665+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 655,+ 513,+ 665+ ],+ "score": 0.97,+ "content": "disparity estimates for a range of noise strengths.",+ "type": "text"+ }+ ]+ }+ ]+ }+ ]+ }+ ],+ "tables": [],+ "interline_equations": [],+ "discarded_blocks": [],+ "need_drop": false,+ "drop_reason": [],+ "para_blocks": [+ {+ "type": "text",+ "bbox": [+ 47,+ 57,+ 299,+ 93+ ],+ "lines": [+ {+ "bbox": [+ 47,+ 57,+ 299,+ 68+ ],+ "spans": [+ {+ "bbox": [+ 49,+ 57,+ 298,+ 68+ ],+ "score": 0.98,+ "content": "of the synthetic stereo scene from a single camera perspective",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 71,+ 299,+ 80+ ],+ "spans": [+ {+ "bbox": [+ 49,+ 71,+ 299,+ 80+ ],+ "score": 0.96,+ "content": "along with the ground truth disparity,occlusion map,and",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 82,+ 123,+ 93+ ],+ "spans": [+ {+ "bbox": [+ 49,+ 82,+ 123,+ 93+ ],+ "score": 0.99,+ "content": "discontinuitymap.",+ "type": "text"+ }+ ]+ }+ ]+ },+ {+ "type": "image",+ "bbox": [+ 47,+ 100,+ 301,+ 535+ ],+ "blocks": [+ {+ "bbox": [+ 51,+ 100,+ 292,+ 484+ ],+ "type": "image_body",+ "lines": [+ {+ "bbox": [+ 51,+ 100,+ 292,+ 484+ ],+ "spans": [+ {+ "bbox": [+ 51,+ 100,+ 292,+ 484+ ],+ "score": 0.9999815225601196,+ "type": "image",+ "image_path": "b07d74524eac6f46b5505b48b1e10db23f2b45cb2d21d5fec72e967e61255811.jpg"+ }+ ]+ }+ ]+ },+ {+ "bbox": [+ 47,+ 488,+ 301,+ 535+ ],+ "type": "image_caption",+ "lines": [+ {+ "bbox": [+ 49,+ 490,+ 299,+ 499+ ],+ "spans": [+ {+ "bbox": [+ 49,+ 490,+ 299,+ 499+ ],+ "score": 1.0,+ "content": "Figure2:Twosampleframesfromthesyntheticvideose-",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 48,+ 501,+ 300,+ 512+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 501,+ 300,+ 512+ ],+ "score": 1.0,+ "content": "quence (1st row), along with their corresponding ground truth",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 48,+ 513,+ 299,+ 523+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 513,+ 299,+ 523+ ],+ "score": 0.98,+ "content": "disparity (2nd row), occlusion map (3rd row), and discontinuity",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 48,+ 525,+ 110,+ 535+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 525,+ 110,+ 535+ ],+ "score": 0.99,+ "content": "map (4th row).",+ "type": "text"+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "type": "text",+ "bbox": [+ 47,+ 549,+ 299,+ 678+ ],+ "lines": [+ {+ "bbox": [+ 58,+ 549,+ 299,+ 558+ ],+ "spans": [+ {+ "bbox": [+ 58,+ 549,+ 298,+ 558+ ],+ "score": 0.98,+ "content": "Theresultsof temporalstereomatching aregiveninFigure",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 561,+ 299,+ 570+ ],+ "spans": [+ {+ "bbox": [+ 47,+ 561,+ 298,+ 570+ ],+ "score": 0.98,+ "content": "3foruniformadditivenoiseconfinedtotherangesof±O",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 573,+ 299,+ 582+ ],+ "spans": [+ {+ "bbox": [+ 49,+ 573,+ 299,+ 582+ ],+ "score": 0.96,+ "content": "±20, and ±40. Each performance plot is given as a function",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 585,+ 299,+ 594+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 585,+ 299,+ 594+ ],+ "score": 0.95,+ "content": "of the feedback coefficient X. As with the majority of temporal",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 597,+ 299,+ 606+ ],+ "spans": [+ {+ "bbox": [+ 49,+ 597,+ 299,+ 606+ ],+ "score": 0.99,+ "content": "stereomatching methods,improvements are negligible when",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 609,+ 299,+ 618+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 609,+ 299,+ 618+ ],+ "score": 0.97,+ "content": "no noise is added to the images [1o], [19]. This is largely due",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 621,+ 299,+ 629+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 621,+ 299,+ 629+ ],+ "score": 1.0,+ "content": "tothefactthatthevideousedtoevaluatethesemethodsis",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 633,+ 299,+ 641+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 633,+ 299,+ 641+ ],+ "score": 1.0,+ "content": "computergeneratedwithverylittlenoisetostartwith,thus",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 644,+ 299,+ 654+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 644,+ 299,+ 654+ ],+ "score": 0.98,+ "content": "the noise suppression achieved with temporal stereo matching",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 657,+ 299,+ 666+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 657,+ 299,+ 666+ ],+ "score": 0.98,+ "content": "showslittletonoimprovementovermethodsthatoperate on",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 669,+ 113,+ 678+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 669,+ 113,+ 678+ ],+ "score": 1.0,+ "content": "pairsofimages.",+ "type": "text"+ }+ ]+ }+ ]+ },+ {+ "type": "text",+ "bbox": [+ 47,+ 680,+ 299,+ 725+ ],+ "lines": [+ {+ "bbox": [+ 58,+ 680,+ 299,+ 690+ ],+ "spans": [+ {+ "bbox": [+ 59,+ 680,+ 298,+ 690+ ],+ "score": 0.97,+ "content": "Significantimprovementsin accuracy canbeseenin Figure",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 692,+ 299,+ 701+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 692,+ 298,+ 701+ ],+ "score": 0.97,+ "content": "3 when the noise has ranges of ±20, and ±40.In this scenario",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 703,+ 299,+ 714+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 703,+ 299,+ 714+ ],+ "score": 0.98,+ "content": "the effect of noise in the current frame is reduced by increasing",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 47,+ 716,+ 299,+ 725+ ],+ "spans": [+ {+ "bbox": [+ 48,+ 716,+ 299,+ 725+ ],+ "score": 0.96,+ "content": "thefeedbackcoefficientX.Thisincreasing ofXhas theeffect",+ "type": "text"+ }+ ]+ }+ ]+ },+ {+ "type": "image",+ "bbox": [+ 310,+ 55,+ 564,+ 371+ ],+ "blocks": [+ {+ "bbox": [+ 314,+ 55,+ 538,+ 305+ ],+ "type": "image_body",+ "lines": [+ {+ "bbox": [+ 314,+ 55,+ 538,+ 305+ ],+ "spans": [+ {+ "bbox": [+ 314,+ 55,+ 538,+ 305+ ],+ "score": 0.9999905824661255,+ "type": "image",+ "image_path": "c7539af438972442d0f86aa46409e6684338ddfd1fbfd6bdacf02220853ccb55.jpg"+ }+ ]+ }+ ]+ },+ {+ "bbox": [+ 310,+ 311,+ 564,+ 371+ ],+ "type": "image_caption",+ "lines": [+ {+ "bbox": [+ 312,+ 313,+ 562,+ 322+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 313,+ 562,+ 322+ ],+ "score": 0.97,+ "content": "Figure 3: Performance of temporal matching at different levels",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 312,+ 325,+ 561,+ 334+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 325,+ 561,+ 334+ ],+ "score": 0.98,+ "content": "of uniformly distributed image noise{±0,±20,±40}.Mean",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 311,+ 336,+ 563,+ 347+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 336,+ 563,+ 347+ ],+ "score": 0.99,+ "content": "squared error (MSE) of disparities is plotted versus the values",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 311,+ 348,+ 561,+ 358+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 348,+ 561,+ 358+ ],+ "score": 0.96,+ "content": "of the feedback coefficient X. Dashed lines correspond to the",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 311,+ 360,+ 535,+ 371+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 360,+ 535,+ 371+ ],+ "score": 0.96,+ "content": "values of MSE obtained without temporal aggregation.",+ "type": "text"+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "type": "image",+ "bbox": [+ 310,+ 418,+ 563,+ 666+ ],+ "blocks": [+ {+ "bbox": [+ 314,+ 418,+ 549,+ 623+ ],+ "type": "image_body",+ "lines": [+ {+ "bbox": [+ 314,+ 418,+ 549,+ 623+ ],+ "spans": [+ {+ "bbox": [+ 314,+ 418,+ 549,+ 623+ ],+ "score": 0.9999067783355713,+ "type": "image",+ "image_path": "9ac4db9197801de4a20dbc9ea17bc0c53afb7290dc8b5b45d9e92e830566cb14.jpg"+ }+ ]+ }+ ]+ },+ {+ "bbox": [+ 310,+ 630,+ 563,+ 666+ ],+ "type": "image_caption",+ "lines": [+ {+ "bbox": [+ 312,+ 631,+ 562,+ 641+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 631,+ 562,+ 641+ ],+ "score": 0.94,+ "content": "Figure 4:Optimal values of the feedback coefficient \\ cor-",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 312,+ 644,+ 561,+ 652+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 644,+ 561,+ 652+ ],+ "score": 0.97,+ "content": "responding to the smallest mean squared error (MSE)of the",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 312,+ 655,+ 513,+ 665+ ],+ "spans": [+ {+ "bbox": [+ 312,+ 655,+ 513,+ 665+ ],+ "score": 0.97,+ "content": "disparity estimates for a range of noise strengths.",+ "type": "text"+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "type": "text",+ "bbox": [+ 311,+ 692,+ 563,+ 725+ ],+ "lines": [+ {+ "bbox": [+ 311,+ 692,+ 563,+ 702+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 692,+ 562,+ 702+ ],+ "score": 0.95,+ "content": "of averaging out noise in the per-pixel costs by selecting",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 311,+ 704,+ 563,+ 713+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 704,+ 562,+ 713+ ],+ "score": 0.98,+ "content": "matches based more heavily upon the auxiliary cost, which",+ "type": "text"+ }+ ]+ },+ {+ "bbox": [+ 311,+ 716,+ 563,+ 725+ ],+ "spans": [+ {+ "bbox": [+ 311,+ 716,+ 563,+ 725+ ],+ "score": 0.97,+ "content": "is essentially a much more stable running average of the cost",+ "type": "text"+ }+ ]+ }+ ]+ }+ ]+ }+ ],+ "_parse_type": "ocr",+ "_version_name": "0.7.0b1"+}diff --git a/tests/test_integrations/test_rag/assets/one_page_with_table_image.2.pdf b/tests/test_integrations/test_rag/assets/one_page_with_table_image.2.pdfnew file mode 100644index 00000000..b1366208Binary files /dev/null and b/tests/test_integrations/test_rag/assets/one_page_with_table_image.2.pdf differdiff --git a/tests/test_integrations/test_rag/assets/one_page_with_table_image.pdf b/tests/test_integrations/test_rag/assets/one_page_with_table_image.pdfnew file mode 100644index 00000000..85fd9a7aBinary files /dev/null and b/tests/test_integrations/test_rag/assets/one_page_with_table_image.pdf differdiff --git a/tests/test_integrations/test_rag/test_api.py b/tests/test_integrations/test_rag/test_api.pynew file mode 100644index 00000000..99d30c07--- /dev/null+++ b/tests/test_integrations/test_rag/test_api.py@@ -0,0 +1,55 @@+import json+import os+import shutil+import tempfile++from magic_pdf.integrations.rag.api import DataReader, RagDocumentReader+from magic_pdf.integrations.rag.type import CategoryType+from magic_pdf.integrations.rag.utils import \+ convert_middle_json_to_layout_elements+++def test_rag_document_reader():+ # setup+ unitest_dir = '/tmp/magic_pdf/unittest/integrations/rag'+ os.makedirs(unitest_dir, exist_ok=True)+ temp_output_dir = tempfile.mkdtemp(dir=unitest_dir)+ os.makedirs(temp_output_dir, exist_ok=True)++ # test+ with open('tests/test_integrations/test_rag/assets/middle.json') as f:+ json_data = json.load(f)+ res = convert_middle_json_to_layout_elements(json_data, temp_output_dir)++ doc = RagDocumentReader(res)+ assert len(list(iter(doc))) == 1++ page = list(iter(doc))[0]+ assert len(list(iter(page))) == 10+ assert len(page.get_rel_map()) == 3++ item = list(iter(page))[0]+ assert item.category_type == CategoryType.text++ # teardown+ shutil.rmtree(temp_output_dir)+++def test_data_reader():+ # setup+ unitest_dir = '/tmp/magic_pdf/unittest/integrations/rag'+ os.makedirs(unitest_dir, exist_ok=True)+ temp_output_dir = tempfile.mkdtemp(dir=unitest_dir)+ os.makedirs(temp_output_dir, exist_ok=True)++ # test+ data_reader = DataReader('tests/test_integrations/test_rag/assets', 'ocr',+ temp_output_dir)++ assert data_reader.get_documents_count() == 2+ for idx in range(data_reader.get_documents_count()):+ document = data_reader.get_document_result(idx)+ assert document is not None++ # teardown+ shutil.rmtree(temp_output_dir)diff --git a/tests/test_integrations/test_rag/test_utils.py b/tests/test_integrations/test_rag/test_utils.pynew file mode 100644index 00000000..b18c1d8e--- /dev/null+++ b/tests/test_integrations/test_rag/test_utils.py@@ -0,0 +1,57 @@+import json+import os+import shutil+import tempfile++from magic_pdf.integrations.rag.type import CategoryType+from magic_pdf.integrations.rag.utils import (+ convert_middle_json_to_layout_elements, inference)+++def test_convert_middle_json_to_layout_elements():+ # setup+ unitest_dir = '/tmp/magic_pdf/unittest/integrations/rag'+ os.makedirs(unitest_dir, exist_ok=True)+ temp_output_dir = tempfile.mkdtemp(dir=unitest_dir)+ os.makedirs(temp_output_dir, exist_ok=True)++ # test+ with open('tests/test_integrations/test_rag/assets/middle.json') as f:+ json_data = json.load(f)+ res = convert_middle_json_to_layout_elements(json_data, temp_output_dir)++ assert len(res) == 1+ assert len(res[0].layout_dets) == 10+ assert res[0].layout_dets[0].anno_id == 0+ assert res[0].layout_dets[0].category_type == CategoryType.text+ assert len(res[0].extra.element_relation) == 3++ # teardown+ shutil.rmtree(temp_output_dir)+++def test_inference():++ asset_dir = 'tests/test_integrations/test_rag/assets'+ # setup+ unitest_dir = '/tmp/magic_pdf/unittest/integrations/rag'+ os.makedirs(unitest_dir, exist_ok=True)+ temp_output_dir = tempfile.mkdtemp(dir=unitest_dir)+ os.makedirs(temp_output_dir, exist_ok=True)++ # test+ res = inference(+ asset_dir + '/one_page_with_table_image.pdf',+ temp_output_dir,+ 'ocr',+ )++ assert res is not None+ assert len(res) == 1+ assert len(res[0].layout_dets) == 10+ assert res[0].layout_dets[0].anno_id == 0+ assert res[0].layout_dets[0].category_type == CategoryType.text+ assert len(res[0].extra.element_relation) == 3++ # teardown+ shutil.rmtree(temp_output_dir)diff --git a/tests/test_para/test_hyphen_at_line_end.py b/tests/test_para/test_hyphen_at_line_end.pynew file mode 100644index 00000000..57cf313d--- /dev/null+++ b/tests/test_para/test_hyphen_at_line_end.py@@ -0,0 +1,28 @@++from magic_pdf.dict2md.ocr_mkcontent import __is_hyphen_at_line_end+++def test_hyphen_at_line_end():+ """+ 测试行尾是不是一个连字符+ """+ test_cases_ok = [+ "I am zhang-",+ "you are zhang- ",+ "math-",+ "This is a TEST-",+ "This is a TESTing-",+ "美国人 hello-",+ ]+ test_cases_bad = [+ "This is a TEST$-",+ "This is a TEST21-",+ "中国人-",+ "美国人 hello人-",+ "this is 123-",+ ]+ for test_case in test_cases_ok:+ assert __is_hyphen_at_line_end(test_case)++ for test_case in test_cases_bad:+ assert not __is_hyphen_at_line_end(test_case)\ No newline at end of filediff --git a/tests/test_tools/test_common.py b/tests/test_tools/test_common.pyindex 0d38e1de..60105efa 100644--- a/tests/test_tools/test_common.py+++ b/tests/test_tools/test_common.py@@ -19,7 +19,12 @@ def test_common_do_parse(method):# runwith open("tests/test_tools/assets/common/cli_test_01.pdf", "rb") as f:bits = f.read()- do_parse(temp_output_dir, filename, bits, [], method, f_dump_content_list=True)+ do_parse(temp_output_dir,+ filename,+ bits, [],+ method,+ False,+ f_dump_content_list=True)# checkbase_output_dir = os.path.join(temp_output_dir, f"fake/{method}")diff --git a/tests/test_unit.py b/tests/test_unit.pyindex 1dbcf70d..37e6af5c 100644--- a/tests/test_unit.py+++ b/tests/test_unit.py@@ -1,18 +1,30 @@-import pytestimport os-from magic_pdf.libs.boxbase import _is_in_or_part_overlap, _is_in_or_part_overlap_with_area_ratio, _is_in, \- _is_part_overlap, _left_intersect, _right_intersect, _is_vertical_full_overlap, _is_bottom_full_overlap, \- _is_left_overlap, __is_overlaps_y_exceeds_threshold, calculate_iou, calculate_overlap_area_2_minbox_area_ratio, \- calculate_overlap_area_in_bbox1_area_ratio, get_minbox_if_overlap_by_ratio, get_bbox_in_boundry, \- find_top_nearest_text_bbox, find_bottom_nearest_text_bbox, find_left_nearest_text_bbox, \- find_right_nearest_text_bbox, bbox_relative_pos, bbox_distance-from magic_pdf.libs.commons import mymax, join_path, get_top_percent_list++import pytest++from magic_pdf.libs.boxbase import (__is_overlaps_y_exceeds_threshold,+ _is_bottom_full_overlap, _is_in,+ _is_in_or_part_overlap,+ _is_in_or_part_overlap_with_area_ratio,+ _is_left_overlap, _is_part_overlap,+ _is_vertical_full_overlap, _left_intersect,+ _right_intersect, bbox_distance,+ bbox_relative_pos, calculate_iou,+ calculate_overlap_area_2_minbox_area_ratio,+ calculate_overlap_area_in_bbox1_area_ratio,+ find_bottom_nearest_text_bbox,+ find_left_nearest_text_bbox,+ find_right_nearest_text_bbox,+ find_top_nearest_text_bbox,+ get_bbox_in_boundary,+ get_minbox_if_overlap_by_ratio)+from magic_pdf.libs.commons import get_top_percent_list, join_path, mymaxfrom magic_pdf.libs.config_reader import get_s3_configfrom magic_pdf.libs.path_utils import parse_s3path# 输入一个列表,如果列表空返回0,否则返回最大元素[email protected]("list_input, target_num",[email protected]('list_input, target_num',[([0, 0, 0, 0], 0),([0], 0),@@ -29,7 +41,7 @@ def test_list_max(list_input: list, target_num) -> None:# 连接多个参数生成路径信息,使用"/"作为连接符,生成的结果需要是一个合法路径[email protected]("path_input, target_path", [[email protected]('path_input, target_path', [(['https:', '', 'www.baidu.com'], 'https://www.baidu.com'),(['https:', 'www.baidu.com'], 'https:/www.baidu.com'),(['D:', 'file', 'pythonProject', 'demo' + '.py'], 'D:/file/pythonProject/demo.py'),@@ -42,7 +54,7 @@ def test_join_path(path_input: list, target_path: str) -> None:# 获取列表中前百分之多少的元素[email protected]("num_list, percent, target_num_list", [[email protected]('num_list, percent, target_num_list', [([], 0.75, []),([-5, -10, 9, 3, 7, -7, 0, 23, -1, -11], 0.8, [23, 9, 7, 3, 0, -1, -5, -7]),([-5, -10, 9, 3, 7, -7, 0, 23, -1, -11], 0, []),@@ -57,9 +69,9 @@ def test_get_top_percent_list(num_list: list, percent: float, target_num_list: l# 输入一个s3路径,返回bucket名字和其余部分(key)[email protected]("s3_path, target_data", [- ("s3://bucket/path/to/my/file.txt", "bucket"),- ("s3a://bucket1/path/to/my/file2.txt", "bucket1"),[email protected]('s3_path, target_data', [+ ('s3://bucket/path/to/my/file.txt', 'bucket'),+ ('s3a://bucket1/path/to/my/file2.txt', 'bucket1'),# ("/path/to/my/file1.txt", "path"),# ("bucket/path/to/my/file2.txt", "bucket"),])@@ -76,7 +88,7 @@ def test_parse_s3path(s3_path: str, target_data: str):# 2个box是否处于包含或者部分重合关系。# 如果某边界重合算重合。# 部分边界重合,其他在内部也算包含[email protected]("box1, box2, target_bool", [[email protected]('box1, box2, target_bool', [((120, 133, 223, 248), (128, 168, 269, 295), True),((137, 53, 245, 157), (134, 11, 200, 147), True), # 部分重合((137, 56, 211, 116), (140, 66, 202, 199), True), # 部分重合@@ -101,7 +113,7 @@ def test_is_in_or_part_overlap(box1: tuple, box2: tuple, target_bool: bool) -> N# 如果box1在box2内部,返回True# 如果是部分重合的,则重合面积占box1的比例大于阈值时候返回True[email protected]("box1, box2, target_bool", [[email protected]('box1, box2, target_bool', [((35, 28, 108, 90), (47, 60, 83, 96), False), # 包含 box1 up box2, box2 多半,box1少半((65, 151, 92, 177), (49, 99, 105, 198), True), # 包含 box1 in box2((80, 62, 112, 84), (74, 40, 144, 111), True), # 包含 box1 in box2@@ -119,7 +131,7 @@ def test_is_in_or_part_overlap_with_area_ratio(box1: tuple, box2: tuple, target_# box1在box2内部或者box2在box1内部返回True。如果部分边界重合也算作包含。[email protected]("box1, box2, target_bool", [[email protected]('box1, box2, target_bool', [# ((), (), "Error"), # Error((65, 151, 92, 177), (49, 99, 105, 198), True), # 包含 box1 in box2((80, 62, 112, 84), (74, 40, 144, 111), True), # 包含 box1 in box2@@ -141,7 +153,7 @@ def test_is_in(box1: tuple, box2: tuple, target_bool: bool) -> None:# 仅仅是部分包含关系,返回True,如果是完全包含关系则返回False[email protected]("box1, box2, target_bool", [[email protected]('box1, box2, target_bool', [((65, 151, 92, 177), (49, 99, 105, 198), False), # 包含 box1 in box2((80, 62, 112, 84), (74, 40, 144, 111), False), # 包含 box1 in box2# ((76, 140, 154, 277), (121, 326, 192, 384), False), # 分离 Error@@ -161,7 +173,7 @@ def test_is_part_overlap(box1: tuple, box2: tuple, target_bool: bool) -> None:# left_box右侧是否和right_box左侧有部分重叠[email protected]("box1, box2, target_bool", [[email protected]('box1, box2, target_bool', [(None, None, False),((88, 81, 222, 173), (60, 221, 123, 358), False), # 分离((121, 149, 184, 289), (172, 130, 230, 268), True), # box1 left bottom box2 相交@@ -179,7 +191,7 @@ def test_left_intersect(box1: tuple, box2: tuple, target_bool: bool) -> None:# left_box左侧是否和right_box右侧部分重叠[email protected]("box1, box2, target_bool", [[email protected]('box1, box2, target_bool', [(None, None, False),((88, 81, 222, 173), (60, 221, 123, 358), False), # 分离((121, 149, 184, 289), (172, 130, 230, 268), False), # box1 left bottom box2 相交@@ -198,7 +210,7 @@ def test_right_intersect(box1: tuple, box2: tuple, target_bool: bool) -> None:# x方向上:要么box1包含box2, 要么box2包含box1。不能部分包含# y方向上:box1和box2有重叠[email protected]("box1, box2, target_bool", [[email protected]('box1, box2, target_bool', [# (None, None, False), # Error((35, 28, 108, 90), (47, 60, 83, 96), True), # box1 top box2, x:box2 in box1, y:有重叠((35, 28, 98, 90), (27, 60, 103, 96), True), # box1 top box2, x:box1 in box2, y:有重叠@@ -214,7 +226,7 @@ def test_is_vertical_full_overlap(box1: tuple, box2: tuple, target_bool: bool) -# 检查box1下方和box2的上方有轻微的重叠,轻微程度收到y_tolerance的限制[email protected]("box1, box2, target_bool", [[email protected]('box1, box2, target_bool', [(None, None, False),((35, 28, 108, 90), (47, 89, 83, 116), True), # box1 top box2, y:有重叠((35, 28, 108, 90), (47, 60, 83, 96), False), # box1 top box2, y:有重叠且过多@@ -228,7 +240,7 @@ def test_is_bottom_full_overlap(box1: tuple, box2: tuple, target_bool: bool) -># 检查box1的左侧是否和box2有重叠[email protected]("box1, box2, target_bool", [[email protected]('box1, box2, target_bool', [(None, None, False),((88, 81, 222, 173), (60, 221, 123, 358), False), # 分离# ((121, 149, 184, 289), (172, 130, 230, 268), False), # box1 left bottom box2 相交 Error@@ -245,7 +257,7 @@ def test_is_left_overlap(box1: tuple, box2: tuple, target_bool: bool) -> None:# 查两个bbox在y轴上是否有重叠,并且该重叠区域的高度占两个bbox高度更低的那个超过阈值[email protected]("box1, box2, target_bool", [[email protected]('box1, box2, target_bool', [# (None, None, "Error"), # Error((51, 69, 192, 147), (75, 48, 132, 187), True), # y: box1 in box2((51, 39, 192, 197), (75, 48, 132, 187), True), # y: box2 in box1@@ -260,7 +272,7 @@ def test_is_overlaps_y_exceeds_threshold(box1: tuple, box2: tuple, target_bool:# Determine the coordinates of the intersection rectangle[email protected]("box1, box2, target_num", [[email protected]('box1, box2, target_num', [# (None, None, "Error"), # Error((88, 81, 222, 173), (60, 221, 123, 358), 0.0), # 分离((76, 140, 154, 277), (121, 326, 192, 384), 0.0), # 分离@@ -276,7 +288,7 @@ def test_calculate_iou(box1: tuple, box2: tuple, target_num: float) -> None:# 计算box1和box2的重叠面积占最小面积的box的比例[email protected]("box1, box2, target_num", [[email protected]('box1, box2, target_num', [# (None, None, "Error"), # Error((142, 109, 238, 164), (134, 211, 224, 270), 0.0), # 分离((88, 81, 222, 173), (60, 221, 123, 358), 0.0), # 分离@@ -295,7 +307,7 @@ def test_calculate_overlap_area_2_minbox_area_ratio(box1: tuple, box2: tuple, ta# 计算box1和box2的重叠面积占bbox1的比例[email protected]("box1, box2, target_num", [[email protected]('box1, box2, target_num', [# (None, None, "Error"), # Error((142, 109, 238, 164), (134, 211, 224, 270), 0.0), # 分离((88, 81, 222, 173), (60, 221, 123, 358), 0.0), # 分离@@ -315,7 +327,7 @@ def test_calculate_overlap_area_in_bbox1_area_ratio(box1: tuple, box2: tuple, ta# 计算两个bbox重叠的面积占最小面积的box的比例,如果比例大于ratio,则返回小的那个bbox,否则返回None[email protected]("box1, box2, ratio, target_box", [[email protected]('box1, box2, ratio, target_box', [# (None, None, 0.8, "Error"), # Error((142, 109, 238, 164), (134, 211, 224, 270), 0.0, None), # 分离((109, 126, 204, 245), (110, 127, 232, 206), 0.5, (110, 127, 232, 206)),@@ -331,7 +343,7 @@ def test_get_minbox_if_overlap_by_ratio(box1: tuple, box2: tuple, ratio: float,# 根据boundry获取在这个范围内的所有的box的列表,完全包含关系[email protected]("boxes, boundry, target_boxs", [[email protected]('boxes, boundary, target_boxs', [# ([], (), "Error"), # Error([], (110, 340, 209, 387), []),([(142, 109, 238, 164)], (134, 211, 224, 270), []), # 分离@@ -347,15 +359,15 @@ def test_get_minbox_if_overlap_by_ratio(box1: tuple, box2: tuple, ratio: float,(137, 29, 287, 87)], (30, 20, 200, 320),[(81, 280, 123, 315), (46, 99, 133, 148), (33, 156, 97, 211)]),])-def test_get_bbox_in_boundry(boxes: list, boundry: tuple, target_boxs: list) -> None:- assert target_boxs == get_bbox_in_boundry(boxes, boundry)+def test_get_bbox_in_boundary(boxes: list, boundary: tuple, target_boxs: list) -> None:+ assert target_boxs == get_bbox_in_boundary(boxes, boundary)# 寻找上方距离最近的box,margin 4个单位, x方向有重合,y方向最近的[email protected]("pymu_blocks, obj_box, target_boxs", [- ([{"bbox": (81, 280, 123, 315)}, {"bbox": (282, 203, 342, 247)}, {"bbox": (183, 100, 300, 155)},- {"bbox": (46, 99, 133, 148)}, {"bbox": (33, 156, 97, 211)},- {"bbox": (137, 29, 287, 87)}], (81, 280, 123, 315), {"bbox": (33, 156, 97, 211)}),[email protected]('pymu_blocks, obj_box, target_boxs', [+ ([{'bbox': (81, 280, 123, 315)}, {'bbox': (282, 203, 342, 247)}, {'bbox': (183, 100, 300, 155)},+ {'bbox': (46, 99, 133, 148)}, {'bbox': (33, 156, 97, 211)},+ {'bbox': (137, 29, 287, 87)}], (81, 280, 123, 315), {'bbox': (33, 156, 97, 211)}),# ([{"bbox": (168, 120, 263, 159)},# {"bbox": (231, 61, 279, 159)},# {"bbox": (35, 85, 136, 110)},@@ -363,46 +375,46 @@ def test_get_bbox_in_boundry(boxes: list, boundry: tuple, target_boxs: list) -># {"bbox": (144, 264, 188, 323)},# {"bbox": (62, 37, 126, 64)}], (228, 193, 347, 225),# [{"bbox": (168, 120, 263, 159)}, {"bbox": (231, 61, 279, 159)}]), # y:方向最近的有两个,x: 两个均有重合 Error- ([{"bbox": (35, 85, 136, 159)},- {"bbox": (168, 120, 263, 159)},- {"bbox": (231, 61, 279, 118)},- {"bbox": (228, 193, 347, 225)},- {"bbox": (144, 264, 188, 323)},- {"bbox": (62, 37, 126, 64)}], (228, 193, 347, 225),- {"bbox": (168, 120, 263, 159)},), # y:方向最近的有两个,x:只有一个有重合- ([{"bbox": (239, 115, 379, 167)},- {"bbox": (33, 237, 104, 262)},- {"bbox": (124, 288, 168, 325)},- {"bbox": (242, 291, 379, 340)},- {"bbox": (55, 117, 121, 154)},- {"bbox": (266, 183, 384, 217)}, ], (124, 288, 168, 325), {'bbox': (55, 117, 121, 154)}),- ([{"bbox": (239, 115, 379, 167)},- {"bbox": (33, 237, 104, 262)},- {"bbox": (124, 288, 168, 325)},- {"bbox": (242, 291, 379, 340)},- {"bbox": (55, 117, 119, 154)},- {"bbox": (266, 183, 384, 217)}, ], (124, 288, 168, 325), None), # x没有重合- ([{"bbox": (80, 90, 249, 200)},- {"bbox": (183, 100, 240, 155)}, ], (183, 100, 240, 155), None), # 包含+ ([{'bbox': (35, 85, 136, 159)},+ {'bbox': (168, 120, 263, 159)},+ {'bbox': (231, 61, 279, 118)},+ {'bbox': (228, 193, 347, 225)},+ {'bbox': (144, 264, 188, 323)},+ {'bbox': (62, 37, 126, 64)}], (228, 193, 347, 225),+ {'bbox': (168, 120, 263, 159)},), # y:方向最近的有两个,x:只有一个有重合+ ([{'bbox': (239, 115, 379, 167)},+ {'bbox': (33, 237, 104, 262)},+ {'bbox': (124, 288, 168, 325)},+ {'bbox': (242, 291, 379, 340)},+ {'bbox': (55, 117, 121, 154)},+ {'bbox': (266, 183, 384, 217)}, ], (124, 288, 168, 325), {'bbox': (55, 117, 121, 154)}),+ ([{'bbox': (239, 115, 379, 167)},+ {'bbox': (33, 237, 104, 262)},+ {'bbox': (124, 288, 168, 325)},+ {'bbox': (242, 291, 379, 340)},+ {'bbox': (55, 117, 119, 154)},+ {'bbox': (266, 183, 384, 217)}, ], (124, 288, 168, 325), None), # x没有重合+ ([{'bbox': (80, 90, 249, 200)},+ {'bbox': (183, 100, 240, 155)}, ], (183, 100, 240, 155), None), # 包含])def test_find_top_nearest_text_bbox(pymu_blocks: list, obj_box: tuple, target_boxs: dict) -> None:assert target_boxs == find_top_nearest_text_bbox(pymu_blocks, obj_box)# 寻找下方距离自己最近的box, x方向有重合,y方向最近的[email protected]("pymu_blocks, obj_box, target_boxs", [- ([{"bbox": (165, 96, 300, 114)},- {"bbox": (11, 157, 139, 201)},- {"bbox": (124, 208, 265, 262)},- {"bbox": (124, 283, 248, 306)},- {"bbox": (39, 267, 84, 301)},- {"bbox": (36, 89, 114, 145)}, ], (165, 96, 300, 114), {"bbox": (124, 208, 265, 262)}),- ([{"bbox": (187, 37, 303, 49)},- {"bbox": (2, 227, 90, 283)},- {"bbox": (158, 174, 200, 212)},- {"bbox": (259, 174, 324, 228)},- {"bbox": (205, 61, 316, 97)},- {"bbox": (295, 248, 374, 287)}, ], (205, 61, 316, 97), {"bbox": (259, 174, 324, 228)}), # y有两个最近的, x只有一个重合[email protected]('pymu_blocks, obj_box, target_boxs', [+ ([{'bbox': (165, 96, 300, 114)},+ {'bbox': (11, 157, 139, 201)},+ {'bbox': (124, 208, 265, 262)},+ {'bbox': (124, 283, 248, 306)},+ {'bbox': (39, 267, 84, 301)},+ {'bbox': (36, 89, 114, 145)}, ], (165, 96, 300, 114), {'bbox': (124, 208, 265, 262)}),+ ([{'bbox': (187, 37, 303, 49)},+ {'bbox': (2, 227, 90, 283)},+ {'bbox': (158, 174, 200, 212)},+ {'bbox': (259, 174, 324, 228)},+ {'bbox': (205, 61, 316, 97)},+ {'bbox': (295, 248, 374, 287)}, ], (205, 61, 316, 97), {'bbox': (259, 174, 324, 228)}), # y有两个最近的, x只有一个重合# ([{"bbox": (187, 37, 303, 49)},# {"bbox": (2, 227, 90, 283)},# {"bbox": (259, 174, 324, 228)},@@ -410,31 +422,31 @@ def test_find_top_nearest_text_bbox(pymu_blocks: list, obj_box: tuple, target_bo# {"bbox": (295, 248, 374, 287)},# {"bbox": (158, 174, 209, 212)}, ], (205, 61, 316, 97),# [{"bbox": (259, 174, 324, 228)}, {"bbox": (158, 174, 209, 212)}]), # x有重合,y有两个最近的 Error- ([{"bbox": (287, 132, 398, 191)},- {"bbox": (44, 141, 163, 188)},- {"bbox": (132, 191, 240, 241)},- {"bbox": (81, 25, 142, 67)},- {"bbox": (74, 297, 116, 314)},- {"bbox": (77, 84, 224, 107)}, ], (287, 132, 398, 191), None), # x没有重合- ([{"bbox": (80, 90, 249, 200)},- {"bbox": (183, 100, 240, 155)}, ], (183, 100, 240, 155), None), # 包含+ ([{'bbox': (287, 132, 398, 191)},+ {'bbox': (44, 141, 163, 188)},+ {'bbox': (132, 191, 240, 241)},+ {'bbox': (81, 25, 142, 67)},+ {'bbox': (74, 297, 116, 314)},+ {'bbox': (77, 84, 224, 107)}, ], (287, 132, 398, 191), None), # x没有重合+ ([{'bbox': (80, 90, 249, 200)},+ {'bbox': (183, 100, 240, 155)}, ], (183, 100, 240, 155), None), # 包含])def test_find_bottom_nearest_text_bbox(pymu_blocks: list, obj_box: tuple, target_boxs: dict) -> None:assert target_boxs == find_bottom_nearest_text_bbox(pymu_blocks, obj_box)# 寻找左侧距离自己最近的box, y方向有重叠,x方向最近[email protected]("pymu_blocks, obj_box, target_boxs", [- ([{"bbox": (80, 90, 249, 200)}, {"bbox": (183, 100, 240, 155)}], (183, 100, 240, 155), None), # 包含- ([{"bbox": (28, 90, 77, 126)}, {"bbox": (35, 84, 84, 120)}], (35, 84, 84, 120), None), # y:重叠,x:重叠大于2- ([{"bbox": (28, 90, 77, 126)}, {"bbox": (75, 84, 134, 120)}], (75, 84, 134, 120), {"bbox": (28, 90, 77, 126)}),[email protected]('pymu_blocks, obj_box, target_boxs', [+ ([{'bbox': (80, 90, 249, 200)}, {'bbox': (183, 100, 240, 155)}], (183, 100, 240, 155), None), # 包含+ ([{'bbox': (28, 90, 77, 126)}, {'bbox': (35, 84, 84, 120)}], (35, 84, 84, 120), None), # y:重叠,x:重叠大于2+ ([{'bbox': (28, 90, 77, 126)}, {'bbox': (75, 84, 134, 120)}], (75, 84, 134, 120), {'bbox': (28, 90, 77, 126)}),# y:重叠,x:重叠小于等于2- ([{"bbox": (239, 115, 379, 167)},- {"bbox": (33, 237, 104, 262)},- {"bbox": (124, 288, 168, 325)},- {"bbox": (242, 291, 379, 340)},- {"bbox": (55, 113, 161, 154)},- {"bbox": (266, 123, 384, 217)}], (266, 123, 384, 217), {"bbox": (55, 113, 161, 154)}), # y重叠,x left+ ([{'bbox': (239, 115, 379, 167)},+ {'bbox': (33, 237, 104, 262)},+ {'bbox': (124, 288, 168, 325)},+ {'bbox': (242, 291, 379, 340)},+ {'bbox': (55, 113, 161, 154)},+ {'bbox': (266, 123, 384, 217)}], (266, 123, 384, 217), {'bbox': (55, 113, 161, 154)}), # y重叠,x left# ([{"bbox": (136, 219, 268, 240)},# {"bbox": (169, 115, 268, 181)},# {"bbox": (33, 237, 104, 262)},@@ -448,17 +460,17 @@ def test_find_left_nearest_text_bbox(pymu_blocks: list, obj_box: tuple, target_b# 寻找右侧距离自己最近的box, y方向有重叠,x方向最近[email protected]("pymu_blocks, obj_box, target_boxs", [- ([{"bbox": (80, 90, 249, 200)}, {"bbox": (183, 100, 240, 155)}], (183, 100, 240, 155), None), # 包含- ([{"bbox": (28, 90, 77, 126)}, {"bbox": (35, 84, 84, 120)}], (28, 90, 77, 126), None), # y:重叠,x:重叠大于2- ([{"bbox": (28, 90, 77, 126)}, {"bbox": (75, 84, 134, 120)}], (28, 90, 77, 126), {"bbox": (75, 84, 134, 120)}),[email protected]('pymu_blocks, obj_box, target_boxs', [+ ([{'bbox': (80, 90, 249, 200)}, {'bbox': (183, 100, 240, 155)}], (183, 100, 240, 155), None), # 包含+ ([{'bbox': (28, 90, 77, 126)}, {'bbox': (35, 84, 84, 120)}], (28, 90, 77, 126), None), # y:重叠,x:重叠大于2+ ([{'bbox': (28, 90, 77, 126)}, {'bbox': (75, 84, 134, 120)}], (28, 90, 77, 126), {'bbox': (75, 84, 134, 120)}),# y:重叠,x:重叠小于等于2- ([{"bbox": (239, 115, 379, 167)},- {"bbox": (33, 237, 104, 262)},- {"bbox": (124, 288, 168, 325)},- {"bbox": (242, 291, 379, 340)},- {"bbox": (55, 113, 161, 154)},- {"bbox": (266, 123, 384, 217)}], (55, 113, 161, 154), {"bbox": (239, 115, 379, 167)}), # y重叠,x right+ ([{'bbox': (239, 115, 379, 167)},+ {'bbox': (33, 237, 104, 262)},+ {'bbox': (124, 288, 168, 325)},+ {'bbox': (242, 291, 379, 340)},+ {'bbox': (55, 113, 161, 154)},+ {'bbox': (266, 123, 384, 217)}], (55, 113, 161, 154), {'bbox': (239, 115, 379, 167)}), # y重叠,x right# ([{"bbox": (169, 115, 298, 181)},# {"bbox": (169, 219, 268, 240)},# {"bbox": (33, 177, 104, 262)},@@ -472,7 +484,7 @@ def test_find_right_nearest_text_bbox(pymu_blocks: list, obj_box: tuple, target_# 判断两个矩形框的相对位置关系 (left, right, bottom, top)[email protected]("box1, box2, target_box", [[email protected]('box1, box2, target_box', [# (None, None, "Error"), # Error((80, 90, 249, 200), (183, 100, 240, 155), (False, False, False, False)), # 包含# ((124, 81, 222, 173), (60, 221, 123, 358), (False, True, False, True)), # 分离,右上 Error@@ -494,7 +506,7 @@ def test_bbox_relative_pos(box1: tuple, box2: tuple, target_box: tuple) -> None:"""[email protected]("box1, box2, target_num", [[email protected]('box1, box2, target_num', [# (None, None, "Error"), # Error((80, 90, 249, 200), (183, 100, 240, 155), 0.0), # 包含((142, 109, 238, 164), (134, 211, 224, 270), 47.0), # 分离,上@@ -514,17 +526,17 @@ def test_bbox_relative_pos(box1: tuple, box2: tuple, target_box: tuple) -> None:def test_bbox_distance(box1: tuple, box2: tuple, target_num: float) -> None:assert target_num - bbox_distance(box1, box2) < 1[email protected](reason="skip")+[email protected](reason='skip')# 根据bucket_name获取s3配置ak,sk,endpointdef test_get_s3_config() -> None:- bucket_name = os.getenv('bucket_name')+ bucket_name = os.getenv('bucket_name')target_data = os.getenv('target_data')assert convert_string_to_list(target_data) == list(get_s3_config(bucket_name))--def convert_string_to_list(s):- cleaned_s = s.strip("'")- items = cleaned_s.split(',')- cleaned_items = [item.strip() for item in items]- return cleaned_items\ No newline at end of file+def convert_string_to_list(s):+ cleaned_s = s.strip("'")+ items = cleaned_s.split(',')+ cleaned_items = [item.strip() for item in items]+ return cleaned_items