文本方向分类优化&更新版面分析模型
@ -0,0 +1,57 @@
|
||||
from typing import List
|
||||
import cv2
|
||||
from pdf_detection import Pipeline
|
||||
import pickle
|
||||
|
||||
|
||||
class LayoutBox(object):
|
||||
def __init__(self, clsid: int, pos: List[float], confidence: float):
|
||||
self.clsid = clsid
|
||||
self.pos = pos
|
||||
self.confidence = confidence
|
||||
|
||||
|
||||
class PageDetectionResult(object):
|
||||
def __init__(self, boxes: List[LayoutBox], image_path: str):
|
||||
self.boxes = boxes
|
||||
self.image_path = image_path
|
||||
|
||||
pipeline = Pipeline('/mnt/pdf2markdown/models/PaddleDetection/inference_model/picodet_lcnet_x1_0_fgd_layout_cdla_infer')
|
||||
|
||||
|
||||
def page_detection_visual(page_detection_result: PageDetectionResult):
|
||||
img = cv2.imread(page_detection_result.image_path)
|
||||
for box in page_detection_result.boxes:
|
||||
pos = box.pos
|
||||
clsid = box.clsid
|
||||
confidence = box.confidence
|
||||
if clsid == 0:
|
||||
color = (0, 0, 0)
|
||||
text = 'text'
|
||||
elif clsid == 1:
|
||||
color = (255, 0, 0)
|
||||
text = 'title'
|
||||
elif clsid == 2:
|
||||
color = (0, 255, 0)
|
||||
text = 'figure'
|
||||
elif clsid == 4:
|
||||
color = (0, 0, 255)
|
||||
text = 'table'
|
||||
if clsid == 5:
|
||||
color = (255, 0, 255)
|
||||
text = 'table caption'
|
||||
text = f'{text} {confidence}'
|
||||
img = cv2.rectangle(img, (int(pos[0]), int(pos[1])), (int(pos[2]), int(pos[3])), color, 2)
|
||||
cv2.putText(img, text, (int(pos[0]), int(pos[1])), cv2.FONT_HERSHEY_TRIPLEX, 1, color, 2)
|
||||
return img
|
||||
|
||||
img_path = '/mnt/research/PaddleOCR/PaddleDetection/datasets/train_output/JPEGImages/0090.jpg'
|
||||
page_detecion_outputs = pipeline(img_path)
|
||||
boxes = []
|
||||
for output in page_detecion_outputs:
|
||||
boxes.append(LayoutBox(output[0], output[1], output[2]))
|
||||
res = PageDetectionResult(boxes, img_path)
|
||||
with open('/mnt/pdf2markdown/a.pkl', 'wb') as f:
|
||||
pickle.dump(res, f)
|
||||
# img = page_detection_visual(res)
|
||||
# cv2.imwrite('/mnt/pdf2markdown/0122.jpg', img)
|
@ -1,39 +0,0 @@
|
||||
mode: paddle
|
||||
draw_threshold: 0.5
|
||||
metric: COCO
|
||||
use_dynamic_shape: false
|
||||
arch: PicoDet
|
||||
min_subgraph_size: 3
|
||||
Preprocess:
|
||||
- interp: 2
|
||||
keep_ratio: false
|
||||
target_size:
|
||||
- 800
|
||||
- 608
|
||||
type: Resize
|
||||
- is_scale: true
|
||||
mean:
|
||||
- 0.485
|
||||
- 0.456
|
||||
- 0.406
|
||||
std:
|
||||
- 0.229
|
||||
- 0.224
|
||||
- 0.225
|
||||
type: NormalizeImage
|
||||
- type: Permute
|
||||
- stride: 32
|
||||
type: PadStride
|
||||
label_list:
|
||||
- table
|
||||
NMS:
|
||||
keep_top_k: 100
|
||||
name: MultiClassNMS
|
||||
nms_threshold: 0.5
|
||||
nms_top_k: 1000
|
||||
score_threshold: 0.3
|
||||
fpn_stride:
|
||||
- 8
|
||||
- 16
|
||||
- 32
|
||||
- 64
|
@ -1,43 +0,0 @@
|
||||
mode: paddle
|
||||
draw_threshold: 0.5
|
||||
metric: COCO
|
||||
use_dynamic_shape: false
|
||||
arch: PicoDet
|
||||
min_subgraph_size: 3
|
||||
Preprocess:
|
||||
- interp: 2
|
||||
keep_ratio: false
|
||||
target_size:
|
||||
- 800
|
||||
- 608
|
||||
type: Resize
|
||||
- is_scale: true
|
||||
mean:
|
||||
- 0.485
|
||||
- 0.456
|
||||
- 0.406
|
||||
std:
|
||||
- 0.229
|
||||
- 0.224
|
||||
- 0.225
|
||||
type: NormalizeImage
|
||||
- type: Permute
|
||||
- stride: 32
|
||||
type: PadStride
|
||||
label_list:
|
||||
- text
|
||||
- title
|
||||
- list
|
||||
- table
|
||||
- figure
|
||||
NMS:
|
||||
keep_top_k: 100
|
||||
name: MultiClassNMS
|
||||
nms_threshold: 0.5
|
||||
nms_top_k: 1000
|
||||
score_threshold: 0.3
|
||||
fpn_stride:
|
||||
- 8
|
||||
- 16
|
||||
- 32
|
||||
- 64
|
@ -0,0 +1,5 @@
|
||||
*.js linguist-vendored
|
||||
*.mjs linguist-vendored
|
||||
*.html linguist-documentation
|
||||
*.css linguist-vendored
|
||||
*.scss linguist-vendored
|
@ -0,0 +1,11 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: 🙏 Q&A
|
||||
url: https://github.com/opendatalab/MinerU/discussions/categories/q-a
|
||||
about: Ask the community for help
|
||||
- name: 💡 Feature requests and ideas
|
||||
url: https://github.com/opendatalab/MinerU/discussions/categories/ideas
|
||||
about: Share ideas for new features
|
||||
- name: 🙌 Show and tell
|
||||
url: https://github.com/opendatalab/MinerU/discussions/categories/show-and-tell
|
||||
about: Show off something you've made
|
@ -0,0 +1,32 @@
|
||||
Thanks for your contribution and we appreciate it a lot. The following instructions would make your pull request more healthy and more easily get feedback. If you do not understand some items, don't worry, just make the pull request and seek help from maintainers.
|
||||
|
||||
## Motivation
|
||||
|
||||
Please describe the motivation of this PR and the goal you want to achieve through this PR.
|
||||
|
||||
## Modification
|
||||
|
||||
Please briefly describe what modification is made in this PR.
|
||||
|
||||
## BC-breaking (Optional)
|
||||
|
||||
Does the modification introduce changes that break the backward compatibility of the downstream repositories?
|
||||
If so, please describe how it breaks the compatibility and how the downstream projects should modify their code to keep compatibility with this PR.
|
||||
|
||||
## Use cases (Optional)
|
||||
|
||||
If this PR introduces a new feature, it is better to list some use cases here and update the documentation.
|
||||
|
||||
## Checklist
|
||||
|
||||
**Before PR**:
|
||||
|
||||
- [ ] Pre-commit or other linting tools are used to fix the potential lint issues.
|
||||
- [ ] Bug fixes are fully covered by unit tests, the case that causes the bug should be added in the unit tests.
|
||||
- [ ] The modification is covered by complete unit tests. If not, please add more unit test to ensure the correctness.
|
||||
- [ ] The documentation has been modified accordingly, like docstring or example tutorials.
|
||||
|
||||
**After PR**:
|
||||
|
||||
- [ ] If the modification has potential influence on downstream or other related projects, this PR should be tested with those projects.
|
||||
- [ ] CLA has been signed and all committers have signed the CLA in this PR.
|
@ -0,0 +1,43 @@
|
||||
name: "MinerU CLA Assistant"
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_target:
|
||||
types: [opened,closed,synchronize]
|
||||
|
||||
# explicitly configure permissions, in case your GITHUB_TOKEN workflow permissions are set to read-only in repository settings
|
||||
permissions:
|
||||
actions: write
|
||||
contents: write # this can be 'read' if the signatures are in remote repository
|
||||
pull-requests: write
|
||||
statuses: write
|
||||
|
||||
jobs:
|
||||
CLAAssistant:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: "CLA Assistant"
|
||||
if: (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') || github.event_name == 'pull_request_target'
|
||||
uses: contributor-assistant/github-action@v2.5.0
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
# the below token should have repo scope and must be manually added by you in the repository's secret
|
||||
# This token is required only if you have configured to store the signatures in a remote repository/organization
|
||||
PERSONAL_ACCESS_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
with:
|
||||
path-to-signatures: 'signatures/version1/cla.json'
|
||||
path-to-document: 'https://github.com/opendatalab/MinerU/blob/master/MinerU_CLA.md' # e.g. a CLA or a DCO document
|
||||
# branch should not be protected
|
||||
branch: 'master'
|
||||
allowlist: myhloli,dt-yy,Focusshang,renpengli01,icecraft,drunkpig,wangbinDL,qiangqiang199,GDDGCZ518,papayalove,conghui,quyuan,LollipopsAndWine
|
||||
|
||||
# the followings are the optional inputs - If the optional inputs are not given, then default values will be taken
|
||||
#remote-organization-name: enter the remote organization name where the signatures should be stored (Default is storing the signatures in the same repository)
|
||||
#remote-repository-name: enter the remote repository name where the signatures should be stored (Default is storing the signatures in the same repository)
|
||||
#create-file-commit-message: 'For example: Creating file for storing CLA Signatures'
|
||||
#signed-commit-message: 'For example: $contributorName has signed the CLA in $owner/$repo#$pullRequestNo'
|
||||
#custom-notsigned-prcomment: 'pull request comment with Introductory message to ask new contributors to sign'
|
||||
#custom-pr-sign-comment: 'The signature to be committed in order to sign the CLA'
|
||||
#custom-allsigned-prcomment: 'pull request comment when all contributors has signed, defaults to **CLA Assistant Lite bot** All Contributors have signed the CLA.'
|
||||
#lock-pullrequest-aftermerge: false - if you don't want this bot to automatically lock the pull request after merging (default - true)
|
||||
#use-dco-flag: true - If you are using DCO instead of CLA
|
@ -0,0 +1,46 @@
|
||||
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
|
||||
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python
|
||||
|
||||
name: mineru
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- "master"
|
||||
- "dev"
|
||||
paths-ignore:
|
||||
- "cmds/**"
|
||||
- "**.md"
|
||||
workflow_dispatch:
|
||||
jobs:
|
||||
cli-test:
|
||||
if: github.repository == 'opendatalab/MinerU'
|
||||
runs-on: pdf
|
||||
timeout-minutes: 240
|
||||
strategy:
|
||||
fail-fast: true
|
||||
|
||||
steps:
|
||||
- name: PDF cli
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 2
|
||||
|
||||
- name: install&test
|
||||
run: |
|
||||
source activate mineru
|
||||
conda env list
|
||||
pip show coverage
|
||||
cd $GITHUB_WORKSPACE && sh tests/retry_env.sh
|
||||
cd $GITHUB_WORKSPACE && python tests/clean_coverage.py
|
||||
cd $GITHUB_WORKSPACE && coverage run -m pytest tests/unittest/ --cov=magic_pdf/ --cov-report html --cov-report term-missing
|
||||
cd $GITHUB_WORKSPACE && python tests/get_coverage.py
|
||||
cd $GITHUB_WORKSPACE && pytest -m P0 -s -v tests/test_cli/test_cli_sdk.py
|
||||
|
||||
notify_to_feishu:
|
||||
if: ${{ always() && !cancelled() && contains(needs.*.result, 'failure')}}
|
||||
needs: cli-test
|
||||
runs-on: pdf
|
||||
steps:
|
||||
- name: notify
|
||||
run: |
|
||||
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":"'$USER_ID'"}]]}}}}' $WEBHOOK_URL
|
@ -0,0 +1,61 @@
|
||||
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
|
||||
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python
|
||||
|
||||
name: mineru
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- "master"
|
||||
- "dev"
|
||||
paths-ignore:
|
||||
- "cmds/**"
|
||||
- "**.md"
|
||||
jobs:
|
||||
cli-test:
|
||||
if: github.repository == 'opendatalab/MinerU'
|
||||
runs-on: pdf
|
||||
timeout-minutes: 240
|
||||
strategy:
|
||||
fail-fast: true
|
||||
|
||||
steps:
|
||||
- name: PDF cli
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 2
|
||||
|
||||
- name: install&test
|
||||
run: |
|
||||
source activate mineru
|
||||
conda env list
|
||||
pip show coverage
|
||||
cd $GITHUB_WORKSPACE && sh tests/retry_env.sh
|
||||
cd $GITHUB_WORKSPACE && python tests/clean_coverage.py
|
||||
cd $GITHUB_WORKSPACE && coverage run -m pytest tests/unittest/ --cov=magic_pdf/ --cov-report html --cov-report term-missing
|
||||
cd $GITHUB_WORKSPACE && python tests/get_coverage.py
|
||||
cd $GITHUB_WORKSPACE && pytest -s -v tests/test_cli/test_cli_sdk.py
|
||||
|
||||
notify_to_feishu:
|
||||
if: ${{ always() && !cancelled() && contains(needs.*.result, 'failure')}}
|
||||
needs: cli-test
|
||||
runs-on: pdf
|
||||
steps:
|
||||
- name: get_actor
|
||||
run: |
|
||||
metion_list="dt-yy"
|
||||
echo $GITHUB_ACTOR
|
||||
if [[ $GITHUB_ACTOR == "drunkpig" ]]; then
|
||||
metion_list="xuchao"
|
||||
elif [[ $GITHUB_ACTOR == "myhloli" ]]; then
|
||||
metion_list="zhaoxiaomeng"
|
||||
elif [[ $GITHUB_ACTOR == "icecraft" ]]; then
|
||||
metion_list="xurui1"
|
||||
fi
|
||||
echo $metion_list
|
||||
echo "METIONS=$metion_list" >> "$GITHUB_ENV"
|
||||
echo ${{ env.METIONS }}
|
||||
|
||||
- name: notify
|
||||
run: |
|
||||
#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":"'$USER_ID'"}]]}}}}' $WEBHOOK_URL
|
@ -0,0 +1,143 @@
|
||||
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
|
||||
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python
|
||||
|
||||
name: Python package
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*released'
|
||||
workflow_dispatch:
|
||||
|
||||
|
||||
jobs:
|
||||
|
||||
update-version:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: master
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.10"
|
||||
|
||||
- name: Update version.py
|
||||
run: |
|
||||
python update_version.py
|
||||
|
||||
- name: Verify version.py
|
||||
run: |
|
||||
ls -l magic_pdf/libs/version.py
|
||||
cat magic_pdf/libs/version.py
|
||||
|
||||
- name: Commit changes
|
||||
run: |
|
||||
git config --local user.email "moe@myhloli.com"
|
||||
git config --local user.name "myhloli"
|
||||
git add magic_pdf/libs/version.py
|
||||
if git diff-index --quiet HEAD; then
|
||||
echo "No changes to commit"
|
||||
else
|
||||
git commit -m "Update version.py with new version"
|
||||
fi
|
||||
id: commit_changes
|
||||
|
||||
- name: Push changes
|
||||
if: steps.commit_changes.outcome == 'success'
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
run: |
|
||||
git push origin HEAD:master
|
||||
|
||||
check-install:
|
||||
needs: [ update-version ]
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: master
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Verify version.py
|
||||
run: |
|
||||
ls -l magic_pdf/libs/version.py
|
||||
cat magic_pdf/libs/version.py
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Install magic-pdf
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -e .[full]
|
||||
|
||||
build:
|
||||
needs: [ check-install ]
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: [ "3.10"]
|
||||
|
||||
steps:
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: master
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install wheel
|
||||
run: |
|
||||
python -m pip install wheel
|
||||
|
||||
- name: Build wheel
|
||||
run: |
|
||||
python setup.py bdist_wheel
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: wheel-file
|
||||
path: dist/*.whl
|
||||
retention-days: 30
|
||||
|
||||
release:
|
||||
needs: [ build ]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Download artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: wheel-file
|
||||
path: dist
|
||||
|
||||
- name: Create and Upload Release
|
||||
id: create_release
|
||||
uses: softprops/action-gh-release@4634c16e79c963813287e889244c50009e7f0981
|
||||
with:
|
||||
files: './dist/*.whl'
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
|
||||
- name: Publish distribution to PyPI
|
||||
run: |
|
||||
pip install -U twine id keyring packaging readme-renderer requests requests-toolbelt rfc3986 rich urllib3
|
||||
twine check dist/*
|
||||
twine upload dist/* -u __token__ -p ${{ secrets.PYPI_TOKEN }}
|
@ -0,0 +1,23 @@
|
||||
name: check-status
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [ci]
|
||||
types: [completed]
|
||||
|
||||
jobs:
|
||||
on-failure:
|
||||
runs-on: pdf
|
||||
permissions:
|
||||
actions: write
|
||||
if: ${{ (github.event.workflow_run.head_branch == 'master') && github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.run_attempt < 3 }}
|
||||
steps:
|
||||
- run: |
|
||||
echo 'The triggering workflow failed'
|
||||
sleep 600
|
||||
curl -L \
|
||||
-X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer ${{ github.token }}" \
|
||||
-H "X-GitHub-Api-Version: 2022-11-28" \
|
||||
https://api.github.com/repos/${{ github.repository }}/actions/runs/${{ github.event.workflow_run.id }}/rerun-failed-jobs
|
@ -0,0 +1,53 @@
|
||||
*.tar
|
||||
*.tar.gz
|
||||
*.zip
|
||||
venv*/
|
||||
envs/
|
||||
slurm_logs/
|
||||
|
||||
sync1.sh
|
||||
data_preprocess_pj1
|
||||
data-preparation1
|
||||
__pycache__
|
||||
*.log
|
||||
*.pyc
|
||||
.vscode
|
||||
debug/
|
||||
*.ipynb
|
||||
.idea
|
||||
|
||||
# vscode history
|
||||
.history
|
||||
|
||||
.DS_Store
|
||||
.env
|
||||
|
||||
bad_words/
|
||||
bak/
|
||||
|
||||
app/tests/*
|
||||
temp/
|
||||
tmp/
|
||||
tmp
|
||||
.vscode
|
||||
.vscode/
|
||||
ocr_demo
|
||||
.coveragerc
|
||||
/app/common/__init__.py
|
||||
/magic_pdf/config/__init__.py
|
||||
source.dev.env
|
||||
|
||||
tmp
|
||||
|
||||
projects/web/node_modules
|
||||
projects/web/dist
|
||||
|
||||
projects/web_demo/web_demo/static/
|
||||
cli_debug/
|
||||
debug_utils/
|
||||
|
||||
# sphinx docs
|
||||
_build/
|
||||
|
||||
|
||||
output/
|
@ -0,0 +1,47 @@
|
||||
repos:
|
||||
- repo: https://github.com/PyCQA/flake8
|
||||
rev: 5.0.4
|
||||
hooks:
|
||||
- id: flake8
|
||||
args: ["--max-line-length=150", "--ignore=E131,E125,W503,W504,E203"]
|
||||
- repo: https://github.com/PyCQA/isort
|
||||
rev: 5.11.5
|
||||
hooks:
|
||||
- id: isort
|
||||
- repo: https://github.com/pre-commit/mirrors-yapf
|
||||
rev: v0.32.0
|
||||
hooks:
|
||||
- id: yapf
|
||||
args: ["--style={based_on_style: google, column_limit: 150, indent_width: 4}"]
|
||||
- repo: https://github.com/codespell-project/codespell
|
||||
rev: v2.2.1
|
||||
hooks:
|
||||
- id: codespell
|
||||
args: ['--skip', '*.json']
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.3.0
|
||||
hooks:
|
||||
- id: trailing-whitespace
|
||||
- id: check-yaml
|
||||
- id: end-of-file-fixer
|
||||
- id: requirements-txt-fixer
|
||||
- id: double-quote-string-fixer
|
||||
- id: check-merge-conflict
|
||||
- id: fix-encoding-pragma
|
||||
args: ["--remove"]
|
||||
- id: mixed-line-ending
|
||||
args: ["--fix=lf"]
|
||||
- repo: https://github.com/executablebooks/mdformat
|
||||
rev: 0.7.9
|
||||
hooks:
|
||||
- id: mdformat
|
||||
args: ["--number", "--table-width", "200"]
|
||||
additional_dependencies:
|
||||
- mdformat-openmmlab
|
||||
- mdformat_frontmatter
|
||||
- linkify-it-py
|
||||
- repo: https://github.com/myint/docformatter
|
||||
rev: v1.3.1
|
||||
hooks:
|
||||
- id: docformatter
|
||||
args: ["--in-place", "--wrap-descriptions", "119"]
|
@ -0,0 +1,16 @@
|
||||
version: 2
|
||||
|
||||
build:
|
||||
os: ubuntu-22.04
|
||||
tools:
|
||||
python: "3.10"
|
||||
|
||||
formats:
|
||||
- epub
|
||||
|
||||
python:
|
||||
install:
|
||||
- requirements: next_docs/zh_cn/requirements.txt
|
||||
|
||||
sphinx:
|
||||
configuration: next_docs/zh_cn/conf.py
|
@ -0,0 +1,662 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
@ -0,0 +1,14 @@
|
||||
# MinerU Contributor License Agreement
|
||||
In order to clarify the intellectual property license granted with Contributions from any person or entity, the open source project MinerU ("MinerU") must have a Contributor License Agreement (CLA) on file that has been signed by each Contributor, indicating agreement to the license terms below. This license is for your protection as a Contributor as well as the protection of MinerU and its users; it does not change your rights to use your own Contributions for any other purpose.
|
||||
|
||||
You accept and agree to the following terms and conditions for Your present and future Contributions submitted to MinerU. Except for the license granted herein to MinerU and recipients of software distributed by MinerU, You reserve all right, title, and interest in and to Your Contributions.
|
||||
|
||||
1. Definitions. "You" (or "Your") shall mean the copyright owner or legal entity authorized by the copyright owner that is making this Agreement with MinerU. For legal entities, the entity making a Contribution and all other entities that control, are controlled by, or are under common control with that entity are considered to be a single Contributor. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "Contribution" shall mean the code, documentation or any original work of authorship, including any modifications or additions to an existing work, that is intentionally submitted by You to MinerU for inclusion in, or documentation of, any of the products owned or managed by MinerU (the "Work"). For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to MinerU or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, MinerU for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution."
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this Agreement, You hereby grant to MinerU and to recipients of software distributed by MinerU a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute Your Contributions and such derivative works.
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this Agreement, You hereby grant to MinerU and to recipients of software distributed by MinerU a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by You that are necessarily infringed by Your Contribution(s) alone or by combination of Your Contribution(s) with the Work to which such Contribution(s) was submitted. If any entity institutes patent litigation against You or any other entity (including a cross-claim or counterclaim in a lawsuit) alleging that Your Contribution, or the Work to which You have contributed, constitutes direct or contributory patent infringement, then any patent licenses granted to that entity under this Agreement for that Contribution or Work shall terminate as of the date such litigation is filed.
|
||||
4. You represent that You are legally entitled to grant the above license. If You are an entity, You represent further that each of Your employee designated by You is authorized to submit Contributions on behalf of You. If You are an individual and Your employer(s) has rights to intellectual property that You create that includes Your Contributions, You represent further that You have received permission to make Contributions on behalf of that employer, that Your employer has waived such rights for Your Contributions to MinerU, or that Your employer has executed a separate CLA with MinerU.
|
||||
5. If you do post content or submit material on MinerU and unless we indicate otherwise, you grant MinerU a nonexclusive, royalty-free, perpetual, irrevocable, and fully sublicensable right to use, reproduce, modify, adapt, publish, perform, translate, create derivative works from, distribute, and display such content throughout the world in any media. You grant MinerU and sublicensees the right to use your GitHub Public Profile, including but not limited to name, that you submit in connection with such content. You represent and warrant that you own or otherwise control all of the rights to the content that you post; that the content is accurate; that use of the content you supply does not violate this policy and will not cause injury to any person or entity; and that you will indemnify MinerU for all claims resulting from content you supply. MinerU has the right but not the obligation to monitor and edit or remove any activity or content. MinerU takes no responsibility and assumes no liability for any content posted by you or any third party.
|
||||
6. You represent that each of Your Contributions is Your original creation. Should You wish to submit work that is not Your original creation, You may submit it to MinerU separately from any Contribution, identifying the complete details of its source and of any license or other restriction (including, but not limited to, related patents, trademarks, and license agreements) of which You are personally aware, and conspicuously marking the work as "Submitted on behalf of a third-party: [named here]".
|
||||
7. You are not expected to provide support for Your Contributions, except to the extent You desire to provide support. You may provide support for free, for a fee, or not at all. Unless required by applicable law or agreed to in writing, You provide Your Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
8. You agree to notify MinerU of any facts or circumstances of which You become aware that would make these representations inaccurate in any respect.
|
||||
9. MinerU reserves the right to update or change this Agreement at any time, by posting the most current version of the Agreement on MinerU, with a new Effective Date shown on Jul. 24th, 2024. All such changes in the Agreement are effective from the Effective Date. Your continued use of MinerU after we post any such changes signifies your agreement to those changes. If you do not agree to the then-current Agreement, you must immediately discontinue using MinerU.
|
@ -0,0 +1,604 @@
|
||||
<div align="center" xmlns="http://www.w3.org/1999/html">
|
||||
<!-- logo -->
|
||||
<p align="center">
|
||||
<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)
|
||||
[](https://github.com/opendatalab/MinerU/issues)
|
||||
[](https://pypi.org/project/magic-pdf/)
|
||||
[](https://pypi.org/project/magic-pdf/)
|
||||
[](https://pepy.tech/project/magic-pdf)
|
||||
[](https://pepy.tech/project/magic-pdf)
|
||||
|
||||
[](https://mineru.net/OpenSourceTools/Extractor?source=github)
|
||||
[](https://huggingface.co/spaces/opendatalab/MinerU)
|
||||
[](https://www.modelscope.cn/studios/OpenDataLab/MinerU)
|
||||
[](https://colab.research.google.com/gist/myhloli/3b3a00a4a0a61577b6c30f989092d20d/mineru_demo.ipynb)
|
||||
[](https://arxiv.org/abs/2409.18839)
|
||||
|
||||
|
||||
<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>🔥🔥🔥
|
||||
<br>
|
||||
<br>
|
||||
<a href="https://mineru.net/client?source=github">
|
||||
Easier to use: Just grab MinerU Desktop. No coding, no login, just a simple interface and smooth interactions. Enjoy it without any fuss!</a>🚀🚀🚀
|
||||
|
||||
</p>
|
||||
|
||||
<!-- join us -->
|
||||
|
||||
<p align="center">
|
||||
👋 join us on <a href="https://discord.gg/Tdedn9GTXq" target="_blank">Discord</a> and <a href="http://mineru.space/s/V85Yl" target="_blank">WeChat</a>
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
# Changelog
|
||||
- 2025/04/29 1.3.10 Released
|
||||
- Support for custom formula delimiters can be achieved by modifying the `latex-delimiter-config` item in the `magic-pdf.json` file under the user directory.
|
||||
- 2025/04/27 1.3.9 Released
|
||||
- Optimized the formula parsing function to improve the success rate of formula rendering
|
||||
- 2025/04/23 1.3.8 Released
|
||||
- The default `ocr` model (`ch`) has been updated to `PP-OCRv4_server_rec_doc` (model update required)
|
||||
- `PP-OCRv4_server_rec_doc` is trained on a mix of more Chinese document data and PP-OCR training data, enhancing recognition capabilities for some traditional Chinese characters, Japanese, and special characters. It supports over 15,000 recognizable characters, improving text recognition in documents while also boosting general text recognition.
|
||||
- [Performance comparison between PP-OCRv4_server_rec_doc, PP-OCRv4_server_rec, and PP-OCRv4_mobile_rec](https://paddlepaddle.github.io/PaddleX/latest/en/module_usage/tutorials/ocr_modules/text_recognition.html#ii-supported-model-list)
|
||||
- Verified results show that the `PP-OCRv4_server_rec_doc` model significantly improves accuracy in both single-language (`Chinese`, `English`, `Japanese`, `Traditional Chinese`) and mixed-language scenarios, with speed comparable to `PP-OCRv4_server_rec`, making it suitable for most use cases.
|
||||
- In a small number of pure English scenarios, the `PP-OCRv4_server_rec_doc` model may encounter word concatenation issues, whereas `PP-OCRv4_server_rec` performs better in such cases. Therefore, we have retained the `PP-OCRv4_server_rec` model, which users can invoke by passing the parameter `lang='ch_server'`(python api) or `--lang ch_server`(cli).
|
||||
- 2025/04/22 1.3.7 Released
|
||||
- Fixed the issue where the `lang` parameter was ineffective during table parsing model initialization.
|
||||
- Fixed the significant slowdown in OCR and table parsing speed in `cpu` mode.
|
||||
- 2025/04/16 1.3.4 Released
|
||||
- Slightly improved the speed of OCR detection by removing some unused blocks.
|
||||
- Fixed page-level sorting errors caused by footnotes in certain cases.
|
||||
- 2025/04/12 1.3.2 released
|
||||
- Fixed the issue of incompatible dependency package versions when installing in Python 3.13 environment on Windows systems.
|
||||
- Optimized memory usage during batch inference.
|
||||
- Improved the parsing effect of tables rotated by 90 degrees.
|
||||
- Enhanced the parsing accuracy for large tables in financial report samples.
|
||||
- Fixed the occasional word concatenation issue in English text areas when OCR language is not specified.(The model needs to be updated)
|
||||
- 2025/04/08 1.3.1 released, fixed some compatibility issues
|
||||
- Supported Python 3.13
|
||||
- Made the final adaptation for some outdated Linux systems (e.g., CentOS 7), and no further support will be guaranteed for subsequent versions. [Installation Instructions](https://github.com/opendatalab/MinerU/issues/1004)
|
||||
- 2025/04/03 1.3.0 released, in this version we made many optimizations and improvements:
|
||||
- Installation and compatibility optimization
|
||||
- By removing the use of `layoutlmv3` in layout, resolved compatibility issues caused by `detectron2`.
|
||||
- Torch version compatibility extended to 2.2~2.6 (excluding 2.5).
|
||||
- CUDA compatibility supports 11.8/12.4/12.6/12.8 (CUDA version determined by torch), resolving compatibility issues for some users with 50-series and H-series GPUs.
|
||||
- Python compatible versions expanded to 3.10~3.12, solving the problem of automatic downgrade to 0.6.1 during installation in non-3.10 environments.
|
||||
- Offline deployment process optimized; no internet connection required after successful deployment to download any model files.
|
||||
- Performance optimization
|
||||
- By supporting batch processing of multiple PDF files ([script example](demo/batch_demo.py)), improved parsing speed for small files in batches (compared to version 1.0.1, formula parsing speed increased by over 1400%, overall parsing speed increased by over 500%).
|
||||
- Optimized loading and usage of the mfr model, reducing GPU memory usage and improving parsing speed (requires re-execution of the [model download process](docs/how_to_download_models_en.md) to obtain incremental updates of model files).
|
||||
- Optimized GPU memory usage, requiring only a minimum of 6GB to run this project.
|
||||
- Improved running speed on MPS devices.
|
||||
- Parsing effect optimization
|
||||
- Updated the mfr model to `unimernet(2503)`, solving the issue of lost line breaks in multi-line formulas.
|
||||
- Usability Optimization
|
||||
- By using `paddleocr2torch`, completely replaced the use of the `paddle` framework and `paddleocr` in the project, resolving conflicts between `paddle` and `torch`, as well as thread safety issues caused by the `paddle` framework.
|
||||
- Added a real-time progress bar during the parsing process to accurately track progress, making the wait less painful.
|
||||
<details>
|
||||
<summary>2025/03/03 1.2.1 released</summary>
|
||||
<ul>
|
||||
<li>Fixed the impact on punctuation marks during full-width to half-width conversion of letters and numbers</li>
|
||||
<li>Fixed caption matching inaccuracies in certain scenarios</li>
|
||||
<li>Fixed formula span loss issues in certain scenarios</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2025/02/24 1.2.0 released</summary>
|
||||
<p>This version includes several fixes and improvements to enhance parsing efficiency and accuracy:</p>
|
||||
<ul>
|
||||
<li><strong>Performance Optimization</strong>
|
||||
<ul>
|
||||
<li>Increased classification speed for PDF documents in auto mode.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><strong>Parsing Optimization</strong>
|
||||
<ul>
|
||||
<li>Improved parsing logic for documents containing watermarks, significantly enhancing the parsing results for such documents.</li>
|
||||
<li>Enhanced the matching logic for multiple images/tables and captions within a single page, improving the accuracy of image-text matching in complex layouts.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><strong>Bug Fixes</strong>
|
||||
<ul>
|
||||
<li>Fixed an issue where image/table spans were incorrectly filled into text blocks under certain conditions.</li>
|
||||
<li>Resolved an issue where title blocks were empty in some cases.</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2025/01/22 1.1.0 released</summary>
|
||||
<p>In this version we have focused on improving parsing accuracy and efficiency:</p>
|
||||
<ul>
|
||||
<li><strong>Model capability upgrade</strong> (requires re-executing the <a href="https://github.com/opendatalab/MinerU/blob/master/docs/how_to_download_models_en.md">model download process</a> to obtain incremental updates of model files)
|
||||
<ul>
|
||||
<li>The layout recognition model has been upgraded to the latest <code>doclayout_yolo(2501)</code> model, improving layout recognition accuracy.</li>
|
||||
<li>The formula parsing model has been upgraded to the latest <code>unimernet(2501)</code> model, improving formula recognition accuracy.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><strong>Performance optimization</strong>
|
||||
<ul>
|
||||
<li>On devices that meet certain configuration requirements (16GB+ VRAM), by optimizing resource usage and restructuring the processing pipeline, overall parsing speed has been increased by more than 50%.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><strong>Parsing effect optimization</strong>
|
||||
<ul>
|
||||
<li>Added a new heading classification feature (testing version, enabled by default) to the online demo (<a href="https://mineru.net/OpenSourceTools/Extractor">mineru.net</a>/<a href="https://huggingface.co/spaces/opendatalab/MinerU">huggingface</a>/<a href="https://www.modelscope.cn/studios/OpenDataLab/MinerU">modelscope</a>), which supports hierarchical classification of headings, thereby enhancing document structuring.</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2025/01/10 1.0.1 released</summary>
|
||||
<p>This is our first official release, where we have introduced a completely new API interface and enhanced compatibility through extensive refactoring, as well as a brand new automatic language identification feature:</p>
|
||||
<ul>
|
||||
<li><strong>New API Interface</strong>
|
||||
<ul>
|
||||
<li>For the data-side API, we have introduced the Dataset class, designed to provide a robust and flexible data processing framework. This framework currently supports a variety of document formats, including images (.jpg and .png), PDFs, Word documents (.doc and .docx), and PowerPoint presentations (.ppt and .pptx). It ensures effective support for data processing tasks ranging from simple to complex.</li>
|
||||
<li>For the user-side API, we have meticulously designed the MinerU processing workflow as a series of composable Stages. Each Stage represents a specific processing step, allowing users to define new Stages according to their needs and creatively combine these stages to customize their data processing workflows.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><strong>Enhanced Compatibility</strong>
|
||||
<ul>
|
||||
<li>By optimizing the dependency environment and configuration items, we ensure stable and efficient operation on ARM architecture Linux systems.</li>
|
||||
<li>We have deeply integrated with Huawei Ascend NPU acceleration, providing autonomous and controllable high-performance computing capabilities. This supports the localization and development of AI application platforms in China. <a href="https://github.com/opendatalab/MinerU/blob/master/docs/README_Ascend_NPU_Acceleration_zh_CN.md">Ascend NPU Acceleration</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><strong>Automatic Language Identification</strong>
|
||||
<ul>
|
||||
<li>By introducing a new language recognition model, setting the <code>lang</code> configuration to <code>auto</code> during document parsing will automatically select the appropriate OCR language model, improving the accuracy of scanned document parsing.</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/11/22 0.10.0 released</summary>
|
||||
<p>Introducing hybrid OCR text extraction capabilities:</p>
|
||||
<ul>
|
||||
<li>Significantly improved parsing performance in complex text distribution scenarios such as dense formulas, irregular span regions, and text represented by images.</li>
|
||||
<li>Combines the dual advantages of accurate content extraction and faster speed in text mode, and more precise span/line region recognition in OCR mode.</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/11/15 0.9.3 released</summary>
|
||||
<p>Integrated <a href="https://github.com/RapidAI/RapidTable">RapidTable</a> for table recognition, improving single-table parsing speed by more than 10 times, with higher accuracy and lower GPU memory usage.</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/11/06 0.9.2 released</summary>
|
||||
<p>Integrated the <a href="https://huggingface.co/U4R/StructTable-InternVL2-1B">StructTable-InternVL2-1B</a> model for table recognition functionality.</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/10/31 0.9.0 released</summary>
|
||||
<p>This is a major new version with extensive code refactoring, addressing numerous issues, improving performance, reducing hardware requirements, and enhancing usability:</p>
|
||||
<ul>
|
||||
<li>Refactored the sorting module code to use <a href="https://github.com/ppaanngggg/layoutreader">layoutreader</a> for reading order sorting, ensuring high accuracy in various layouts.</li>
|
||||
<li>Refactored the paragraph concatenation module to achieve good results in cross-column, cross-page, cross-figure, and cross-table scenarios.</li>
|
||||
<li>Refactored the list and table of contents recognition functions, significantly improving the accuracy of list blocks and table of contents blocks, as well as the parsing of corresponding text paragraphs.</li>
|
||||
<li>Refactored the matching logic for figures, tables, and descriptive text, greatly enhancing the accuracy of matching captions and footnotes to figures and tables, and reducing the loss rate of descriptive text to near zero.</li>
|
||||
<li>Added multi-language support for OCR, supporting detection and recognition of 84 languages. For the list of supported languages, see <a href="https://paddlepaddle.github.io/PaddleOCR/latest/en/ppocr/blog/multi_languages.html#5-support-languages-and-abbreviations">OCR Language Support List</a>.</li>
|
||||
<li>Added memory recycling logic and other memory optimization measures, significantly reducing memory usage. The memory requirement for enabling all acceleration features except table acceleration (layout/formula/OCR) has been reduced from 16GB to 8GB, and the memory requirement for enabling all acceleration features has been reduced from 24GB to 10GB.</li>
|
||||
<li>Optimized configuration file feature switches, adding an independent formula detection switch to significantly improve speed and parsing results when formula detection is not needed.</li>
|
||||
<li>Integrated <a href="https://github.com/opendatalab/PDF-Extract-Kit">PDF-Extract-Kit 1.0</a>:
|
||||
<ul>
|
||||
<li>Added the self-developed <code>doclayout_yolo</code> model, which speeds up processing by more than 10 times compared to the original solution while maintaining similar parsing effects, and can be freely switched with <code>layoutlmv3</code> via the configuration file.</li>
|
||||
<li>Upgraded formula parsing to <code>unimernet 0.2.1</code>, improving formula parsing accuracy while significantly reducing memory usage.</li>
|
||||
<li>Due to the repository change for <code>PDF-Extract-Kit 1.0</code>, you need to re-download the model. Please refer to <a href="https://github.com/opendatalab/MinerU/blob/master/docs/how_to_download_models_en.md">How to Download Models</a> for detailed steps.</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/09/27 Version 0.8.1 released</summary>
|
||||
<p>Fixed some bugs, and providing a <a href="https://github.com/opendatalab/MinerU/blob/master/projects/web_demo/README.md">localized deployment version</a> of the <a href="https://opendatalab.com/OpenSourceTools/Extractor/PDF/">online demo</a> and the <a href="https://github.com/opendatalab/MinerU/blob/master/projects/web/README.md">front-end interface</a>.</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/09/09 Version 0.8.0 released</summary>
|
||||
<p>Supporting fast deployment with Dockerfile, and launching demos on Huggingface and Modelscope.</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/08/30 Version 0.7.1 released</summary>
|
||||
<p>Add paddle tablemaster table recognition option</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/08/09 Version 0.7.0b1 released</summary>
|
||||
<p>Simplified installation process, added table recognition functionality</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/08/01 Version 0.6.2b1 released</summary>
|
||||
<p>Optimized dependency conflict issues and installation documentation</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/07/05 Initial open-source release</summary>
|
||||
</details>
|
||||
|
||||
<!-- TABLE OF CONTENT -->
|
||||
|
||||
<details open="open">
|
||||
<summary><h2 style="display: inline-block">Table of Contents</h2></summary>
|
||||
<ol>
|
||||
<li>
|
||||
<a href="#mineru">MinerU</a>
|
||||
<ul>
|
||||
<li><a href="#project-introduction">Project Introduction</a></li>
|
||||
<li><a href="#key-features">Key Features</a></li>
|
||||
<li><a href="#quick-start">Quick Start</a>
|
||||
<ul>
|
||||
<li><a href="#online-demo">Online Demo</a></li>
|
||||
<li><a href="#quick-cpu-demo">Quick CPU Demo</a></li>
|
||||
<li><a href="#using-gpu">Using GPU</a></li>
|
||||
<li><a href="#using-npu">Using NPU</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a href="#usage">Usage</a>
|
||||
<ul>
|
||||
<li><a href="#command-line">Command Line</a></li>
|
||||
<li><a href="#api">API</a></li>
|
||||
<li><a href="#deploy-derived-projects">Deploy Derived Projects</a></li>
|
||||
<li><a href="#development-guide">Development Guide</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">All Thanks To Our Contributors</a></li>
|
||||
<li><a href="#license-information">License Information</a></li>
|
||||
<li><a href="#acknowledgments">Acknowledgments</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</a></li>
|
||||
<li><a href="#magic-html">Magic-html</a></li>
|
||||
<li><a href="#links">Links</a></li>
|
||||
</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**.
|
||||
|
||||
https://github.com/user-attachments/assets/4bea02c9-6d54-4cd6-97ed-dff14340982c
|
||||
|
||||
## Key Features
|
||||
|
||||
- Remove headers, footers, footnotes, page numbers, etc., to ensure semantic coherence.
|
||||
- Output text in human-readable order, suitable for single-column, multi-column, and complex layouts.
|
||||
- Preserve the structure of the original document, including headings, paragraphs, lists, etc.
|
||||
- Extract images, image descriptions, tables, table titles, and footnotes.
|
||||
- Automatically recognize and convert formulas in the document to LaTeX format.
|
||||
- Automatically recognize and convert tables in the document to HTML format.
|
||||
- Automatically detect scanned PDFs and garbled PDFs and enable OCR functionality.
|
||||
- OCR supports detection and recognition of 84 languages.
|
||||
- Supports multiple output formats, such as multimodal and NLP Markdown, JSON sorted by reading order, and rich intermediate formats.
|
||||
- Supports various visualization results, including layout visualization and span visualization, for efficient confirmation of output quality.
|
||||
- Supports running in a pure CPU environment, and also supports GPU(CUDA)/NPU(CANN)/MPS acceleration
|
||||
- Compatible with Windows, Linux, and Mac platforms.
|
||||
|
||||
## Quick Start
|
||||
|
||||
If 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)
|
||||
- Accelerate inference by using CUDA/CANN/MPS
|
||||
- [Linux/Windows + CUDA](#Using-GPU)
|
||||
- [Linux + CANN](#using-npu)
|
||||
- [MacOS + MPS](#using-mps)
|
||||
|
||||
> [!WARNING]
|
||||
> **Pre-installation Notice—Hardware and Software Environment Support**
|
||||
>
|
||||
> To ensure the stability and reliability of the project, we only optimize and test for specific hardware and software environments during development. This ensures that users deploying and running the project on recommended system configurations will get the best performance with the fewest compatibility issues.
|
||||
>
|
||||
> By focusing resources on the mainline environment, our team can more efficiently resolve potential bugs and develop new features.
|
||||
>
|
||||
> In non-mainline environments, due to the diversity of hardware and software configurations, as well as third-party dependency compatibility issues, we cannot guarantee 100% project availability. Therefore, for users who wish to use this project in non-recommended environments, we suggest carefully reading the documentation and FAQ first. Most issues already have corresponding solutions in the FAQ. We also encourage community feedback to help us gradually expand support.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td colspan="3" rowspan="2">Operating System</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Linux after 2019</td>
|
||||
<td>Windows 10 / 11</td>
|
||||
<td>macOS 11+</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3">CPU</td>
|
||||
<td>x86_64 / arm64</td>
|
||||
<td>x86_64(unsupported ARM Windows)</td>
|
||||
<td>x86_64 / arm64</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3">Memory Requirements</td>
|
||||
<td colspan="3">16GB or more, recommended 32GB+</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3">Storage Requirements</td>
|
||||
<td colspan="3">20GB or more, with a preference for SSD</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3">Python Version</td>
|
||||
<td colspan="3">3.10~3.13</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3">Nvidia Driver Version</td>
|
||||
<td>latest (Proprietary Driver)</td>
|
||||
<td>latest</td>
|
||||
<td>None</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3">CUDA Environment</td>
|
||||
<td colspan="2"><a href="https://pytorch.org/get-started/locally/">Refer to the PyTorch official website</a></td>
|
||||
<td>None</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3">CANN Environment(NPU support)</td>
|
||||
<td>8.0+(Ascend 910b)</td>
|
||||
<td>None</td>
|
||||
<td>None</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td rowspan="2">GPU/MPS Hardware Support List</td>
|
||||
<td colspan="2">GPU VRAM 6GB or more</td>
|
||||
<td colspan="2">All GPUs with Tensor Cores produced from Volta(2017) onwards.<br>
|
||||
More than 6GB VRAM </td>
|
||||
<td rowspan="2">Apple silicon</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
### Online Demo
|
||||
|
||||
Synced with dev branch updates:
|
||||
|
||||
[](https://mineru.net/OpenSourceTools/Extractor?source=github)
|
||||
[](https://huggingface.co/spaces/opendatalab/MinerU)
|
||||
[](https://www.modelscope.cn/studios/OpenDataLab/MinerU)
|
||||
|
||||
### Quick CPU Demo
|
||||
|
||||
#### 1. Install magic-pdf
|
||||
|
||||
```bash
|
||||
conda create -n mineru 'python=3.12' -y
|
||||
conda activate mineru
|
||||
pip install -U "magic-pdf[full]"
|
||||
```
|
||||
|
||||
#### 2. Download model weight files
|
||||
|
||||
Refer to [How to Download Model Files](docs/how_to_download_models_en.md) for detailed instructions.
|
||||
|
||||
#### 3. Modify the Configuration File for Additional Configuration
|
||||
|
||||
After completing the [2. Download model weight files](#2-download-model-weight-files) step, the script will automatically generate a `magic-pdf.json` file in the user directory and configure the default model path.
|
||||
You can find the `magic-pdf.json` file in your 【user directory】.
|
||||
|
||||
> [!TIP]
|
||||
> The user directory for Windows is "C:\\Users\\username", for Linux it is "/home/username", and for macOS it is "/Users/username".
|
||||
|
||||
You can modify certain configurations in this file to enable or disable features, such as table recognition:
|
||||
|
||||
|
||||
> [!NOTE]
|
||||
> If the following items are not present in the JSON, please manually add the required items and remove the comment content (standard JSON does not support comments).
|
||||
|
||||
```json
|
||||
{
|
||||
// other config
|
||||
"layout-config": {
|
||||
"model": "doclayout_yolo"
|
||||
},
|
||||
"formula-config": {
|
||||
"mfd_model": "yolo_v8_mfd",
|
||||
"mfr_model": "unimernet_small",
|
||||
"enable": true // The formula recognition feature is enabled by default. If you need to disable it, please change the value here to "false".
|
||||
},
|
||||
"table-config": {
|
||||
"model": "rapid_table",
|
||||
"sub_model": "slanet_plus",
|
||||
"enable": true, // The table recognition feature is enabled by default. If you need to disable it, please change the value here to "false".
|
||||
"max_time": 400
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 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
|
||||
> [!IMPORTANT]
|
||||
> Docker requires a GPU with at least 6GB 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/docker/global/Dockerfile -O Dockerfile
|
||||
docker build -t mineru:latest .
|
||||
docker run -it --name mineru --gpus=all mineru:latest /bin/bash -c "echo 'source /opt/mineru_venv/bin/activate' >> ~/.bashrc && exec bash"
|
||||
magic-pdf --help
|
||||
```
|
||||
|
||||
### Using NPU
|
||||
|
||||
If your device has NPU acceleration hardware, you can follow the tutorial below to use NPU acceleration:
|
||||
|
||||
[Ascend NPU Acceleration](docs/README_Ascend_NPU_Acceleration_zh_CN.md)
|
||||
|
||||
### Using MPS
|
||||
|
||||
If your device uses Apple silicon chips, you can enable MPS acceleration for your tasks.
|
||||
|
||||
You can enable MPS acceleration by setting the `device-mode` parameter to `mps` in the `magic-pdf.json` configuration file.
|
||||
|
||||
```json
|
||||
{
|
||||
// other config
|
||||
"device-mode": "mps"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
### Command Line
|
||||
|
||||
[Using MinerU via Command Line](https://mineru.readthedocs.io/en/latest/user_guide/usage/command_line.html)
|
||||
|
||||
> [!TIP]
|
||||
> For more information about the output files, please refer to the [Output File Description](docs/output_file_en_us.md).
|
||||
|
||||
### API
|
||||
|
||||
[Using MinerU via Python API](https://mineru.readthedocs.io/en/latest/user_guide/usage/api.html)
|
||||
|
||||
|
||||
### Deploy Derived Projects
|
||||
|
||||
Derived projects include secondary development projects based on MinerU by project developers and community developers,
|
||||
such as application interfaces based on Gradio, RAG based on llama, web demos similar to the official website, lightweight multi-GPU load balancing client/server ends, etc.
|
||||
These projects may offer more features and a better user experience.
|
||||
For specific deployment methods, please refer to the [Derived Project README](projects/README.md)
|
||||
|
||||
|
||||
### Development Guide
|
||||
|
||||
TODO
|
||||
|
||||
# TODO
|
||||
|
||||
- [x] Reading order based on the model
|
||||
- [x] Recognition of `index` and `list` in the main text
|
||||
- [x] Table recognition
|
||||
- [x] Heading Classification
|
||||
- [ ] Code block recognition in the main text
|
||||
- [ ] [Chemical formula recognition](docs/chemical_knowledge_introduction/introduction.pdf)
|
||||
- [ ] Geometric shape recognition
|
||||
|
||||
# Known Issues
|
||||
|
||||
- Reading order is determined by the model based on the spatial distribution of readable content, and may be out of order in some areas under extremely complex layouts.
|
||||
- Vertical text is not supported.
|
||||
- Tables of contents and lists are recognized through rules, and some uncommon list formats may not be recognized.
|
||||
- Code blocks are not yet supported in the layout model.
|
||||
- Comic books, art albums, primary school textbooks, and exercises cannot be parsed well.
|
||||
- Table recognition may result in row/column recognition errors in complex tables.
|
||||
- OCR recognition may produce inaccurate characters in PDFs of lesser-known languages (e.g., diacritical marks in Latin script, easily confused characters in Arabic script).
|
||||
- Some formulas may not render correctly in Markdown.
|
||||
|
||||
# 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">
|
||||
<img src="https://contrib.rocks/image?repo=opendatalab/MinerU" />
|
||||
</a>
|
||||
|
||||
# License Information
|
||||
|
||||
[LICENSE.md](LICENSE.md)
|
||||
|
||||
This 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)
|
||||
- [DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO)
|
||||
- [StructEqTable](https://github.com/UniModal4Reasoning/StructEqTable-Deploy)
|
||||
- [RapidTable](https://github.com/RapidAI/RapidTable)
|
||||
- [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR)
|
||||
- [RapidOCR](https://github.com/RapidAI/RapidOCR)
|
||||
- [PaddleOCR2Pytorch](https://github.com/frotms/PaddleOCR2Pytorch)
|
||||
- [PyMuPDF](https://github.com/pymupdf/PyMuPDF)
|
||||
- [layoutreader](https://github.com/ppaanngggg/layoutreader)
|
||||
- [fast-langdetect](https://github.com/LlmKira/fast-langdetect)
|
||||
- [pdfminer.six](https://github.com/pdfminer/pdfminer.six)
|
||||
|
||||
# Citation
|
||||
|
||||
```bibtex
|
||||
@misc{wang2024mineruopensourcesolutionprecise,
|
||||
title={MinerU: An Open-Source Solution for Precise Document Content Extraction},
|
||||
author={Bin Wang and Chao Xu and Xiaomeng Zhao and Linke Ouyang and Fan Wu and Zhiyuan Zhao and Rui Xu and Kaiwen Liu and Yuan Qu and Fukai Shang and Bo Zhang and Liqun Wei and Zhihao Sui and Wei Li and Botian Shi and Yu Qiao and Dahua Lin and Conghui He},
|
||||
year={2024},
|
||||
eprint={2409.18839},
|
||||
archivePrefix={arXiv},
|
||||
primaryClass={cs.CV},
|
||||
url={https://arxiv.org/abs/2409.18839},
|
||||
}
|
||||
|
||||
@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}
|
||||
}
|
||||
```
|
||||
|
||||
# Star History
|
||||
|
||||
<a>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=opendatalab/MinerU&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=opendatalab/MinerU&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=opendatalab/MinerU&type=Date" />
|
||||
</picture>
|
||||
</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
|
||||
|
||||
# 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)
|
@ -0,0 +1,23 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from magic_pdf.data.batch_build_dataset import batch_build_dataset
|
||||
from magic_pdf.tools.common import batch_do_parse
|
||||
|
||||
|
||||
def batch(pdf_dir, output_dir, method, lang):
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
doc_paths = []
|
||||
for doc_path in Path(pdf_dir).glob('*'):
|
||||
if doc_path.suffix == '.pdf':
|
||||
doc_paths.append(doc_path)
|
||||
|
||||
# build dataset with 2 workers
|
||||
datasets = batch_build_dataset(doc_paths, 4, lang)
|
||||
|
||||
# os.environ["MINERU_MIN_BATCH_INFERENCE_SIZE"] = "200" # every 200 pages will be parsed in one batch
|
||||
batch_do_parse(output_dir, [str(doc_path.stem) for doc_path in doc_paths], datasets, method)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
batch("pdfs", "output", "auto", "")
|
||||
|
@ -0,0 +1,68 @@
|
||||
# Copyright (c) Opendatalab. All rights reserved.
|
||||
import os
|
||||
|
||||
from magic_pdf.data.data_reader_writer import FileBasedDataWriter, FileBasedDataReader
|
||||
from magic_pdf.data.dataset import PymuDocDataset
|
||||
from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze
|
||||
from magic_pdf.config.enums import SupportedPdfParseMethod
|
||||
|
||||
# args
|
||||
__dir__ = os.path.dirname(os.path.abspath(__file__))
|
||||
pdf_file_name = os.path.join(__dir__, "pdfs", "demo1.pdf") # replace with the real pdf path
|
||||
name_without_extension = os.path.basename(pdf_file_name).split('.')[0]
|
||||
|
||||
# prepare env
|
||||
local_image_dir = os.path.join(__dir__, "output", name_without_extension, "images")
|
||||
local_md_dir = os.path.join(__dir__, "output", name_without_extension)
|
||||
image_dir = str(os.path.basename(local_image_dir))
|
||||
os.makedirs(local_image_dir, exist_ok=True)
|
||||
|
||||
image_writer, md_writer = FileBasedDataWriter(local_image_dir), FileBasedDataWriter(local_md_dir)
|
||||
|
||||
# read bytes
|
||||
reader1 = FileBasedDataReader("")
|
||||
pdf_bytes = reader1.read(pdf_file_name) # read the pdf content
|
||||
|
||||
# proc
|
||||
## Create Dataset Instance
|
||||
ds = PymuDocDataset(pdf_bytes)
|
||||
|
||||
## inference
|
||||
if ds.classify() == SupportedPdfParseMethod.OCR:
|
||||
infer_result = ds.apply(doc_analyze, ocr=True)
|
||||
|
||||
## pipeline
|
||||
pipe_result = infer_result.pipe_ocr_mode(image_writer)
|
||||
|
||||
else:
|
||||
infer_result = ds.apply(doc_analyze, ocr=False)
|
||||
|
||||
## pipeline
|
||||
pipe_result = infer_result.pipe_txt_mode(image_writer)
|
||||
|
||||
### get model inference result
|
||||
model_inference_result = infer_result.get_infer_res()
|
||||
|
||||
### draw layout result on each page
|
||||
pipe_result.draw_layout(os.path.join(local_md_dir, f"{name_without_extension}_layout.pdf"))
|
||||
|
||||
### draw spans result on each page
|
||||
pipe_result.draw_span(os.path.join(local_md_dir, f"{name_without_extension}_spans.pdf"))
|
||||
|
||||
### get markdown content
|
||||
md_content = pipe_result.get_markdown(image_dir)
|
||||
|
||||
### dump markdown
|
||||
pipe_result.dump_md(md_writer, f"{name_without_extension}.md", image_dir)
|
||||
|
||||
### get content list content
|
||||
content_list_content = pipe_result.get_content_list(image_dir)
|
||||
|
||||
### dump content list
|
||||
pipe_result.dump_content_list(md_writer, f"{name_without_extension}_content_list.json", image_dir)
|
||||
|
||||
### get middle json
|
||||
middle_json_content = pipe_result.get_middle_json()
|
||||
|
||||
### dump middle json
|
||||
pipe_result.dump_middle_json(md_writer, f'{name_without_extension}_middle.json')
|
@ -0,0 +1,51 @@
|
||||
# Use the official Ubuntu base image
|
||||
FROM swr.cn-central-221.ovaijisuan.com/mindformers/mindformers1.2_mindspore2.3:20240722
|
||||
|
||||
USER root
|
||||
|
||||
# Set environment variables to non-interactive to avoid prompts during installation
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# Update the package list and install necessary packages
|
||||
RUN apt-get update && \
|
||||
apt-get install -y \
|
||||
software-properties-common && \
|
||||
add-apt-repository -y ppa:deadsnakes/ppa && \
|
||||
apt-get update && \
|
||||
apt-get install -y \
|
||||
python3.10 \
|
||||
python3.10-venv \
|
||||
python3.10-distutils \
|
||||
python3.10-dev \
|
||||
python3-pip \
|
||||
wget \
|
||||
git \
|
||||
libgl1 \
|
||||
libglib2.0-0 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Set Python 3.10 as the default python3
|
||||
RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1
|
||||
|
||||
# Create a virtual environment for MinerU
|
||||
RUN python3 -m venv /opt/mineru_venv
|
||||
|
||||
# Copy the configuration file template and install magic-pdf latest
|
||||
RUN /bin/bash -c "wget https://gcore.jsdelivr.net/gh/opendatalab/MinerU@master/magic-pdf.template.json && \
|
||||
cp magic-pdf.template.json /root/magic-pdf.json && \
|
||||
source /opt/mineru_venv/bin/activate && \
|
||||
pip3 install --upgrade pip -i https://mirrors.aliyun.com/pypi/simple && \
|
||||
pip3 install torch==2.3.1 torchvision==0.18.1 -i https://mirrors.aliyun.com/pypi/simple && \
|
||||
pip3 install -U magic-pdf[full] 'numpy<2' decorator attrs absl-py cloudpickle ml-dtypes tornado einops -i https://mirrors.aliyun.com/pypi/simple && \
|
||||
wget https://gitee.com/ascend/pytorch/releases/download/v6.0.rc2-pytorch2.3.1/torch_npu-2.3.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl && \
|
||||
pip3 install torch_npu-2.3.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl"
|
||||
|
||||
# Download models and update the configuration file
|
||||
RUN /bin/bash -c "source /opt/mineru_venv/bin/activate && \
|
||||
pip3 install modelscope -i https://mirrors.aliyun.com/pypi/simple && \
|
||||
wget https://gcore.jsdelivr.net/gh/opendatalab/MinerU@master/scripts/download_models.py -O download_models.py && \
|
||||
python3 download_models.py && \
|
||||
sed -i 's|cpu|npu|g' /root/magic-pdf.json"
|
||||
|
||||
# Set the entry point to activate the virtual environment and run the command line tool
|
||||
ENTRYPOINT ["/bin/bash", "-c", "source /opt/mineru_venv/bin/activate && exec \"$@\"", "--"]
|
@ -0,0 +1,54 @@
|
||||
# Use the official Ubuntu base image
|
||||
FROM ubuntu:22.04
|
||||
|
||||
# Set environment variables to non-interactive to avoid prompts during installation
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# Update the package list and install necessary packages
|
||||
RUN apt-get update && \
|
||||
apt-get install -y \
|
||||
software-properties-common && \
|
||||
add-apt-repository ppa:deadsnakes/ppa && \
|
||||
apt-get update && \
|
||||
apt-get install -y \
|
||||
python3.10 \
|
||||
python3.10-venv \
|
||||
python3.10-distutils \
|
||||
python3-pip \
|
||||
wget \
|
||||
git \
|
||||
libgl1 \
|
||||
libreoffice \
|
||||
fonts-noto-cjk \
|
||||
fonts-wqy-zenhei \
|
||||
fonts-wqy-microhei \
|
||||
ttf-mscorefonts-installer \
|
||||
fontconfig \
|
||||
libglib2.0-0 \
|
||||
libxrender1 \
|
||||
libsm6 \
|
||||
libxext6 \
|
||||
poppler-utils \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Set Python 3.10 as the default python3
|
||||
RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1
|
||||
|
||||
# Create a virtual environment for MinerU
|
||||
RUN python3 -m venv /opt/mineru_venv
|
||||
|
||||
# Copy the configuration file template and install magic-pdf latest
|
||||
RUN /bin/bash -c "wget https://gcore.jsdelivr.net/gh/opendatalab/MinerU@master/magic-pdf.template.json && \
|
||||
cp magic-pdf.template.json /root/magic-pdf.json && \
|
||||
source /opt/mineru_venv/bin/activate && \
|
||||
pip3 install --upgrade pip -i https://mirrors.aliyun.com/pypi/simple && \
|
||||
pip3 install -U magic-pdf[full] -i https://mirrors.aliyun.com/pypi/simple"
|
||||
|
||||
# Download models and update the configuration file
|
||||
RUN /bin/bash -c "pip3 install modelscope -i https://mirrors.aliyun.com/pypi/simple && \
|
||||
wget https://gcore.jsdelivr.net/gh/opendatalab/MinerU@master/scripts/download_models.py -O download_models.py && \
|
||||
python3 download_models.py && \
|
||||
sed -i 's|cpu|cuda|g' /root/magic-pdf.json"
|
||||
|
||||
# Set the entry point to activate the virtual environment and run the command line tool
|
||||
ENTRYPOINT ["/bin/bash", "-c", "source /opt/mineru_venv/bin/activate && exec \"$@\"", "--"]
|
@ -0,0 +1,54 @@
|
||||
# Use the official Ubuntu base image
|
||||
FROM ubuntu:22.04
|
||||
|
||||
# Set environment variables to non-interactive to avoid prompts during installation
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# Update the package list and install necessary packages
|
||||
RUN apt-get update && \
|
||||
apt-get install -y \
|
||||
software-properties-common && \
|
||||
add-apt-repository ppa:deadsnakes/ppa && \
|
||||
apt-get update && \
|
||||
apt-get install -y \
|
||||
python3.10 \
|
||||
python3.10-venv \
|
||||
python3.10-distutils \
|
||||
python3-pip \
|
||||
wget \
|
||||
git \
|
||||
libgl1 \
|
||||
libreoffice \
|
||||
fonts-noto-cjk \
|
||||
fonts-wqy-zenhei \
|
||||
fonts-wqy-microhei \
|
||||
ttf-mscorefonts-installer \
|
||||
fontconfig \
|
||||
libglib2.0-0 \
|
||||
libxrender1 \
|
||||
libsm6 \
|
||||
libxext6 \
|
||||
poppler-utils \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Set Python 3.10 as the default python3
|
||||
RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1
|
||||
|
||||
# Create a virtual environment for MinerU
|
||||
RUN python3 -m venv /opt/mineru_venv
|
||||
|
||||
# Copy the configuration file template and install magic-pdf latest
|
||||
RUN /bin/bash -c "wget https://github.com/opendatalab/MinerU/raw/master/magic-pdf.template.json && \
|
||||
cp magic-pdf.template.json /root/magic-pdf.json && \
|
||||
source /opt/mineru_venv/bin/activate && \
|
||||
pip3 install --upgrade pip && \
|
||||
pip3 install -U magic-pdf[full]"
|
||||
|
||||
# Download models and update the configuration file
|
||||
RUN /bin/bash -c "pip3 install huggingface_hub && \
|
||||
wget https://github.com/opendatalab/MinerU/raw/master/scripts/download_models_hf.py -O download_models.py && \
|
||||
python3 download_models.py && \
|
||||
sed -i 's|cpu|cuda|g' /root/magic-pdf.json"
|
||||
|
||||
# Set the entry point to activate the virtual environment and run the command line tool
|
||||
ENTRYPOINT ["/bin/bash", "-c", "source /opt/mineru_venv/bin/activate && exec \"$@\"", "--"]
|
@ -0,0 +1,95 @@
|
||||
# Frequently Asked Questions
|
||||
|
||||
### 1. When using the command `pip install magic-pdf[full]` on newer versions of macOS, the error `zsh: no matches found: magic-pdf[full]` occurs.
|
||||
|
||||
On macOS, the default shell has switched from Bash to Z shell, which has special handling logic for certain types of string matching. This can lead to the "no matches found" error. You can try disabling the globbing feature in the command line and then run the installation command again.
|
||||
|
||||
```bash
|
||||
setopt no_nomatch
|
||||
pip install magic-pdf[full]
|
||||
```
|
||||
|
||||
### 2. Encountering the error `pickle.UnpicklingError: invalid load key, 'v'.` during use
|
||||
|
||||
This might be due to an incomplete download of the model file. You can try re-downloading the model file and then try again.
|
||||
Reference: https://github.com/opendatalab/MinerU/issues/143
|
||||
|
||||
### 3. Where should the model files be downloaded and how should the `/models-dir` configuration be set?
|
||||
|
||||
The path for the model files is configured in "magic-pdf.json". just like:
|
||||
|
||||
```json
|
||||
{
|
||||
"models-dir": "/tmp/models"
|
||||
}
|
||||
```
|
||||
|
||||
This path is an absolute path, not a relative path. You can obtain the absolute path in the models directory using the "pwd" command.
|
||||
Reference: https://github.com/opendatalab/MinerU/issues/155#issuecomment-2230216874
|
||||
|
||||
### 4. Encountered the error `ImportError: libGL.so.1: cannot open shared object file: No such file or directory` in Ubuntu 22.04 on WSL2
|
||||
|
||||
The `libgl` library is missing in Ubuntu 22.04 on WSL2. You can install the `libgl` library with the following command to resolve the issue:
|
||||
|
||||
```bash
|
||||
sudo apt-get install libgl1-mesa-glx
|
||||
```
|
||||
|
||||
Reference: https://github.com/opendatalab/MinerU/issues/388
|
||||
|
||||
### 5. Encountered error `ModuleNotFoundError: No module named 'fairscale'`
|
||||
|
||||
You need to uninstall the module and reinstall it:
|
||||
|
||||
```bash
|
||||
pip uninstall fairscale
|
||||
pip install fairscale
|
||||
```
|
||||
|
||||
Reference: https://github.com/opendatalab/MinerU/issues/411
|
||||
|
||||
### 6. On some newer devices like the H100, the text parsed during OCR using CUDA acceleration is garbled.
|
||||
|
||||
The compatibility of cuda11 with new graphics cards is poor, and the CUDA version used by Paddle needs to be upgraded.
|
||||
|
||||
```bash
|
||||
pip install paddlepaddle-gpu==3.0.0b1 -i https://www.paddlepaddle.org.cn/packages/stable/cu123/
|
||||
```
|
||||
|
||||
Reference: https://github.com/opendatalab/MinerU/issues/558
|
||||
|
||||
### 7. On some Linux servers, the program immediately reports an error `Illegal instruction (core dumped)`
|
||||
|
||||
This might be because the server's CPU does not support the AVX/AVX2 instruction set, or the CPU itself supports it but has been disabled by the system administrator. You can try contacting the system administrator to remove the restriction or change to a different server.
|
||||
|
||||
References: https://github.com/opendatalab/MinerU/issues/591 , https://github.com/opendatalab/MinerU/issues/736
|
||||
|
||||
|
||||
### 8. Error when installing MinerU on CentOS 7 or Ubuntu 18: `ERROR: Failed building wheel for simsimd`
|
||||
|
||||
The new version of albumentations (1.4.21) introduces a dependency on simsimd. Since the pre-built package of simsimd for Linux requires a glibc version greater than or equal to 2.28, this causes installation issues on some Linux distributions released before 2019. You can resolve this issue by using the following command:
|
||||
```
|
||||
pip install -U magic-pdf[full,old_linux] --extra-index-url https://wheels.myhloli.com
|
||||
```
|
||||
|
||||
Reference: https://github.com/opendatalab/MinerU/issues/1004
|
||||
|
||||
### 9. Old Graphics Cards Such as M40 Encounter "RuntimeError: CUDA error: CUBLAS_STATUS_NOT_SUPPORTED"
|
||||
|
||||
An error occurs during operation (cuda):
|
||||
```
|
||||
RuntimeError: CUDA error: CUBLAS_STATUS_NOT_SUPPORTED when calling cublasGemmStridedBatchedEx(handle, opa, opb, (int)m, (int)n, (int)k, (void*)&falpha, a, CUDA_R_16BF, (int)lda, stridea, b, CUDA_R_16BF, (int)ldb, strideb, (void*)&fbeta, c, CUDA_R_16BF, (int)ldc, stridec, (int)num_batches, compute_type, CUBLAS_GEMM_DEFAULT_TENSOR_OP)
|
||||
```
|
||||
Because BF16 precision is not supported on graphics cards before the Turing architecture and some graphics cards are not recognized by torch, it is necessary to manually disable BF16 precision.
|
||||
Modify the code in lines 287-290 of the "pdf_parse_union_core_v2.py" file (note that the location may vary in different versions):
|
||||
```
|
||||
if torch.cuda.is_bf16_supported():
|
||||
supports_bfloat16 = True
|
||||
else:
|
||||
supports_bfloat16 = False
|
||||
```
|
||||
Change it to:
|
||||
```
|
||||
supports_bfloat16 = False
|
||||
```
|
||||
Reference: https://github.com/opendatalab/MinerU/issues/1508
|
@ -0,0 +1,111 @@
|
||||
# Ubuntu 22.04 LTS
|
||||
|
||||
### 1. Check if NVIDIA Drivers Are Installed
|
||||
|
||||
```sh
|
||||
nvidia-smi
|
||||
```
|
||||
|
||||
If you see information similar to the following, it means that the NVIDIA drivers are already installed, and you can skip Step 2.
|
||||
|
||||
> [!NOTE]
|
||||
> Notice:`CUDA Version` should be >= 12.4, If the displayed version number is less than 12.4, please upgrade the driver.
|
||||
|
||||
```plaintext
|
||||
+---------------------------------------------------------------------------------------+
|
||||
| NVIDIA-SMI 570.133.07 Driver Version: 572.83 CUDA Version: 12.8 |
|
||||
|-----------------------------------------+----------------------+----------------------+
|
||||
| GPU Name TCC/WDDM | Bus-Id Disp.A | Volatile Uncorr. ECC |
|
||||
| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |
|
||||
| | | MIG M. |
|
||||
|=========================================+======================+======================|
|
||||
| 0 NVIDIA GeForce RTX 3060 Ti WDDM | 00000000:01:00.0 On | N/A |
|
||||
| 0% 51C P8 12W / 200W | 1489MiB / 8192MiB | 5% Default |
|
||||
| | | N/A |
|
||||
+-----------------------------------------+----------------------+----------------------+
|
||||
```
|
||||
|
||||
### 2. Install the Driver
|
||||
|
||||
If no driver is installed, use the following command:
|
||||
|
||||
```sh
|
||||
sudo apt-get update
|
||||
sudo apt-get install nvidia-driver-570-server
|
||||
```
|
||||
|
||||
Install the proprietary driver and restart your computer after installation.
|
||||
|
||||
```sh
|
||||
reboot
|
||||
```
|
||||
|
||||
### 3. Install Anaconda
|
||||
|
||||
If Anaconda is already installed, skip this step.
|
||||
|
||||
```sh
|
||||
wget https://repo.anaconda.com/archive/Anaconda3-2024.06-1-Linux-x86_64.sh
|
||||
bash Anaconda3-2024.06-1-Linux-x86_64.sh
|
||||
```
|
||||
|
||||
In the final step, enter `yes`, close the terminal, and reopen it.
|
||||
|
||||
### 4. Create an Environment Using Conda
|
||||
|
||||
```bash
|
||||
conda create -n mineru 'python=3.12' -y
|
||||
conda activate mineru
|
||||
```
|
||||
|
||||
### 5. Install Applications
|
||||
|
||||
```sh
|
||||
pip install -U magic-pdf[full]
|
||||
```
|
||||
> [!TIP]
|
||||
> After installation, you can check the version of `magic-pdf` using the following command:
|
||||
>
|
||||
> ```sh
|
||||
> magic-pdf --version
|
||||
> ```
|
||||
|
||||
|
||||
### 6. Download Models
|
||||
|
||||
|
||||
Refer to detailed instructions on [how to download model files](how_to_download_models_en.md).
|
||||
|
||||
|
||||
## 7. Understand the Location of the Configuration File
|
||||
|
||||
After completing the [6. Download Models](#6-download-models) step, the script will automatically generate a `magic-pdf.json` file in the user directory and configure the default model path.
|
||||
You can find the `magic-pdf.json` file in your user directory.
|
||||
|
||||
> [!TIP]
|
||||
> The user directory for Linux is "/home/username".
|
||||
|
||||
|
||||
### 8. First Run
|
||||
|
||||
Download a sample file from the repository and test it.
|
||||
|
||||
```sh
|
||||
wget https://github.com/opendatalab/MinerU/raw/master/demo/pdfs/small_ocr.pdf
|
||||
magic-pdf -p small_ocr.pdf -o ./output
|
||||
```
|
||||
|
||||
### 9. Test CUDA Acceleration
|
||||
|
||||
If your graphics card has at least **6GB** of VRAM, follow these steps to test CUDA acceleration:
|
||||
|
||||
1. Modify the value of `"device-mode"` in the `magic-pdf.json` configuration file located in your home directory.
|
||||
```json
|
||||
{
|
||||
"device-mode": "cuda"
|
||||
}
|
||||
```
|
||||
2. Test CUDA acceleration with the following command:
|
||||
```sh
|
||||
magic-pdf -p small_ocr.pdf -o ./output
|
||||
```
|
@ -0,0 +1,83 @@
|
||||
# Windows 10/11
|
||||
|
||||
### 1. Install CUDA and cuDNN
|
||||
|
||||
You need to install a CUDA version that is compatible with torch's requirements. For details, please refer to the [official PyTorch website](https://pytorch.org/get-started/locally/).
|
||||
|
||||
- CUDA 11.8 https://developer.nvidia.com/cuda-11-8-0-download-archive
|
||||
- CUDA 12.4 https://developer.nvidia.com/cuda-12-4-0-download-archive
|
||||
- CUDA 12.6 https://developer.nvidia.com/cuda-12-6-0-download-archive
|
||||
- CUDA 12.8 https://developer.nvidia.com/cuda-12-8-0-download-archive
|
||||
|
||||
### 2. Install Anaconda
|
||||
|
||||
If Anaconda is already installed, you can skip this step.
|
||||
|
||||
Download link: https://repo.anaconda.com/archive/Anaconda3-2024.06-1-Windows-x86_64.exe
|
||||
|
||||
### 3. Create an Environment Using Conda
|
||||
|
||||
```bash
|
||||
conda create -n mineru 'python=3.12' -y
|
||||
conda activate mineru
|
||||
```
|
||||
|
||||
### 4. Install Applications
|
||||
|
||||
```
|
||||
pip install -U magic-pdf[full]
|
||||
```
|
||||
|
||||
> [!IMPORTANT]
|
||||
> After installation, you can check the version of `magic-pdf` using the following command:
|
||||
>
|
||||
> ```bash
|
||||
> magic-pdf --version
|
||||
> ```
|
||||
|
||||
|
||||
### 5. Download Models
|
||||
|
||||
Refer to detailed instructions on [how to download model files](how_to_download_models_en.md).
|
||||
|
||||
### 6. Understand the Location of the Configuration File
|
||||
|
||||
After completing the [5. Download Models](#5-download-models) step, the script will automatically generate a `magic-pdf.json` file in the user directory and configure the default model path.
|
||||
You can find the `magic-pdf.json` file in your 【user directory】 .
|
||||
|
||||
> [!TIP]
|
||||
> The user directory for Windows is "C:/Users/username".
|
||||
|
||||
### 7. First Run
|
||||
|
||||
Download a sample file from the repository and test it.
|
||||
|
||||
```powershell
|
||||
wget https://github.com/opendatalab/MinerU/raw/master/demo/pdfs/small_ocr.pdf -O small_ocr.pdf
|
||||
magic-pdf -p small_ocr.pdf -o ./output
|
||||
```
|
||||
|
||||
### 8. Test CUDA Acceleration
|
||||
|
||||
If your graphics card has at least 6GB of VRAM, follow these steps to test CUDA-accelerated parsing performance.
|
||||
|
||||
1. **Overwrite the installation of torch and torchvision** supporting CUDA.(Please select the appropriate index-url based on your CUDA version. For more details, refer to the [PyTorch official website](https://pytorch.org/get-started/locally/).)
|
||||
|
||||
```
|
||||
pip install --force-reinstall torch torchvision --index-url https://download.pytorch.org/whl/cu124
|
||||
```
|
||||
|
||||
2. **Modify the value of `"device-mode"`** in the `magic-pdf.json` configuration file located in your user directory.
|
||||
|
||||
```json
|
||||
{
|
||||
"device-mode": "cuda"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
3. **Run the following command to test CUDA acceleration**:
|
||||
|
||||
```
|
||||
magic-pdf -p small_ocr.pdf -o ./output
|
||||
```
|
@ -0,0 +1,23 @@
|
||||
Model downloads are divided into initial downloads and updates to the model directory. Please refer to the corresponding documentation for instructions on how to proceed.
|
||||
|
||||
|
||||
# Initial download of model files
|
||||
|
||||
### Download the Model from Hugging Face
|
||||
|
||||
Use a Python Script to Download Model Files from Hugging Face
|
||||
```bash
|
||||
pip install huggingface_hub
|
||||
wget https://github.com/opendatalab/MinerU/raw/master/scripts/download_models_hf.py -O download_models_hf.py
|
||||
python download_models_hf.py
|
||||
```
|
||||
The Python script will automatically download the model files and configure the model directory in the configuration file.
|
||||
|
||||
The configuration file can be found in the user directory, with the filename `magic-pdf.json`.
|
||||
|
||||
|
||||
# How to update models previously downloaded
|
||||
|
||||
## 1. Models downloaded via Hugging Face or Model Scope
|
||||
|
||||
If you previously downloaded models via Hugging Face or Model Scope, you can rerun the Python script used for the initial download. This will automatically update the model directory to the latest version.
|
After Width: | Height: | Size: 18 KiB |
After Width: | Height: | Size: 96 KiB |
After Width: | Height: | Size: 105 KiB |
After Width: | Height: | Size: 106 KiB |
After Width: | Height: | Size: 559 KiB |
After Width: | Height: | Size: 13 KiB |
After Width: | Height: | Size: 262 KiB |
After Width: | Height: | Size: 247 KiB |
After Width: | Height: | Size: 550 KiB |
After Width: | Height: | Size: 498 KiB |
@ -0,0 +1,330 @@
|
||||
## 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
|
||||
|
||||
Each 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
|
||||
|
||||
All 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.
|
||||
|
||||

|
||||
|
||||
### some_pdf_model.json
|
||||
|
||||
#### Structure Definition
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, Field
|
||||
from enum import IntEnum
|
||||
|
||||
class CategoryType(IntEnum):
|
||||
title = 0 # Title
|
||||
plain_text = 1 # Text
|
||||
abandon = 2 # Includes headers, footers, page numbers, and page annotations
|
||||
figure = 3 # Image
|
||||
figure_caption = 4 # Image description
|
||||
table = 5 # Table
|
||||
table_caption = 6 # Table description
|
||||
table_footnote = 7 # Table footnote
|
||||
isolate_formula = 8 # Block formula
|
||||
formula_caption = 9 # Formula label
|
||||
|
||||
embedding = 13 # Inline formula
|
||||
isolated = 14 # Block formula
|
||||
text = 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)
|
||||
width: int = Field(description="Page width", ge=0)
|
||||
|
||||
class ObjectInferenceResult(BaseModel):
|
||||
category_id: CategoryType = Field(description="Category", ge=0)
|
||||
poly: list[float] = Field(description="Quadrilateral coordinates, representing the coordinates of the top-left, top-right, bottom-right, and bottom-left points respectively")
|
||||
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 MinerU
|
||||
inference_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.
|
||||

|
||||
|
||||
#### example
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"layout_dets": [
|
||||
{
|
||||
"category_id": 2,
|
||||
"poly": [
|
||||
99.1906967163086,
|
||||
100.3119125366211,
|
||||
730.3707885742188,
|
||||
100.3119125366211,
|
||||
730.3707885742188,
|
||||
245.81326293945312,
|
||||
99.1906967163086,
|
||||
245.81326293945312
|
||||
],
|
||||
"score": 0.9999997615814209
|
||||
}
|
||||
],
|
||||
"page_info": {
|
||||
"page_no": 0,
|
||||
"height": 2339,
|
||||
"width": 1654
|
||||
}
|
||||
},
|
||||
{
|
||||
"layout_dets": [
|
||||
{
|
||||
"category_id": 5,
|
||||
"poly": [
|
||||
99.13092803955078,
|
||||
2210.680419921875,
|
||||
497.3183898925781,
|
||||
2210.680419921875,
|
||||
497.3183898925781,
|
||||
2264.78076171875,
|
||||
99.13092803955078,
|
||||
2264.78076171875
|
||||
],
|
||||
"score": 0.9999997019767761
|
||||
}
|
||||
],
|
||||
"page_info": {
|
||||
"page_no": 1,
|
||||
"height": 2339,
|
||||
"width": 1654
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### some_pdf_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 |
|
||||
|
||||
<br>
|
||||
|
||||
**pdf_info**
|
||||
|
||||
Field 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 |
|
||||
|
||||
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.
|
||||
|
||||
<br>
|
||||
|
||||
**block**
|
||||
|
||||
The 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 |
|
||||
|
||||
<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 |
|
||||
|
||||
Detailed explanation of second-level block types
|
||||
|
||||
| type | Description |
|
||||
| :----------------- | :--------------------- |
|
||||
| image_body | Main body of the image |
|
||||
| image_caption | Image description text |
|
||||
| image_footnote | Image footnote |
|
||||
| table_body | Main body of the table |
|
||||
| table_caption | Table description text |
|
||||
| table_footnote | Table footnote |
|
||||
| text | Text block |
|
||||
| title | Title block |
|
||||
| index | Index block |
|
||||
| list | List block |
|
||||
| interline_equation | Block formula |
|
||||
|
||||
<br>
|
||||
|
||||
**line**
|
||||
|
||||
The 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 |
|
||||
|
||||
<br>
|
||||
|
||||
**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 |
|
||||
|
||||
**Summary**
|
||||
|
||||
A span is the smallest storage unit for all elements.
|
||||
|
||||
The elements stored within para_blocks are block information.
|
||||
|
||||
The block structure is as follows:
|
||||
|
||||
First-level block (if any) -> Second-level block -> Line -> Span
|
||||
|
||||
#### example
|
||||
|
||||
```json
|
||||
{
|
||||
"pdf_info": [
|
||||
{
|
||||
"preproc_blocks": [
|
||||
{
|
||||
"type": "text",
|
||||
"bbox": [
|
||||
52,
|
||||
61.956024169921875,
|
||||
294,
|
||||
82.99800872802734
|
||||
],
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
52,
|
||||
61.956024169921875,
|
||||
294,
|
||||
72.0000228881836
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
54.0,
|
||||
61.956024169921875,
|
||||
296.2261657714844,
|
||||
72.0000228881836
|
||||
],
|
||||
"content": "dependent on the service headway and the reliability of the departure ",
|
||||
"type": "text",
|
||||
"score": 1.0
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"layout_bboxes": [
|
||||
{
|
||||
"layout_bbox": [
|
||||
52,
|
||||
61,
|
||||
294,
|
||||
731
|
||||
],
|
||||
"layout_label": "V",
|
||||
"sub_layout": []
|
||||
}
|
||||
],
|
||||
"page_idx": 0,
|
||||
"page_size": [
|
||||
612.0,
|
||||
792.0
|
||||
],
|
||||
"_layout_tree": [],
|
||||
"images": [],
|
||||
"tables": [],
|
||||
"interline_equations": [],
|
||||
"discarded_blocks": [],
|
||||
"para_blocks": [
|
||||
{
|
||||
"type": "text",
|
||||
"bbox": [
|
||||
52,
|
||||
61.956024169921875,
|
||||
294,
|
||||
82.99800872802734
|
||||
],
|
||||
"lines": [
|
||||
{
|
||||
"bbox": [
|
||||
52,
|
||||
61.956024169921875,
|
||||
294,
|
||||
72.0000228881836
|
||||
],
|
||||
"spans": [
|
||||
{
|
||||
"bbox": [
|
||||
54.0,
|
||||
61.956024169921875,
|
||||
296.2261657714844,
|
||||
72.0000228881836
|
||||
],
|
||||
"content": "dependent on the service headway and the reliability of the departure ",
|
||||
"type": "text",
|
||||
"score": 1.0
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"_parse_type": "txt",
|
||||
"_version_name": "0.6.1"
|
||||
}
|
||||
```
|
@ -0,0 +1,54 @@
|
||||
{
|
||||
"bucket_info":{
|
||||
"bucket-name-1":["ak", "sk", "endpoint"],
|
||||
"bucket-name-2":["ak", "sk", "endpoint"]
|
||||
},
|
||||
"models-dir":"/tmp/models",
|
||||
"layoutreader-model-dir":"/tmp/layoutreader",
|
||||
"device-mode":"cpu",
|
||||
"layout-config": {
|
||||
"model": "doclayout_yolo"
|
||||
},
|
||||
"formula-config": {
|
||||
"mfd_model": "yolo_v8_mfd",
|
||||
"mfr_model": "unimernet_small",
|
||||
"enable": true
|
||||
},
|
||||
"table-config": {
|
||||
"model": "rapid_table",
|
||||
"sub_model": "slanet_plus",
|
||||
"enable": true,
|
||||
"max_time": 400
|
||||
},
|
||||
"latex-delimiter-config": {
|
||||
"display": {
|
||||
"left": "$$",
|
||||
"right": "$$"
|
||||
},
|
||||
"inline": {
|
||||
"left": "$",
|
||||
"right": "$"
|
||||
}
|
||||
},
|
||||
"llm-aided-config": {
|
||||
"formula_aided": {
|
||||
"api_key": "your_api_key",
|
||||
"base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
||||
"model": "qwen2.5-7b-instruct",
|
||||
"enable": false
|
||||
},
|
||||
"text_aided": {
|
||||
"api_key": "your_api_key",
|
||||
"base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
||||
"model": "qwen2.5-7b-instruct",
|
||||
"enable": false
|
||||
},
|
||||
"title_aided": {
|
||||
"api_key": "your_api_key",
|
||||
"base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
||||
"model": "qwen2.5-32b-instruct",
|
||||
"enable": false
|
||||
}
|
||||
},
|
||||
"config_version": "1.2.1"
|
||||
}
|
@ -0,0 +1,674 @@
|
||||
Metadata-Version: 2.4
|
||||
Name: magic_pdf
|
||||
Version: 1.3.11
|
||||
Summary: A practical tool for converting PDF to Markdown
|
||||
License: AGPL-3.0
|
||||
Project-URL: Home, https://mineru.net/
|
||||
Project-URL: Repository, https://github.com/opendatalab/MinerU
|
||||
Keywords: magic-pdf, mineru, MinerU, convert, pdf, markdown
|
||||
Classifier: Programming Language :: Python :: 3.10
|
||||
Classifier: Programming Language :: Python :: 3.11
|
||||
Classifier: Programming Language :: Python :: 3.12
|
||||
Classifier: Programming Language :: Python :: 3.13
|
||||
Requires-Python: >=3.10,<3.14
|
||||
Description-Content-Type: text/markdown
|
||||
License-File: LICENSE.md
|
||||
Requires-Dist: boto3>=1.28.43
|
||||
Requires-Dist: Brotli>=1.1.0
|
||||
Requires-Dist: click>=8.1.7
|
||||
Requires-Dist: fast-langdetect<0.3.0,>=0.2.3
|
||||
Requires-Dist: loguru>=0.6.0
|
||||
Requires-Dist: numpy>=1.21.6
|
||||
Requires-Dist: pydantic<2.11,>=2.7.2
|
||||
Requires-Dist: PyMuPDF<1.25.0,>=1.24.9
|
||||
Requires-Dist: scikit-learn>=1.0.2
|
||||
Requires-Dist: torch!=2.5.0,!=2.5.1,<3,>=2.2.2
|
||||
Requires-Dist: torchvision
|
||||
Requires-Dist: transformers!=4.51.0,<5.0.0,>=4.49.0
|
||||
Requires-Dist: pdfminer.six==20250506
|
||||
Requires-Dist: tqdm>=4.67.1
|
||||
Provides-Extra: lite
|
||||
Requires-Dist: paddleocr==2.7.3; extra == "lite"
|
||||
Requires-Dist: paddlepaddle==3.0.0b1; platform_system == "Linux" and extra == "lite"
|
||||
Requires-Dist: paddlepaddle==2.6.1; (platform_system == "Windows" or platform_system == "Darwin") and extra == "lite"
|
||||
Provides-Extra: full
|
||||
Requires-Dist: matplotlib<4,>=3.10; extra == "full"
|
||||
Requires-Dist: ultralytics<9,>=8.3.48; extra == "full"
|
||||
Requires-Dist: doclayout_yolo==0.0.2b1; extra == "full"
|
||||
Requires-Dist: dill<1,>=0.3.8; extra == "full"
|
||||
Requires-Dist: rapid_table<2.0.0,>=1.0.5; extra == "full"
|
||||
Requires-Dist: PyYAML<7,>=6.0.2; extra == "full"
|
||||
Requires-Dist: ftfy<7,>=6.3.1; extra == "full"
|
||||
Requires-Dist: openai<2,>=1.70.0; extra == "full"
|
||||
Requires-Dist: shapely<3,>=2.0.7; extra == "full"
|
||||
Requires-Dist: pyclipper<2,>=1.3.0; extra == "full"
|
||||
Requires-Dist: omegaconf<3,>=2.3.0; extra == "full"
|
||||
Provides-Extra: full-old-linux
|
||||
Requires-Dist: matplotlib<=3.10.1,>=3.10; extra == "full-old-linux"
|
||||
Requires-Dist: ultralytics<=8.3.104,>=8.3.48; extra == "full-old-linux"
|
||||
Requires-Dist: doclayout_yolo==0.0.2b1; extra == "full-old-linux"
|
||||
Requires-Dist: dill==0.3.8; extra == "full-old-linux"
|
||||
Requires-Dist: PyYAML==6.0.2; extra == "full-old-linux"
|
||||
Requires-Dist: ftfy==6.3.1; extra == "full-old-linux"
|
||||
Requires-Dist: openai==1.71.0; extra == "full-old-linux"
|
||||
Requires-Dist: shapely==2.1.0; extra == "full-old-linux"
|
||||
Requires-Dist: pyclipper==1.3.0.post6; extra == "full-old-linux"
|
||||
Requires-Dist: omegaconf==2.3.0; extra == "full-old-linux"
|
||||
Requires-Dist: albumentations==1.4.20; extra == "full-old-linux"
|
||||
Requires-Dist: rapid_table==1.0.3; extra == "full-old-linux"
|
||||
Dynamic: classifier
|
||||
Dynamic: description
|
||||
Dynamic: description-content-type
|
||||
Dynamic: keywords
|
||||
Dynamic: license
|
||||
Dynamic: license-file
|
||||
Dynamic: project-url
|
||||
Dynamic: provides-extra
|
||||
Dynamic: requires-dist
|
||||
Dynamic: requires-python
|
||||
Dynamic: summary
|
||||
|
||||
<div align="center" xmlns="http://www.w3.org/1999/html">
|
||||
<!-- logo -->
|
||||
<p align="center">
|
||||
<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)
|
||||
[](https://github.com/opendatalab/MinerU/issues)
|
||||
[](https://pypi.org/project/magic-pdf/)
|
||||
[](https://pypi.org/project/magic-pdf/)
|
||||
[](https://pepy.tech/project/magic-pdf)
|
||||
[](https://pepy.tech/project/magic-pdf)
|
||||
|
||||
[](https://mineru.net/OpenSourceTools/Extractor?source=github)
|
||||
[](https://huggingface.co/spaces/opendatalab/MinerU)
|
||||
[](https://www.modelscope.cn/studios/OpenDataLab/MinerU)
|
||||
[](https://colab.research.google.com/gist/myhloli/3b3a00a4a0a61577b6c30f989092d20d/mineru_demo.ipynb)
|
||||
[](https://arxiv.org/abs/2409.18839)
|
||||
|
||||
|
||||
<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>🔥🔥🔥
|
||||
<br>
|
||||
<br>
|
||||
<a href="https://mineru.net/client?source=github">
|
||||
Easier to use: Just grab MinerU Desktop. No coding, no login, just a simple interface and smooth interactions. Enjoy it without any fuss!</a>🚀🚀🚀
|
||||
|
||||
</p>
|
||||
|
||||
<!-- join us -->
|
||||
|
||||
<p align="center">
|
||||
👋 join us on <a href="https://discord.gg/Tdedn9GTXq" target="_blank">Discord</a> and <a href="http://mineru.space/s/V85Yl" target="_blank">WeChat</a>
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
# Changelog
|
||||
- 2025/04/29 1.3.10 Released
|
||||
- Support for custom formula delimiters can be achieved by modifying the `latex-delimiter-config` item in the `magic-pdf.json` file under the user directory.
|
||||
- 2025/04/27 1.3.9 Released
|
||||
- Optimized the formula parsing function to improve the success rate of formula rendering
|
||||
- 2025/04/23 1.3.8 Released
|
||||
- The default `ocr` model (`ch`) has been updated to `PP-OCRv4_server_rec_doc` (model update required)
|
||||
- `PP-OCRv4_server_rec_doc` is trained on a mix of more Chinese document data and PP-OCR training data, enhancing recognition capabilities for some traditional Chinese characters, Japanese, and special characters. It supports over 15,000 recognizable characters, improving text recognition in documents while also boosting general text recognition.
|
||||
- [Performance comparison between PP-OCRv4_server_rec_doc, PP-OCRv4_server_rec, and PP-OCRv4_mobile_rec](https://paddlepaddle.github.io/PaddleX/latest/en/module_usage/tutorials/ocr_modules/text_recognition.html#ii-supported-model-list)
|
||||
- Verified results show that the `PP-OCRv4_server_rec_doc` model significantly improves accuracy in both single-language (`Chinese`, `English`, `Japanese`, `Traditional Chinese`) and mixed-language scenarios, with speed comparable to `PP-OCRv4_server_rec`, making it suitable for most use cases.
|
||||
- In a small number of pure English scenarios, the `PP-OCRv4_server_rec_doc` model may encounter word concatenation issues, whereas `PP-OCRv4_server_rec` performs better in such cases. Therefore, we have retained the `PP-OCRv4_server_rec` model, which users can invoke by passing the parameter `lang='ch_server'`(python api) or `--lang ch_server`(cli).
|
||||
- 2025/04/22 1.3.7 Released
|
||||
- Fixed the issue where the `lang` parameter was ineffective during table parsing model initialization.
|
||||
- Fixed the significant slowdown in OCR and table parsing speed in `cpu` mode.
|
||||
- 2025/04/16 1.3.4 Released
|
||||
- Slightly improved the speed of OCR detection by removing some unused blocks.
|
||||
- Fixed page-level sorting errors caused by footnotes in certain cases.
|
||||
- 2025/04/12 1.3.2 released
|
||||
- Fixed the issue of incompatible dependency package versions when installing in Python 3.13 environment on Windows systems.
|
||||
- Optimized memory usage during batch inference.
|
||||
- Improved the parsing effect of tables rotated by 90 degrees.
|
||||
- Enhanced the parsing accuracy for large tables in financial report samples.
|
||||
- Fixed the occasional word concatenation issue in English text areas when OCR language is not specified.(The model needs to be updated)
|
||||
- 2025/04/08 1.3.1 released, fixed some compatibility issues
|
||||
- Supported Python 3.13
|
||||
- Made the final adaptation for some outdated Linux systems (e.g., CentOS 7), and no further support will be guaranteed for subsequent versions. [Installation Instructions](https://github.com/opendatalab/MinerU/issues/1004)
|
||||
- 2025/04/03 1.3.0 released, in this version we made many optimizations and improvements:
|
||||
- Installation and compatibility optimization
|
||||
- By removing the use of `layoutlmv3` in layout, resolved compatibility issues caused by `detectron2`.
|
||||
- Torch version compatibility extended to 2.2~2.6 (excluding 2.5).
|
||||
- CUDA compatibility supports 11.8/12.4/12.6/12.8 (CUDA version determined by torch), resolving compatibility issues for some users with 50-series and H-series GPUs.
|
||||
- Python compatible versions expanded to 3.10~3.12, solving the problem of automatic downgrade to 0.6.1 during installation in non-3.10 environments.
|
||||
- Offline deployment process optimized; no internet connection required after successful deployment to download any model files.
|
||||
- Performance optimization
|
||||
- By supporting batch processing of multiple PDF files ([script example](demo/batch_demo.py)), improved parsing speed for small files in batches (compared to version 1.0.1, formula parsing speed increased by over 1400%, overall parsing speed increased by over 500%).
|
||||
- Optimized loading and usage of the mfr model, reducing GPU memory usage and improving parsing speed (requires re-execution of the [model download process](docs/how_to_download_models_en.md) to obtain incremental updates of model files).
|
||||
- Optimized GPU memory usage, requiring only a minimum of 6GB to run this project.
|
||||
- Improved running speed on MPS devices.
|
||||
- Parsing effect optimization
|
||||
- Updated the mfr model to `unimernet(2503)`, solving the issue of lost line breaks in multi-line formulas.
|
||||
- Usability Optimization
|
||||
- By using `paddleocr2torch`, completely replaced the use of the `paddle` framework and `paddleocr` in the project, resolving conflicts between `paddle` and `torch`, as well as thread safety issues caused by the `paddle` framework.
|
||||
- Added a real-time progress bar during the parsing process to accurately track progress, making the wait less painful.
|
||||
<details>
|
||||
<summary>2025/03/03 1.2.1 released</summary>
|
||||
<ul>
|
||||
<li>Fixed the impact on punctuation marks during full-width to half-width conversion of letters and numbers</li>
|
||||
<li>Fixed caption matching inaccuracies in certain scenarios</li>
|
||||
<li>Fixed formula span loss issues in certain scenarios</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2025/02/24 1.2.0 released</summary>
|
||||
<p>This version includes several fixes and improvements to enhance parsing efficiency and accuracy:</p>
|
||||
<ul>
|
||||
<li><strong>Performance Optimization</strong>
|
||||
<ul>
|
||||
<li>Increased classification speed for PDF documents in auto mode.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><strong>Parsing Optimization</strong>
|
||||
<ul>
|
||||
<li>Improved parsing logic for documents containing watermarks, significantly enhancing the parsing results for such documents.</li>
|
||||
<li>Enhanced the matching logic for multiple images/tables and captions within a single page, improving the accuracy of image-text matching in complex layouts.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><strong>Bug Fixes</strong>
|
||||
<ul>
|
||||
<li>Fixed an issue where image/table spans were incorrectly filled into text blocks under certain conditions.</li>
|
||||
<li>Resolved an issue where title blocks were empty in some cases.</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2025/01/22 1.1.0 released</summary>
|
||||
<p>In this version we have focused on improving parsing accuracy and efficiency:</p>
|
||||
<ul>
|
||||
<li><strong>Model capability upgrade</strong> (requires re-executing the <a href="https://github.com/opendatalab/MinerU/blob/master/docs/how_to_download_models_en.md">model download process</a> to obtain incremental updates of model files)
|
||||
<ul>
|
||||
<li>The layout recognition model has been upgraded to the latest <code>doclayout_yolo(2501)</code> model, improving layout recognition accuracy.</li>
|
||||
<li>The formula parsing model has been upgraded to the latest <code>unimernet(2501)</code> model, improving formula recognition accuracy.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><strong>Performance optimization</strong>
|
||||
<ul>
|
||||
<li>On devices that meet certain configuration requirements (16GB+ VRAM), by optimizing resource usage and restructuring the processing pipeline, overall parsing speed has been increased by more than 50%.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><strong>Parsing effect optimization</strong>
|
||||
<ul>
|
||||
<li>Added a new heading classification feature (testing version, enabled by default) to the online demo (<a href="https://mineru.net/OpenSourceTools/Extractor">mineru.net</a>/<a href="https://huggingface.co/spaces/opendatalab/MinerU">huggingface</a>/<a href="https://www.modelscope.cn/studios/OpenDataLab/MinerU">modelscope</a>), which supports hierarchical classification of headings, thereby enhancing document structuring.</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2025/01/10 1.0.1 released</summary>
|
||||
<p>This is our first official release, where we have introduced a completely new API interface and enhanced compatibility through extensive refactoring, as well as a brand new automatic language identification feature:</p>
|
||||
<ul>
|
||||
<li><strong>New API Interface</strong>
|
||||
<ul>
|
||||
<li>For the data-side API, we have introduced the Dataset class, designed to provide a robust and flexible data processing framework. This framework currently supports a variety of document formats, including images (.jpg and .png), PDFs, Word documents (.doc and .docx), and PowerPoint presentations (.ppt and .pptx). It ensures effective support for data processing tasks ranging from simple to complex.</li>
|
||||
<li>For the user-side API, we have meticulously designed the MinerU processing workflow as a series of composable Stages. Each Stage represents a specific processing step, allowing users to define new Stages according to their needs and creatively combine these stages to customize their data processing workflows.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><strong>Enhanced Compatibility</strong>
|
||||
<ul>
|
||||
<li>By optimizing the dependency environment and configuration items, we ensure stable and efficient operation on ARM architecture Linux systems.</li>
|
||||
<li>We have deeply integrated with Huawei Ascend NPU acceleration, providing autonomous and controllable high-performance computing capabilities. This supports the localization and development of AI application platforms in China. <a href="https://github.com/opendatalab/MinerU/blob/master/docs/README_Ascend_NPU_Acceleration_zh_CN.md">Ascend NPU Acceleration</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><strong>Automatic Language Identification</strong>
|
||||
<ul>
|
||||
<li>By introducing a new language recognition model, setting the <code>lang</code> configuration to <code>auto</code> during document parsing will automatically select the appropriate OCR language model, improving the accuracy of scanned document parsing.</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/11/22 0.10.0 released</summary>
|
||||
<p>Introducing hybrid OCR text extraction capabilities:</p>
|
||||
<ul>
|
||||
<li>Significantly improved parsing performance in complex text distribution scenarios such as dense formulas, irregular span regions, and text represented by images.</li>
|
||||
<li>Combines the dual advantages of accurate content extraction and faster speed in text mode, and more precise span/line region recognition in OCR mode.</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/11/15 0.9.3 released</summary>
|
||||
<p>Integrated <a href="https://github.com/RapidAI/RapidTable">RapidTable</a> for table recognition, improving single-table parsing speed by more than 10 times, with higher accuracy and lower GPU memory usage.</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/11/06 0.9.2 released</summary>
|
||||
<p>Integrated the <a href="https://huggingface.co/U4R/StructTable-InternVL2-1B">StructTable-InternVL2-1B</a> model for table recognition functionality.</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/10/31 0.9.0 released</summary>
|
||||
<p>This is a major new version with extensive code refactoring, addressing numerous issues, improving performance, reducing hardware requirements, and enhancing usability:</p>
|
||||
<ul>
|
||||
<li>Refactored the sorting module code to use <a href="https://github.com/ppaanngggg/layoutreader">layoutreader</a> for reading order sorting, ensuring high accuracy in various layouts.</li>
|
||||
<li>Refactored the paragraph concatenation module to achieve good results in cross-column, cross-page, cross-figure, and cross-table scenarios.</li>
|
||||
<li>Refactored the list and table of contents recognition functions, significantly improving the accuracy of list blocks and table of contents blocks, as well as the parsing of corresponding text paragraphs.</li>
|
||||
<li>Refactored the matching logic for figures, tables, and descriptive text, greatly enhancing the accuracy of matching captions and footnotes to figures and tables, and reducing the loss rate of descriptive text to near zero.</li>
|
||||
<li>Added multi-language support for OCR, supporting detection and recognition of 84 languages. For the list of supported languages, see <a href="https://paddlepaddle.github.io/PaddleOCR/latest/en/ppocr/blog/multi_languages.html#5-support-languages-and-abbreviations">OCR Language Support List</a>.</li>
|
||||
<li>Added memory recycling logic and other memory optimization measures, significantly reducing memory usage. The memory requirement for enabling all acceleration features except table acceleration (layout/formula/OCR) has been reduced from 16GB to 8GB, and the memory requirement for enabling all acceleration features has been reduced from 24GB to 10GB.</li>
|
||||
<li>Optimized configuration file feature switches, adding an independent formula detection switch to significantly improve speed and parsing results when formula detection is not needed.</li>
|
||||
<li>Integrated <a href="https://github.com/opendatalab/PDF-Extract-Kit">PDF-Extract-Kit 1.0</a>:
|
||||
<ul>
|
||||
<li>Added the self-developed <code>doclayout_yolo</code> model, which speeds up processing by more than 10 times compared to the original solution while maintaining similar parsing effects, and can be freely switched with <code>layoutlmv3</code> via the configuration file.</li>
|
||||
<li>Upgraded formula parsing to <code>unimernet 0.2.1</code>, improving formula parsing accuracy while significantly reducing memory usage.</li>
|
||||
<li>Due to the repository change for <code>PDF-Extract-Kit 1.0</code>, you need to re-download the model. Please refer to <a href="https://github.com/opendatalab/MinerU/blob/master/docs/how_to_download_models_en.md">How to Download Models</a> for detailed steps.</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/09/27 Version 0.8.1 released</summary>
|
||||
<p>Fixed some bugs, and providing a <a href="https://github.com/opendatalab/MinerU/blob/master/projects/web_demo/README.md">localized deployment version</a> of the <a href="https://opendatalab.com/OpenSourceTools/Extractor/PDF/">online demo</a> and the <a href="https://github.com/opendatalab/MinerU/blob/master/projects/web/README.md">front-end interface</a>.</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/09/09 Version 0.8.0 released</summary>
|
||||
<p>Supporting fast deployment with Dockerfile, and launching demos on Huggingface and Modelscope.</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/08/30 Version 0.7.1 released</summary>
|
||||
<p>Add paddle tablemaster table recognition option</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/08/09 Version 0.7.0b1 released</summary>
|
||||
<p>Simplified installation process, added table recognition functionality</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/08/01 Version 0.6.2b1 released</summary>
|
||||
<p>Optimized dependency conflict issues and installation documentation</p>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>2024/07/05 Initial open-source release</summary>
|
||||
</details>
|
||||
|
||||
<!-- TABLE OF CONTENT -->
|
||||
|
||||
<details open="open">
|
||||
<summary><h2 style="display: inline-block">Table of Contents</h2></summary>
|
||||
<ol>
|
||||
<li>
|
||||
<a href="#mineru">MinerU</a>
|
||||
<ul>
|
||||
<li><a href="#project-introduction">Project Introduction</a></li>
|
||||
<li><a href="#key-features">Key Features</a></li>
|
||||
<li><a href="#quick-start">Quick Start</a>
|
||||
<ul>
|
||||
<li><a href="#online-demo">Online Demo</a></li>
|
||||
<li><a href="#quick-cpu-demo">Quick CPU Demo</a></li>
|
||||
<li><a href="#using-gpu">Using GPU</a></li>
|
||||
<li><a href="#using-npu">Using NPU</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a href="#usage">Usage</a>
|
||||
<ul>
|
||||
<li><a href="#command-line">Command Line</a></li>
|
||||
<li><a href="#api">API</a></li>
|
||||
<li><a href="#deploy-derived-projects">Deploy Derived Projects</a></li>
|
||||
<li><a href="#development-guide">Development Guide</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">All Thanks To Our Contributors</a></li>
|
||||
<li><a href="#license-information">License Information</a></li>
|
||||
<li><a href="#acknowledgments">Acknowledgments</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</a></li>
|
||||
<li><a href="#magic-html">Magic-html</a></li>
|
||||
<li><a href="#links">Links</a></li>
|
||||
</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**.
|
||||
|
||||
https://github.com/user-attachments/assets/4bea02c9-6d54-4cd6-97ed-dff14340982c
|
||||
|
||||
## Key Features
|
||||
|
||||
- Remove headers, footers, footnotes, page numbers, etc., to ensure semantic coherence.
|
||||
- Output text in human-readable order, suitable for single-column, multi-column, and complex layouts.
|
||||
- Preserve the structure of the original document, including headings, paragraphs, lists, etc.
|
||||
- Extract images, image descriptions, tables, table titles, and footnotes.
|
||||
- Automatically recognize and convert formulas in the document to LaTeX format.
|
||||
- Automatically recognize and convert tables in the document to HTML format.
|
||||
- Automatically detect scanned PDFs and garbled PDFs and enable OCR functionality.
|
||||
- OCR supports detection and recognition of 84 languages.
|
||||
- Supports multiple output formats, such as multimodal and NLP Markdown, JSON sorted by reading order, and rich intermediate formats.
|
||||
- Supports various visualization results, including layout visualization and span visualization, for efficient confirmation of output quality.
|
||||
- Supports running in a pure CPU environment, and also supports GPU(CUDA)/NPU(CANN)/MPS acceleration
|
||||
- Compatible with Windows, Linux, and Mac platforms.
|
||||
|
||||
## Quick Start
|
||||
|
||||
If 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)
|
||||
- Accelerate inference by using CUDA/CANN/MPS
|
||||
- [Linux/Windows + CUDA](#Using-GPU)
|
||||
- [Linux + CANN](#using-npu)
|
||||
- [MacOS + MPS](#using-mps)
|
||||
|
||||
> [!WARNING]
|
||||
> **Pre-installation Notice—Hardware and Software Environment Support**
|
||||
>
|
||||
> To ensure the stability and reliability of the project, we only optimize and test for specific hardware and software environments during development. This ensures that users deploying and running the project on recommended system configurations will get the best performance with the fewest compatibility issues.
|
||||
>
|
||||
> By focusing resources on the mainline environment, our team can more efficiently resolve potential bugs and develop new features.
|
||||
>
|
||||
> In non-mainline environments, due to the diversity of hardware and software configurations, as well as third-party dependency compatibility issues, we cannot guarantee 100% project availability. Therefore, for users who wish to use this project in non-recommended environments, we suggest carefully reading the documentation and FAQ first. Most issues already have corresponding solutions in the FAQ. We also encourage community feedback to help us gradually expand support.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td colspan="3" rowspan="2">Operating System</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Linux after 2019</td>
|
||||
<td>Windows 10 / 11</td>
|
||||
<td>macOS 11+</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3">CPU</td>
|
||||
<td>x86_64 / arm64</td>
|
||||
<td>x86_64(unsupported ARM Windows)</td>
|
||||
<td>x86_64 / arm64</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3">Memory Requirements</td>
|
||||
<td colspan="3">16GB or more, recommended 32GB+</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3">Storage Requirements</td>
|
||||
<td colspan="3">20GB or more, with a preference for SSD</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3">Python Version</td>
|
||||
<td colspan="3">3.10~3.13</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3">Nvidia Driver Version</td>
|
||||
<td>latest (Proprietary Driver)</td>
|
||||
<td>latest</td>
|
||||
<td>None</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3">CUDA Environment</td>
|
||||
<td colspan="2"><a href="https://pytorch.org/get-started/locally/">Refer to the PyTorch official website</a></td>
|
||||
<td>None</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="3">CANN Environment(NPU support)</td>
|
||||
<td>8.0+(Ascend 910b)</td>
|
||||
<td>None</td>
|
||||
<td>None</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td rowspan="2">GPU/MPS Hardware Support List</td>
|
||||
<td colspan="2">GPU VRAM 6GB or more</td>
|
||||
<td colspan="2">All GPUs with Tensor Cores produced from Volta(2017) onwards.<br>
|
||||
More than 6GB VRAM </td>
|
||||
<td rowspan="2">Apple silicon</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
### Online Demo
|
||||
|
||||
Synced with dev branch updates:
|
||||
|
||||
[](https://mineru.net/OpenSourceTools/Extractor?source=github)
|
||||
[](https://huggingface.co/spaces/opendatalab/MinerU)
|
||||
[](https://www.modelscope.cn/studios/OpenDataLab/MinerU)
|
||||
|
||||
### Quick CPU Demo
|
||||
|
||||
#### 1. Install magic-pdf
|
||||
|
||||
```bash
|
||||
conda create -n mineru 'python=3.12' -y
|
||||
conda activate mineru
|
||||
pip install -U "magic-pdf[full]"
|
||||
```
|
||||
|
||||
#### 2. Download model weight files
|
||||
|
||||
Refer to [How to Download Model Files](docs/how_to_download_models_en.md) for detailed instructions.
|
||||
|
||||
#### 3. Modify the Configuration File for Additional Configuration
|
||||
|
||||
After completing the [2. Download model weight files](#2-download-model-weight-files) step, the script will automatically generate a `magic-pdf.json` file in the user directory and configure the default model path.
|
||||
You can find the `magic-pdf.json` file in your 【user directory】.
|
||||
|
||||
> [!TIP]
|
||||
> The user directory for Windows is "C:\\Users\\username", for Linux it is "/home/username", and for macOS it is "/Users/username".
|
||||
|
||||
You can modify certain configurations in this file to enable or disable features, such as table recognition:
|
||||
|
||||
|
||||
> [!NOTE]
|
||||
> If the following items are not present in the JSON, please manually add the required items and remove the comment content (standard JSON does not support comments).
|
||||
|
||||
```json
|
||||
{
|
||||
// other config
|
||||
"layout-config": {
|
||||
"model": "doclayout_yolo"
|
||||
},
|
||||
"formula-config": {
|
||||
"mfd_model": "yolo_v8_mfd",
|
||||
"mfr_model": "unimernet_small",
|
||||
"enable": true // The formula recognition feature is enabled by default. If you need to disable it, please change the value here to "false".
|
||||
},
|
||||
"table-config": {
|
||||
"model": "rapid_table",
|
||||
"sub_model": "slanet_plus",
|
||||
"enable": true, // The table recognition feature is enabled by default. If you need to disable it, please change the value here to "false".
|
||||
"max_time": 400
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 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
|
||||
> [!IMPORTANT]
|
||||
> Docker requires a GPU with at least 6GB 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/docker/global/Dockerfile -O Dockerfile
|
||||
docker build -t mineru:latest .
|
||||
docker run -it --name mineru --gpus=all mineru:latest /bin/bash -c "echo 'source /opt/mineru_venv/bin/activate' >> ~/.bashrc && exec bash"
|
||||
magic-pdf --help
|
||||
```
|
||||
|
||||
### Using NPU
|
||||
|
||||
If your device has NPU acceleration hardware, you can follow the tutorial below to use NPU acceleration:
|
||||
|
||||
[Ascend NPU Acceleration](docs/README_Ascend_NPU_Acceleration_zh_CN.md)
|
||||
|
||||
### Using MPS
|
||||
|
||||
If your device uses Apple silicon chips, you can enable MPS acceleration for your tasks.
|
||||
|
||||
You can enable MPS acceleration by setting the `device-mode` parameter to `mps` in the `magic-pdf.json` configuration file.
|
||||
|
||||
```json
|
||||
{
|
||||
// other config
|
||||
"device-mode": "mps"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
### Command Line
|
||||
|
||||
[Using MinerU via Command Line](https://mineru.readthedocs.io/en/latest/user_guide/usage/command_line.html)
|
||||
|
||||
> [!TIP]
|
||||
> For more information about the output files, please refer to the [Output File Description](docs/output_file_en_us.md).
|
||||
|
||||
### API
|
||||
|
||||
[Using MinerU via Python API](https://mineru.readthedocs.io/en/latest/user_guide/usage/api.html)
|
||||
|
||||
|
||||
### Deploy Derived Projects
|
||||
|
||||
Derived projects include secondary development projects based on MinerU by project developers and community developers,
|
||||
such as application interfaces based on Gradio, RAG based on llama, web demos similar to the official website, lightweight multi-GPU load balancing client/server ends, etc.
|
||||
These projects may offer more features and a better user experience.
|
||||
For specific deployment methods, please refer to the [Derived Project README](projects/README.md)
|
||||
|
||||
|
||||
### Development Guide
|
||||
|
||||
TODO
|
||||
|
||||
# TODO
|
||||
|
||||
- [x] Reading order based on the model
|
||||
- [x] Recognition of `index` and `list` in the main text
|
||||
- [x] Table recognition
|
||||
- [x] Heading Classification
|
||||
- [ ] Code block recognition in the main text
|
||||
- [ ] [Chemical formula recognition](docs/chemical_knowledge_introduction/introduction.pdf)
|
||||
- [ ] Geometric shape recognition
|
||||
|
||||
# Known Issues
|
||||
|
||||
- Reading order is determined by the model based on the spatial distribution of readable content, and may be out of order in some areas under extremely complex layouts.
|
||||
- Vertical text is not supported.
|
||||
- Tables of contents and lists are recognized through rules, and some uncommon list formats may not be recognized.
|
||||
- Code blocks are not yet supported in the layout model.
|
||||
- Comic books, art albums, primary school textbooks, and exercises cannot be parsed well.
|
||||
- Table recognition may result in row/column recognition errors in complex tables.
|
||||
- OCR recognition may produce inaccurate characters in PDFs of lesser-known languages (e.g., diacritical marks in Latin script, easily confused characters in Arabic script).
|
||||
- Some formulas may not render correctly in Markdown.
|
||||
|
||||
# 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">
|
||||
<img src="https://contrib.rocks/image?repo=opendatalab/MinerU" />
|
||||
</a>
|
||||
|
||||
# License Information
|
||||
|
||||
[LICENSE.md](LICENSE.md)
|
||||
|
||||
This 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)
|
||||
- [DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO)
|
||||
- [StructEqTable](https://github.com/UniModal4Reasoning/StructEqTable-Deploy)
|
||||
- [RapidTable](https://github.com/RapidAI/RapidTable)
|
||||
- [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR)
|
||||
- [RapidOCR](https://github.com/RapidAI/RapidOCR)
|
||||
- [PaddleOCR2Pytorch](https://github.com/frotms/PaddleOCR2Pytorch)
|
||||
- [PyMuPDF](https://github.com/pymupdf/PyMuPDF)
|
||||
- [layoutreader](https://github.com/ppaanngggg/layoutreader)
|
||||
- [fast-langdetect](https://github.com/LlmKira/fast-langdetect)
|
||||
- [pdfminer.six](https://github.com/pdfminer/pdfminer.six)
|
||||
|
||||
# Citation
|
||||
|
||||
```bibtex
|
||||
@misc{wang2024mineruopensourcesolutionprecise,
|
||||
title={MinerU: An Open-Source Solution for Precise Document Content Extraction},
|
||||
author={Bin Wang and Chao Xu and Xiaomeng Zhao and Linke Ouyang and Fan Wu and Zhiyuan Zhao and Rui Xu and Kaiwen Liu and Yuan Qu and Fukai Shang and Bo Zhang and Liqun Wei and Zhihao Sui and Wei Li and Botian Shi and Yu Qiao and Dahua Lin and Conghui He},
|
||||
year={2024},
|
||||
eprint={2409.18839},
|
||||
archivePrefix={arXiv},
|
||||
primaryClass={cs.CV},
|
||||
url={https://arxiv.org/abs/2409.18839},
|
||||
}
|
||||
|
||||
@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}
|
||||
}
|
||||
```
|
||||
|
||||
# Star History
|
||||
|
||||
<a>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=opendatalab/MinerU&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=opendatalab/MinerU&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=opendatalab/MinerU&type=Date" />
|
||||
</picture>
|
||||
</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
|
||||
|
||||
# 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)
|
@ -0,0 +1,208 @@
|
||||
LICENSE.md
|
||||
README.md
|
||||
setup.py
|
||||
magic_pdf/__init__.py
|
||||
magic_pdf/pdf_parse_union_core_v2.py
|
||||
magic_pdf.egg-info/PKG-INFO
|
||||
magic_pdf.egg-info/SOURCES.txt
|
||||
magic_pdf.egg-info/dependency_links.txt
|
||||
magic_pdf.egg-info/entry_points.txt
|
||||
magic_pdf.egg-info/not-zip-safe
|
||||
magic_pdf.egg-info/requires.txt
|
||||
magic_pdf.egg-info/top_level.txt
|
||||
magic_pdf/config/__init__.py
|
||||
magic_pdf/config/constants.py
|
||||
magic_pdf/config/drop_reason.py
|
||||
magic_pdf/config/drop_tag.py
|
||||
magic_pdf/config/enums.py
|
||||
magic_pdf/config/exceptions.py
|
||||
magic_pdf/config/make_content_config.py
|
||||
magic_pdf/config/model_block_type.py
|
||||
magic_pdf/config/ocr_content_type.py
|
||||
magic_pdf/data/__init__.py
|
||||
magic_pdf/data/batch_build_dataset.py
|
||||
magic_pdf/data/dataset.py
|
||||
magic_pdf/data/read_api.py
|
||||
magic_pdf/data/schemas.py
|
||||
magic_pdf/data/utils.py
|
||||
magic_pdf/data/data_reader_writer/__init__.py
|
||||
magic_pdf/data/data_reader_writer/base.py
|
||||
magic_pdf/data/data_reader_writer/filebase.py
|
||||
magic_pdf/data/data_reader_writer/multi_bucket_s3.py
|
||||
magic_pdf/data/data_reader_writer/s3.py
|
||||
magic_pdf/data/io/__init__.py
|
||||
magic_pdf/data/io/base.py
|
||||
magic_pdf/data/io/http.py
|
||||
magic_pdf/data/io/s3.py
|
||||
magic_pdf/dict2md/__init__.py
|
||||
magic_pdf/dict2md/ocr_mkcontent.py
|
||||
magic_pdf/filter/__init__.py
|
||||
magic_pdf/filter/pdf_classify_by_type.py
|
||||
magic_pdf/filter/pdf_meta_scan.py
|
||||
magic_pdf/integrations/__init__.py
|
||||
magic_pdf/integrations/rag/__init__.py
|
||||
magic_pdf/integrations/rag/api.py
|
||||
magic_pdf/integrations/rag/type.py
|
||||
magic_pdf/integrations/rag/utils.py
|
||||
magic_pdf/libs/__init__.py
|
||||
magic_pdf/libs/boxbase.py
|
||||
magic_pdf/libs/clean_memory.py
|
||||
magic_pdf/libs/commons.py
|
||||
magic_pdf/libs/config_reader.py
|
||||
magic_pdf/libs/convert_utils.py
|
||||
magic_pdf/libs/coordinate_transform.py
|
||||
magic_pdf/libs/draw_bbox.py
|
||||
magic_pdf/libs/hash_utils.py
|
||||
magic_pdf/libs/json_compressor.py
|
||||
magic_pdf/libs/language.py
|
||||
magic_pdf/libs/local_math.py
|
||||
magic_pdf/libs/markdown_utils.py
|
||||
magic_pdf/libs/path_utils.py
|
||||
magic_pdf/libs/pdf_check.py
|
||||
magic_pdf/libs/pdf_image_tools.py
|
||||
magic_pdf/libs/performance_stats.py
|
||||
magic_pdf/libs/safe_filename.py
|
||||
magic_pdf/libs/version.py
|
||||
magic_pdf/model/__init__.py
|
||||
magic_pdf/model/batch_analyze.py
|
||||
magic_pdf/model/doc_analyze_by_custom_model.py
|
||||
magic_pdf/model/magic_model.py
|
||||
magic_pdf/model/model_list.py
|
||||
magic_pdf/model/pdf_extract_kit.py
|
||||
magic_pdf/model/pp_structure_v2.py
|
||||
magic_pdf/model/sub_modules/__init__.py
|
||||
magic_pdf/model/sub_modules/model_init.py
|
||||
magic_pdf/model/sub_modules/model_utils.py
|
||||
magic_pdf/model/sub_modules/language_detection/__init__.py
|
||||
magic_pdf/model/sub_modules/language_detection/utils.py
|
||||
magic_pdf/model/sub_modules/language_detection/yolov11/YOLOv11.py
|
||||
magic_pdf/model/sub_modules/language_detection/yolov11/__init__.py
|
||||
magic_pdf/model/sub_modules/layout/__init__.py
|
||||
magic_pdf/model/sub_modules/layout/doclayout_yolo/DocLayoutYOLO.py
|
||||
magic_pdf/model/sub_modules/layout/doclayout_yolo/__init__.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/__init__.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/backbone.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/beit.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/deit.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/model_init.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/rcnn_vl.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/visualizer.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/layoutlmft/__init__.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/layoutlmft/data/__init__.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/layoutlmft/data/cord.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/layoutlmft/data/data_collator.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/layoutlmft/data/funsd.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/layoutlmft/data/image_utils.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/layoutlmft/data/xfund.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/layoutlmft/models/__init__.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/layoutlmft/models/layoutlmv3/__init__.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/layoutlmft/models/layoutlmv3/configuration_layoutlmv3.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/layoutlmft/models/layoutlmv3/modeling_layoutlmv3.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/layoutlmft/models/layoutlmv3/tokenization_layoutlmv3.py
|
||||
magic_pdf/model/sub_modules/layout/layoutlmv3/layoutlmft/models/layoutlmv3/tokenization_layoutlmv3_fast.py
|
||||
magic_pdf/model/sub_modules/mfd/__init__.py
|
||||
magic_pdf/model/sub_modules/mfd/yolov8/YOLOv8.py
|
||||
magic_pdf/model/sub_modules/mfd/yolov8/__init__.py
|
||||
magic_pdf/model/sub_modules/mfr/__init__.py
|
||||
magic_pdf/model/sub_modules/mfr/unimernet/Unimernet.py
|
||||
magic_pdf/model/sub_modules/mfr/unimernet/__init__.py
|
||||
magic_pdf/model/sub_modules/mfr/unimernet/unimernet_hf/__init__.py
|
||||
magic_pdf/model/sub_modules/mfr/unimernet/unimernet_hf/modeling_unimernet.py
|
||||
magic_pdf/model/sub_modules/mfr/unimernet/unimernet_hf/unimer_mbart/__init__.py
|
||||
magic_pdf/model/sub_modules/mfr/unimernet/unimernet_hf/unimer_mbart/configuration_unimer_mbart.py
|
||||
magic_pdf/model/sub_modules/mfr/unimernet/unimernet_hf/unimer_mbart/modeling_unimer_mbart.py
|
||||
magic_pdf/model/sub_modules/mfr/unimernet/unimernet_hf/unimer_mbart/tokenization_unimer_mbart.py
|
||||
magic_pdf/model/sub_modules/mfr/unimernet/unimernet_hf/unimer_swin/__init__.py
|
||||
magic_pdf/model/sub_modules/mfr/unimernet/unimernet_hf/unimer_swin/configuration_unimer_swin.py
|
||||
magic_pdf/model/sub_modules/mfr/unimernet/unimernet_hf/unimer_swin/image_processing_unimer_swin.py
|
||||
magic_pdf/model/sub_modules/mfr/unimernet/unimernet_hf/unimer_swin/modeling_unimer_swin.py
|
||||
magic_pdf/model/sub_modules/ocr/__init__.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/__init__.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/ocr_utils.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorch_paddle.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/__init__.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/base_ocr_v20.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/data/__init__.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/data/imaug/__init__.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/data/imaug/operators.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/__init__.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/common.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/architectures/__init__.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/architectures/base_model.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/__init__.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/det_mobilenet_v3.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_hgnet.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_lcnetv3.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_mobilenet_v3.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_mv1_enhance.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/backbones/rec_svtrnet.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/__init__.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/cls_head.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/det_db_head.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_ctc_head.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/heads/rec_multi_head.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/__init__.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/db_fpn.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/intracl.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/modeling/necks/rnn.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/__init__.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/cls_postprocess.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/db_postprocess.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/postprocess/rec_postprocess.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/__init__.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/arch_config.yaml
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/models_config.yml
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/dict/arabic_dict.txt
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/dict/chinese_cht_dict.txt
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/dict/cyrillic_dict.txt
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/dict/devanagari_dict.txt
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/dict/en_dict.txt
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/dict/japan_dict.txt
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/dict/ka_dict.txt
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/dict/korean_dict.txt
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/dict/latin_dict.txt
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/dict/ppocr_keys_v1.txt
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/dict/ppocrv4_doc_dict.txt
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/dict/ta_dict.txt
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/dict/te_dict.txt
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/__init__.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/__init__.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_cls.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_det.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_rec.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/predict_system.py
|
||||
magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/tools/infer/pytorchocr_utility.py
|
||||
magic_pdf/model/sub_modules/reading_oreder/__init__.py
|
||||
magic_pdf/model/sub_modules/reading_oreder/layoutreader/__init__.py
|
||||
magic_pdf/model/sub_modules/reading_oreder/layoutreader/helpers.py
|
||||
magic_pdf/model/sub_modules/reading_oreder/layoutreader/xycut.py
|
||||
magic_pdf/model/sub_modules/table/__init__.py
|
||||
magic_pdf/model/sub_modules/table/table_utils.py
|
||||
magic_pdf/model/sub_modules/table/rapidtable/__init__.py
|
||||
magic_pdf/model/sub_modules/table/rapidtable/rapid_table.py
|
||||
magic_pdf/operators/__init__.py
|
||||
magic_pdf/operators/models.py
|
||||
magic_pdf/operators/pipes.py
|
||||
magic_pdf/post_proc/__init__.py
|
||||
magic_pdf/post_proc/llm_aided.py
|
||||
magic_pdf/post_proc/para_split_v3.py
|
||||
magic_pdf/pre_proc/__init__.py
|
||||
magic_pdf/pre_proc/construct_page_dict.py
|
||||
magic_pdf/pre_proc/cut_image.py
|
||||
magic_pdf/pre_proc/ocr_detect_all_bboxes.py
|
||||
magic_pdf/pre_proc/ocr_dict_merge.py
|
||||
magic_pdf/pre_proc/ocr_span_list_modify.py
|
||||
magic_pdf/pre_proc/remove_bbox_overlap.py
|
||||
magic_pdf/resources/fasttext-langdetect/lid.176.ftz
|
||||
magic_pdf/resources/model_config/model_configs.yaml
|
||||
magic_pdf/resources/slanet_plus/slanet-plus.onnx
|
||||
magic_pdf/resources/yolov11-langdetect/yolo_v11_ft.pt
|
||||
magic_pdf/spark/__init__.py
|
||||
magic_pdf/spark/spark_api.py
|
||||
magic_pdf/tools/__init__.py
|
||||
magic_pdf/tools/cli.py
|
||||
magic_pdf/tools/cli_dev.py
|
||||
magic_pdf/tools/common.py
|
||||
magic_pdf/utils/__init__.py
|
||||
magic_pdf/utils/annotations.py
|
||||
magic_pdf/utils/office_to_pdf.py
|
@ -0,0 +1 @@
|
||||
|
@ -0,0 +1,3 @@
|
||||
[console_scripts]
|
||||
magic-pdf = magic_pdf.tools.cli:cli
|
||||
magic-pdf-dev = magic_pdf.tools.cli_dev:cli
|
@ -0,0 +1 @@
|
||||
|
@ -0,0 +1,50 @@
|
||||
boto3>=1.28.43
|
||||
Brotli>=1.1.0
|
||||
click>=8.1.7
|
||||
fast-langdetect<0.3.0,>=0.2.3
|
||||
loguru>=0.6.0
|
||||
numpy>=1.21.6
|
||||
pydantic<2.11,>=2.7.2
|
||||
PyMuPDF<1.25.0,>=1.24.9
|
||||
scikit-learn>=1.0.2
|
||||
torch!=2.5.0,!=2.5.1,<3,>=2.2.2
|
||||
torchvision
|
||||
transformers!=4.51.0,<5.0.0,>=4.49.0
|
||||
pdfminer.six==20250506
|
||||
tqdm>=4.67.1
|
||||
|
||||
[full]
|
||||
matplotlib<4,>=3.10
|
||||
ultralytics<9,>=8.3.48
|
||||
doclayout_yolo==0.0.2b1
|
||||
dill<1,>=0.3.8
|
||||
rapid_table<2.0.0,>=1.0.5
|
||||
PyYAML<7,>=6.0.2
|
||||
ftfy<7,>=6.3.1
|
||||
openai<2,>=1.70.0
|
||||
shapely<3,>=2.0.7
|
||||
pyclipper<2,>=1.3.0
|
||||
omegaconf<3,>=2.3.0
|
||||
|
||||
[full_old_linux]
|
||||
matplotlib<=3.10.1,>=3.10
|
||||
ultralytics<=8.3.104,>=8.3.48
|
||||
doclayout_yolo==0.0.2b1
|
||||
dill==0.3.8
|
||||
PyYAML==6.0.2
|
||||
ftfy==6.3.1
|
||||
openai==1.71.0
|
||||
shapely==2.1.0
|
||||
pyclipper==1.3.0.post6
|
||||
omegaconf==2.3.0
|
||||
albumentations==1.4.20
|
||||
rapid_table==1.0.3
|
||||
|
||||
[lite]
|
||||
paddleocr==2.7.3
|
||||
|
||||
[lite:platform_system == "Linux"]
|
||||
paddlepaddle==3.0.0b1
|
||||
|
||||
[lite:platform_system == "Windows" or platform_system == "Darwin"]
|
||||
paddlepaddle==2.6.1
|
@ -0,0 +1 @@
|
||||
magic_pdf
|
@ -0,0 +1,60 @@
|
||||
"""span维度自定义字段."""
|
||||
# span是否是跨页合并的
|
||||
CROSS_PAGE = 'cross_page'
|
||||
|
||||
"""
|
||||
block维度自定义字段
|
||||
"""
|
||||
# block中lines是否被删除
|
||||
LINES_DELETED = 'lines_deleted'
|
||||
|
||||
# table recognition max time default value
|
||||
TABLE_MAX_TIME_VALUE = 400
|
||||
|
||||
# pp_table_result_max_length
|
||||
TABLE_MAX_LEN = 480
|
||||
|
||||
# table master structure dict
|
||||
TABLE_MASTER_DICT = 'table_master_structure_dict.txt'
|
||||
|
||||
# table master dir
|
||||
TABLE_MASTER_DIR = 'table_structure_tablemaster_infer/'
|
||||
|
||||
# pp detect model dir
|
||||
DETECT_MODEL_DIR = 'ch_PP-OCRv4_det_infer'
|
||||
|
||||
# pp rec model dir
|
||||
REC_MODEL_DIR = 'ch_PP-OCRv4_rec_infer'
|
||||
|
||||
# pp rec char dict path
|
||||
REC_CHAR_DICT = 'ppocr_keys_v1.txt'
|
||||
|
||||
# pp rec copy rec directory
|
||||
PP_REC_DIRECTORY = '.paddleocr/whl/rec/ch/ch_PP-OCRv4_rec_infer'
|
||||
|
||||
# pp rec copy det directory
|
||||
PP_DET_DIRECTORY = '.paddleocr/whl/det/ch/ch_PP-OCRv4_det_infer'
|
||||
|
||||
|
||||
class MODEL_NAME:
|
||||
# pp table structure algorithm
|
||||
TABLE_MASTER = 'tablemaster'
|
||||
# struct eqtable
|
||||
STRUCT_EQTABLE = 'struct_eqtable'
|
||||
|
||||
DocLayout_YOLO = 'doclayout_yolo'
|
||||
|
||||
LAYOUTLMv3 = 'layoutlmv3'
|
||||
|
||||
YOLO_V8_MFD = 'yolo_v8_mfd'
|
||||
|
||||
UniMerNet_v2_Small = 'unimernet_small'
|
||||
|
||||
RAPID_TABLE = 'rapid_table'
|
||||
|
||||
YOLO_V11_LangDetect = 'yolo_v11n_langdetect'
|
||||
|
||||
|
||||
PARSE_TYPE_TXT = 'txt'
|
||||
PARSE_TYPE_OCR = 'ocr'
|
||||
|
@ -0,0 +1,19 @@
|
||||
|
||||
COLOR_BG_HEADER_TXT_BLOCK = 'color_background_header_txt_block'
|
||||
PAGE_NO = 'page-no' # 页码
|
||||
CONTENT_IN_FOOT_OR_HEADER = 'in-foot-header-area' # 页眉页脚内的文本
|
||||
VERTICAL_TEXT = 'vertical-text' # 垂直文本
|
||||
ROTATE_TEXT = 'rotate-text' # 旋转文本
|
||||
EMPTY_SIDE_BLOCK = 'empty-side-block' # 边缘上的空白没有任何内容的block
|
||||
ON_IMAGE_TEXT = 'on-image-text' # 文本在图片上
|
||||
ON_TABLE_TEXT = 'on-table-text' # 文本在表格上
|
||||
|
||||
|
||||
class DropTag:
|
||||
PAGE_NUMBER = 'page_no'
|
||||
HEADER = 'header'
|
||||
FOOTER = 'footer'
|
||||
FOOTNOTE = 'footnote'
|
||||
NOT_IN_LAYOUT = 'not_in_layout'
|
||||
SPAN_OVERLAP = 'span_overlap'
|
||||
BLOCK_OVERLAP = 'block_overlap'
|
@ -0,0 +1,7 @@
|
||||
|
||||
import enum
|
||||
|
||||
|
||||
class SupportedPdfParseMethod(enum.Enum):
|
||||
OCR = 'ocr'
|
||||
TXT = 'txt'
|
@ -0,0 +1,39 @@
|
||||
|
||||
class FileNotExisted(Exception):
|
||||
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
|
||||
def __str__(self):
|
||||
return f'File {self.path} does not exist.'
|
||||
|
||||
|
||||
class InvalidConfig(Exception):
|
||||
def __init__(self, msg):
|
||||
self.msg = msg
|
||||
|
||||
def __str__(self):
|
||||
return f'Invalid config: {self.msg}'
|
||||
|
||||
|
||||
class InvalidParams(Exception):
|
||||
def __init__(self, msg):
|
||||
self.msg = msg
|
||||
|
||||
def __str__(self):
|
||||
return f'Invalid params: {self.msg}'
|
||||
|
||||
|
||||
class EmptyData(Exception):
|
||||
def __init__(self, msg):
|
||||
self.msg = msg
|
||||
|
||||
def __str__(self):
|
||||
return f'Empty data: {self.msg}'
|
||||
|
||||
class CUDA_NOT_AVAILABLE(Exception):
|
||||
def __init__(self, msg):
|
||||
self.msg = msg
|
||||
|
||||
def __str__(self):
|
||||
return f'CUDA not available: {self.msg}'
|
@ -0,0 +1,11 @@
|
||||
class MakeMode:
|
||||
MM_MD = 'mm_markdown'
|
||||
NLP_MD = 'nlp_markdown'
|
||||
STANDARD_FORMAT = 'standard_format'
|
||||
|
||||
|
||||
class DropMode:
|
||||
WHOLE_PDF = 'whole_pdf'
|
||||
SINGLE_PAGE = 'single_page'
|
||||
NONE = 'none'
|
||||
NONE_WITH_REASON = 'none_with_reason'
|
@ -0,0 +1,10 @@
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class ModelBlockTypeEnum(Enum):
|
||||
TITLE = 0
|
||||
PLAIN_TEXT = 1
|
||||
ABANDON = 2
|
||||
ISOLATE_FORMULA = 8
|
||||
EMBEDDING = 13
|
||||
ISOLATED = 14
|
@ -0,0 +1,40 @@
|
||||
class ContentType:
|
||||
Image = 'image'
|
||||
Table = 'table'
|
||||
Text = 'text'
|
||||
InlineEquation = 'inline_equation'
|
||||
InterlineEquation = 'interline_equation'
|
||||
|
||||
|
||||
class BlockType:
|
||||
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'
|
||||
List = 'list'
|
||||
Index = 'index'
|
||||
|
||||
|
||||
class CategoryId:
|
||||
Title = 0
|
||||
Text = 1
|
||||
Abandon = 2
|
||||
ImageBody = 3
|
||||
ImageCaption = 4
|
||||
TableBody = 5
|
||||
TableCaption = 6
|
||||
TableFootnote = 7
|
||||
InterlineEquation_Layout = 8
|
||||
InlineEquation = 13
|
||||
InterlineEquation_YOLO = 14
|
||||
OcrText = 15
|
||||
ImageFootnote = 101
|
@ -0,0 +1,167 @@
|
||||
import concurrent.futures
|
||||
|
||||
import fitz
|
||||
|
||||
from magic_pdf.data.dataset import PymuDocDataset
|
||||
from magic_pdf.data.utils import fitz_doc_to_image # PyMuPDF
|
||||
|
||||
|
||||
def partition_array_greedy(arr, k):
|
||||
"""Partition an array into k parts using a simple greedy approach.
|
||||
|
||||
Parameters:
|
||||
-----------
|
||||
arr : list
|
||||
The input array of integers
|
||||
k : int
|
||||
Number of partitions to create
|
||||
|
||||
Returns:
|
||||
--------
|
||||
partitions : list of lists
|
||||
The k partitions of the array
|
||||
"""
|
||||
# Handle edge cases
|
||||
if k <= 0:
|
||||
raise ValueError('k must be a positive integer')
|
||||
if k > len(arr):
|
||||
k = len(arr) # Adjust k if it's too large
|
||||
if k == 1:
|
||||
return [list(range(len(arr)))]
|
||||
if k == len(arr):
|
||||
return [[i] for i in range(len(arr))]
|
||||
|
||||
# Sort the array in descending order
|
||||
sorted_indices = sorted(range(len(arr)), key=lambda i: arr[i][1], reverse=True)
|
||||
|
||||
# Initialize k empty partitions
|
||||
partitions = [[] for _ in range(k)]
|
||||
partition_sums = [0] * k
|
||||
|
||||
# Assign each element to the partition with the smallest current sum
|
||||
for idx in sorted_indices:
|
||||
# Find the partition with the smallest sum
|
||||
min_sum_idx = partition_sums.index(min(partition_sums))
|
||||
|
||||
# Add the element to this partition
|
||||
partitions[min_sum_idx].append(idx) # Store the original index
|
||||
partition_sums[min_sum_idx] += arr[idx][1]
|
||||
|
||||
return partitions
|
||||
|
||||
|
||||
def process_pdf_batch(pdf_jobs, idx):
|
||||
"""Process a batch of PDF pages using multiple threads.
|
||||
|
||||
Parameters:
|
||||
-----------
|
||||
pdf_jobs : list of tuples
|
||||
List of (pdf_path, page_num) tuples
|
||||
output_dir : str or None
|
||||
Directory to save images to
|
||||
num_threads : int
|
||||
Number of threads to use
|
||||
**kwargs :
|
||||
Additional arguments for process_pdf_page
|
||||
|
||||
Returns:
|
||||
--------
|
||||
images : list
|
||||
List of processed images
|
||||
"""
|
||||
images = []
|
||||
|
||||
for pdf_path, _ in pdf_jobs:
|
||||
doc = fitz.open(pdf_path)
|
||||
tmp = []
|
||||
for page_num in range(len(doc)):
|
||||
page = doc[page_num]
|
||||
tmp.append(fitz_doc_to_image(page))
|
||||
images.append(tmp)
|
||||
return (idx, images)
|
||||
|
||||
|
||||
def batch_build_dataset(pdf_paths, k, lang=None):
|
||||
"""Process multiple PDFs by partitioning them into k balanced parts and
|
||||
processing each part in parallel.
|
||||
|
||||
Parameters:
|
||||
-----------
|
||||
pdf_paths : list
|
||||
List of paths to PDF files
|
||||
k : int
|
||||
Number of partitions to create
|
||||
output_dir : str or None
|
||||
Directory to save images to
|
||||
threads_per_worker : int
|
||||
Number of threads to use per worker
|
||||
**kwargs :
|
||||
Additional arguments for process_pdf_page
|
||||
|
||||
Returns:
|
||||
--------
|
||||
all_images : list
|
||||
List of all processed images
|
||||
"""
|
||||
|
||||
results = []
|
||||
for pdf_path in pdf_paths:
|
||||
with open(pdf_path, 'rb') as f:
|
||||
pdf_bytes = f.read()
|
||||
dataset = PymuDocDataset(pdf_bytes, lang=lang)
|
||||
results.append(dataset)
|
||||
return results
|
||||
|
||||
|
||||
#
|
||||
# # Get page counts for each PDF
|
||||
# pdf_info = []
|
||||
# total_pages = 0
|
||||
#
|
||||
# for pdf_path in pdf_paths:
|
||||
# try:
|
||||
# doc = fitz.open(pdf_path)
|
||||
# num_pages = len(doc)
|
||||
# pdf_info.append((pdf_path, num_pages))
|
||||
# total_pages += num_pages
|
||||
# doc.close()
|
||||
# except Exception as e:
|
||||
# print(f'Error opening {pdf_path}: {e}')
|
||||
#
|
||||
# # Partition the jobs based on page countEach job has 1 page
|
||||
# partitions = partition_array_greedy(pdf_info, k)
|
||||
#
|
||||
# # Process each partition in parallel
|
||||
# all_images_h = {}
|
||||
#
|
||||
# with concurrent.futures.ProcessPoolExecutor(max_workers=k) as executor:
|
||||
# # Submit one task per partition
|
||||
# futures = []
|
||||
# for sn, partition in enumerate(partitions):
|
||||
# # Get the jobs for this partition
|
||||
# partition_jobs = [pdf_info[idx] for idx in partition]
|
||||
#
|
||||
# # Submit the task
|
||||
# future = executor.submit(
|
||||
# process_pdf_batch,
|
||||
# partition_jobs,
|
||||
# sn
|
||||
# )
|
||||
# futures.append(future)
|
||||
# # Process results as they complete
|
||||
# for i, future in enumerate(concurrent.futures.as_completed(futures)):
|
||||
# try:
|
||||
# idx, images = future.result()
|
||||
# all_images_h[idx] = images
|
||||
# except Exception as e:
|
||||
# print(f'Error processing partition: {e}')
|
||||
# results = [None] * len(pdf_paths)
|
||||
# for i in range(len(partitions)):
|
||||
# partition = partitions[i]
|
||||
# for j in range(len(partition)):
|
||||
# with open(pdf_info[partition[j]][0], 'rb') as f:
|
||||
# pdf_bytes = f.read()
|
||||
# dataset = PymuDocDataset(pdf_bytes, lang=lang)
|
||||
# dataset.set_images(all_images_h[i][j])
|
||||
# results[partition[j]] = dataset
|
||||
# return results
|
@ -0,0 +1,12 @@
|
||||
from magic_pdf.data.data_reader_writer.filebase import \
|
||||
FileBasedDataReader # noqa: F401
|
||||
from magic_pdf.data.data_reader_writer.filebase import \
|
||||
FileBasedDataWriter # noqa: F401
|
||||
from magic_pdf.data.data_reader_writer.multi_bucket_s3 import \
|
||||
MultiBucketS3DataReader # noqa: F401
|
||||
from magic_pdf.data.data_reader_writer.multi_bucket_s3 import \
|
||||
MultiBucketS3DataWriter # noqa: F401
|
||||
from magic_pdf.data.data_reader_writer.s3 import S3DataReader # noqa: F401
|
||||
from magic_pdf.data.data_reader_writer.s3 import S3DataWriter # noqa: F401
|
||||
from magic_pdf.data.data_reader_writer.base import DataReader # noqa: F401
|
||||
from magic_pdf.data.data_reader_writer.base import DataWriter # noqa: F401
|
@ -0,0 +1,63 @@
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
class DataReader(ABC):
|
||||
|
||||
def read(self, path: str) -> bytes:
|
||||
"""Read the file.
|
||||
|
||||
Args:
|
||||
path (str): file path to read
|
||||
|
||||
Returns:
|
||||
bytes: the content of the file
|
||||
"""
|
||||
return self.read_at(path)
|
||||
|
||||
@abstractmethod
|
||||
def read_at(self, path: str, offset: int = 0, limit: int = -1) -> bytes:
|
||||
"""Read the file at offset and limit.
|
||||
|
||||
Args:
|
||||
path (str): the file path
|
||||
offset (int, optional): the number of bytes skipped. Defaults to 0.
|
||||
limit (int, optional): the length of bytes want to read. Defaults to -1.
|
||||
|
||||
Returns:
|
||||
bytes: the content of the file
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class DataWriter(ABC):
|
||||
@abstractmethod
|
||||
def write(self, path: str, data: bytes) -> None:
|
||||
"""Write the data to the file.
|
||||
|
||||
Args:
|
||||
path (str): the target file where to write
|
||||
data (bytes): the data want to write
|
||||
"""
|
||||
pass
|
||||
|
||||
def write_string(self, path: str, data: str) -> None:
|
||||
"""Write the data to file, the data will be encoded to bytes.
|
||||
|
||||
Args:
|
||||
path (str): the target file where to write
|
||||
data (str): the data want to write
|
||||
"""
|
||||
|
||||
def safe_encode(data: str, method: str):
|
||||
try:
|
||||
bit_data = data.encode(encoding=method, errors='replace')
|
||||
return bit_data, True
|
||||
except: # noqa
|
||||
return None, False
|
||||
|
||||
for method in ['utf-8', 'ascii']:
|
||||
bit_data, flag = safe_encode(data, method)
|
||||
if flag:
|
||||
self.write(path, bit_data)
|
||||
break
|
@ -0,0 +1,62 @@
|
||||
import os
|
||||
|
||||
from magic_pdf.data.data_reader_writer.base import DataReader, DataWriter
|
||||
|
||||
|
||||
class FileBasedDataReader(DataReader):
|
||||
def __init__(self, parent_dir: str = ''):
|
||||
"""Initialized with parent_dir.
|
||||
|
||||
Args:
|
||||
parent_dir (str, optional): the parent directory that may be used within methods. Defaults to ''.
|
||||
"""
|
||||
self._parent_dir = parent_dir
|
||||
|
||||
def read_at(self, path: str, offset: int = 0, limit: int = -1) -> bytes:
|
||||
"""Read at offset and limit.
|
||||
|
||||
Args:
|
||||
path (str): the path of file, if the path is relative path, it will be joined with parent_dir.
|
||||
offset (int, optional): the number of bytes skipped. Defaults to 0.
|
||||
limit (int, optional): the length of bytes want to read. Defaults to -1.
|
||||
|
||||
Returns:
|
||||
bytes: the content of file
|
||||
"""
|
||||
fn_path = path
|
||||
if not os.path.isabs(fn_path) and len(self._parent_dir) > 0:
|
||||
fn_path = os.path.join(self._parent_dir, path)
|
||||
|
||||
with open(fn_path, 'rb') as f:
|
||||
f.seek(offset)
|
||||
if limit == -1:
|
||||
return f.read()
|
||||
else:
|
||||
return f.read(limit)
|
||||
|
||||
|
||||
class FileBasedDataWriter(DataWriter):
|
||||
def __init__(self, parent_dir: str = '') -> None:
|
||||
"""Initialized with parent_dir.
|
||||
|
||||
Args:
|
||||
parent_dir (str, optional): the parent directory that may be used within methods. Defaults to ''.
|
||||
"""
|
||||
self._parent_dir = parent_dir
|
||||
|
||||
def write(self, path: str, data: bytes) -> None:
|
||||
"""Write file with data.
|
||||
|
||||
Args:
|
||||
path (str): the path of file, if the path is relative path, it will be joined with parent_dir.
|
||||
data (bytes): the data want to write
|
||||
"""
|
||||
fn_path = path
|
||||
if not os.path.isabs(fn_path) and len(self._parent_dir) > 0:
|
||||
fn_path = os.path.join(self._parent_dir, path)
|
||||
|
||||
if not os.path.exists(os.path.dirname(fn_path)) and os.path.dirname(fn_path) != "":
|
||||
os.makedirs(os.path.dirname(fn_path), exist_ok=True)
|
||||
|
||||
with open(fn_path, 'wb') as f:
|
||||
f.write(data)
|
@ -0,0 +1,145 @@
|
||||
|
||||
from magic_pdf.config.exceptions import InvalidConfig, InvalidParams
|
||||
from magic_pdf.data.data_reader_writer.base import DataReader, DataWriter
|
||||
from magic_pdf.data.io.s3 import S3Reader, S3Writer
|
||||
from magic_pdf.data.schemas import S3Config
|
||||
from magic_pdf.libs.path_utils import (parse_s3_range_params, parse_s3path,
|
||||
remove_non_official_s3_args)
|
||||
|
||||
|
||||
class MultiS3Mixin:
|
||||
def __init__(self, default_prefix: str, s3_configs: list[S3Config]):
|
||||
"""Initialized with multiple s3 configs.
|
||||
|
||||
Args:
|
||||
default_prefix (str): the default prefix of the relative path. for example, {some_bucket}/{some_prefix} or {some_bucket}
|
||||
s3_configs (list[S3Config]): list of s3 configs, the bucket_name must be unique in the list.
|
||||
|
||||
Raises:
|
||||
InvalidConfig: default bucket config not in s3_configs.
|
||||
InvalidConfig: bucket name not unique in s3_configs.
|
||||
InvalidConfig: default bucket must be provided.
|
||||
"""
|
||||
if len(default_prefix) == 0:
|
||||
raise InvalidConfig('default_prefix must be provided')
|
||||
|
||||
arr = default_prefix.strip('/').split('/')
|
||||
self.default_bucket = arr[0]
|
||||
self.default_prefix = '/'.join(arr[1:])
|
||||
|
||||
found_default_bucket_config = False
|
||||
for conf in s3_configs:
|
||||
if conf.bucket_name == self.default_bucket:
|
||||
found_default_bucket_config = True
|
||||
break
|
||||
|
||||
if not found_default_bucket_config:
|
||||
raise InvalidConfig(
|
||||
f'default_bucket: {self.default_bucket} config must be provided in s3_configs: {s3_configs}'
|
||||
)
|
||||
|
||||
uniq_bucket = set([conf.bucket_name for conf in s3_configs])
|
||||
if len(uniq_bucket) != len(s3_configs):
|
||||
raise InvalidConfig(
|
||||
f'the bucket_name in s3_configs: {s3_configs} must be unique'
|
||||
)
|
||||
|
||||
self.s3_configs = s3_configs
|
||||
self._s3_clients_h: dict = {}
|
||||
|
||||
|
||||
class MultiBucketS3DataReader(DataReader, MultiS3Mixin):
|
||||
def read(self, path: str) -> bytes:
|
||||
"""Read the path from s3, select diffect bucket client for each request
|
||||
based on the bucket, also support range read.
|
||||
|
||||
Args:
|
||||
path (str): the s3 path of file, the path must be in the format of s3://bucket_name/path?offset,limit.
|
||||
for example: s3://bucket_name/path?0,100.
|
||||
|
||||
Returns:
|
||||
bytes: the content of s3 file.
|
||||
"""
|
||||
may_range_params = parse_s3_range_params(path)
|
||||
if may_range_params is None or 2 != len(may_range_params):
|
||||
byte_start, byte_len = 0, -1
|
||||
else:
|
||||
byte_start, byte_len = int(may_range_params[0]), int(may_range_params[1])
|
||||
path = remove_non_official_s3_args(path)
|
||||
return self.read_at(path, byte_start, byte_len)
|
||||
|
||||
def __get_s3_client(self, bucket_name: str):
|
||||
if bucket_name not in set([conf.bucket_name for conf in self.s3_configs]):
|
||||
raise InvalidParams(
|
||||
f'bucket name: {bucket_name} not found in s3_configs: {self.s3_configs}'
|
||||
)
|
||||
if bucket_name not in self._s3_clients_h:
|
||||
conf = next(
|
||||
filter(lambda conf: conf.bucket_name == bucket_name, self.s3_configs)
|
||||
)
|
||||
self._s3_clients_h[bucket_name] = S3Reader(
|
||||
bucket_name,
|
||||
conf.access_key,
|
||||
conf.secret_key,
|
||||
conf.endpoint_url,
|
||||
conf.addressing_style,
|
||||
)
|
||||
return self._s3_clients_h[bucket_name]
|
||||
|
||||
def read_at(self, path: str, offset: int = 0, limit: int = -1) -> bytes:
|
||||
"""Read the file with offset and limit, select diffect bucket client
|
||||
for each request based on the bucket.
|
||||
|
||||
Args:
|
||||
path (str): the file path.
|
||||
offset (int, optional): the number of bytes skipped. Defaults to 0.
|
||||
limit (int, optional): the number of bytes want to read. Defaults to -1 which means infinite.
|
||||
|
||||
Returns:
|
||||
bytes: the file content.
|
||||
"""
|
||||
if path.startswith('s3://'):
|
||||
bucket_name, path = parse_s3path(path)
|
||||
s3_reader = self.__get_s3_client(bucket_name)
|
||||
else:
|
||||
s3_reader = self.__get_s3_client(self.default_bucket)
|
||||
if self.default_prefix:
|
||||
path = self.default_prefix + '/' + path
|
||||
return s3_reader.read_at(path, offset, limit)
|
||||
|
||||
|
||||
class MultiBucketS3DataWriter(DataWriter, MultiS3Mixin):
|
||||
def __get_s3_client(self, bucket_name: str):
|
||||
if bucket_name not in set([conf.bucket_name for conf in self.s3_configs]):
|
||||
raise InvalidParams(
|
||||
f'bucket name: {bucket_name} not found in s3_configs: {self.s3_configs}'
|
||||
)
|
||||
if bucket_name not in self._s3_clients_h:
|
||||
conf = next(
|
||||
filter(lambda conf: conf.bucket_name == bucket_name, self.s3_configs)
|
||||
)
|
||||
self._s3_clients_h[bucket_name] = S3Writer(
|
||||
bucket_name,
|
||||
conf.access_key,
|
||||
conf.secret_key,
|
||||
conf.endpoint_url,
|
||||
conf.addressing_style,
|
||||
)
|
||||
return self._s3_clients_h[bucket_name]
|
||||
|
||||
def write(self, path: str, data: bytes) -> None:
|
||||
"""Write file with data, also select diffect bucket client for each
|
||||
request based on the bucket.
|
||||
|
||||
Args:
|
||||
path (str): the path of file, if the path is relative path, it will be joined with parent_dir.
|
||||
data (bytes): the data want to write.
|
||||
"""
|
||||
if path.startswith('s3://'):
|
||||
bucket_name, path = parse_s3path(path)
|
||||
s3_writer = self.__get_s3_client(bucket_name)
|
||||
else:
|
||||
s3_writer = self.__get_s3_client(self.default_bucket)
|
||||
if self.default_prefix:
|
||||
path = self.default_prefix + '/' + path
|
||||
return s3_writer.write(path, data)
|
@ -0,0 +1,73 @@
|
||||
from magic_pdf.data.data_reader_writer.multi_bucket_s3 import (
|
||||
MultiBucketS3DataReader, MultiBucketS3DataWriter)
|
||||
from magic_pdf.data.schemas import S3Config
|
||||
|
||||
|
||||
class S3DataReader(MultiBucketS3DataReader):
|
||||
def __init__(
|
||||
self,
|
||||
default_prefix_without_bucket: str,
|
||||
bucket: str,
|
||||
ak: str,
|
||||
sk: str,
|
||||
endpoint_url: str,
|
||||
addressing_style: str = 'auto',
|
||||
):
|
||||
"""s3 reader client.
|
||||
|
||||
Args:
|
||||
default_prefix_without_bucket: prefix that not contains bucket
|
||||
bucket (str): bucket name
|
||||
ak (str): access key
|
||||
sk (str): secret key
|
||||
endpoint_url (str): endpoint url of s3
|
||||
addressing_style (str, optional): Defaults to 'auto'. Other valid options here are 'path' and 'virtual'
|
||||
refer to https://boto3.amazonaws.com/v1/documentation/api/1.9.42/guide/s3.html
|
||||
"""
|
||||
super().__init__(
|
||||
f'{bucket}/{default_prefix_without_bucket}',
|
||||
[
|
||||
S3Config(
|
||||
bucket_name=bucket,
|
||||
access_key=ak,
|
||||
secret_key=sk,
|
||||
endpoint_url=endpoint_url,
|
||||
addressing_style=addressing_style,
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
class S3DataWriter(MultiBucketS3DataWriter):
|
||||
def __init__(
|
||||
self,
|
||||
default_prefix_without_bucket: str,
|
||||
bucket: str,
|
||||
ak: str,
|
||||
sk: str,
|
||||
endpoint_url: str,
|
||||
addressing_style: str = 'auto',
|
||||
):
|
||||
"""s3 writer client.
|
||||
|
||||
Args:
|
||||
default_prefix_without_bucket: prefix that not contains bucket
|
||||
bucket (str): bucket name
|
||||
ak (str): access key
|
||||
sk (str): secret key
|
||||
endpoint_url (str): endpoint url of s3
|
||||
addressing_style (str, optional): Defaults to 'auto'. Other valid options here are 'path' and 'virtual'
|
||||
refer to https://boto3.amazonaws.com/v1/documentation/api/1.9.42/guide/s3.html
|
||||
"""
|
||||
super().__init__(
|
||||
f'{bucket}/{default_prefix_without_bucket}',
|
||||
[
|
||||
S3Config(
|
||||
bucket_name=bucket,
|
||||
access_key=ak,
|
||||
secret_key=sk,
|
||||
endpoint_url=endpoint_url,
|
||||
addressing_style=addressing_style,
|
||||
)
|
||||
],
|
||||
)
|
@ -0,0 +1,408 @@
|
||||
import os
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Callable, Iterator
|
||||
|
||||
import fitz
|
||||
from loguru import logger
|
||||
|
||||
from magic_pdf.config.enums import SupportedPdfParseMethod
|
||||
from magic_pdf.data.schemas import PageInfo
|
||||
from magic_pdf.data.utils import fitz_doc_to_image
|
||||
from magic_pdf.filter import classify
|
||||
|
||||
|
||||
class PageableData(ABC):
|
||||
@abstractmethod
|
||||
def get_image(self) -> dict:
|
||||
"""Transform data to image."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_doc(self) -> fitz.Page:
|
||||
"""Get the pymudoc page."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_page_info(self) -> PageInfo:
|
||||
"""Get the page info of the page.
|
||||
|
||||
Returns:
|
||||
PageInfo: the page info of this page
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def draw_rect(self, rect_coords, color, fill, fill_opacity, width, overlay):
|
||||
"""draw rectangle.
|
||||
|
||||
Args:
|
||||
rect_coords (list[float]): four elements array contain the top-left and bottom-right coordinates, [x0, y0, x1, y1]
|
||||
color (list[float] | None): three element tuple which describe the RGB of the board line, None means no board line
|
||||
fill (list[float] | None): fill the board with RGB, None means will not fill with color
|
||||
fill_opacity (float): opacity of the fill, range from [0, 1]
|
||||
width (float): the width of board
|
||||
overlay (bool): fill the color in foreground or background. True means fill in background.
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def insert_text(self, coord, content, fontsize, color):
|
||||
"""insert text.
|
||||
|
||||
Args:
|
||||
coord (list[float]): four elements array contain the top-left and bottom-right coordinates, [x0, y0, x1, y1]
|
||||
content (str): the text content
|
||||
fontsize (int): font size of the text
|
||||
color (list[float] | None): three element tuple which describe the RGB of the board line, None will use the default font color!
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class Dataset(ABC):
|
||||
@abstractmethod
|
||||
def __len__(self) -> int:
|
||||
"""The length of the dataset."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def __iter__(self) -> Iterator[PageableData]:
|
||||
"""Yield the page data."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def supported_methods(self) -> list[SupportedPdfParseMethod]:
|
||||
"""The methods that this dataset support.
|
||||
|
||||
Returns:
|
||||
list[SupportedPdfParseMethod]: The supported methods, Valid methods are: OCR, TXT
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def data_bits(self) -> bytes:
|
||||
"""The bits used to create this dataset."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_page(self, page_id: int) -> PageableData:
|
||||
"""Get the page indexed by page_id.
|
||||
|
||||
Args:
|
||||
page_id (int): the index of the page
|
||||
|
||||
Returns:
|
||||
PageableData: the page doc object
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def dump_to_file(self, file_path: str):
|
||||
"""Dump the file.
|
||||
|
||||
Args:
|
||||
file_path (str): the file path
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def apply(self, proc: Callable, *args, **kwargs):
|
||||
"""Apply callable method which.
|
||||
|
||||
Args:
|
||||
proc (Callable): invoke proc as follows:
|
||||
proc(self, *args, **kwargs)
|
||||
|
||||
Returns:
|
||||
Any: return the result generated by proc
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def classify(self) -> SupportedPdfParseMethod:
|
||||
"""classify the dataset.
|
||||
|
||||
Returns:
|
||||
SupportedPdfParseMethod: _description_
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def clone(self):
|
||||
"""clone this dataset."""
|
||||
pass
|
||||
|
||||
|
||||
class PymuDocDataset(Dataset):
|
||||
def __init__(self, bits: bytes, lang=None):
|
||||
"""Initialize the dataset, which wraps the pymudoc documents.
|
||||
|
||||
Args:
|
||||
bits (bytes): the bytes of the pdf
|
||||
"""
|
||||
self._raw_fitz = fitz.open('pdf', bits)
|
||||
self._records = [Doc(v) for v in self._raw_fitz]
|
||||
self._data_bits = bits
|
||||
self._raw_data = bits
|
||||
self._classify_result = None
|
||||
|
||||
if lang == '':
|
||||
self._lang = None
|
||||
elif lang == 'auto':
|
||||
from magic_pdf.model.sub_modules.language_detection.utils import \
|
||||
auto_detect_lang
|
||||
self._lang = auto_detect_lang(self._data_bits)
|
||||
logger.info(f'lang: {lang}, detect_lang: {self._lang}')
|
||||
else:
|
||||
self._lang = lang
|
||||
logger.info(f'lang: {lang}')
|
||||
|
||||
def __len__(self) -> int:
|
||||
"""The page number of the pdf."""
|
||||
return len(self._records)
|
||||
|
||||
def __iter__(self) -> Iterator[PageableData]:
|
||||
"""Yield the page doc object."""
|
||||
return iter(self._records)
|
||||
|
||||
def supported_methods(self) -> list[SupportedPdfParseMethod]:
|
||||
"""The method supported by this dataset.
|
||||
|
||||
Returns:
|
||||
list[SupportedPdfParseMethod]: the supported methods
|
||||
"""
|
||||
return [SupportedPdfParseMethod.OCR, SupportedPdfParseMethod.TXT]
|
||||
|
||||
def data_bits(self) -> bytes:
|
||||
"""The pdf bits used to create this dataset."""
|
||||
return self._data_bits
|
||||
|
||||
def get_page(self, page_id: int) -> PageableData:
|
||||
"""The page doc object.
|
||||
|
||||
Args:
|
||||
page_id (int): the page doc index
|
||||
|
||||
Returns:
|
||||
PageableData: the page doc object
|
||||
"""
|
||||
return self._records[page_id]
|
||||
|
||||
def dump_to_file(self, file_path: str):
|
||||
"""Dump the file.
|
||||
|
||||
Args:
|
||||
file_path (str): the file path
|
||||
"""
|
||||
|
||||
dir_name = os.path.dirname(file_path)
|
||||
if dir_name not in ('', '.', '..'):
|
||||
os.makedirs(dir_name, exist_ok=True)
|
||||
self._raw_fitz.save(file_path)
|
||||
|
||||
def apply(self, proc: Callable, *args, **kwargs):
|
||||
"""Apply callable method which.
|
||||
|
||||
Args:
|
||||
proc (Callable): invoke proc as follows:
|
||||
proc(dataset, *args, **kwargs)
|
||||
|
||||
Returns:
|
||||
Any: return the result generated by proc
|
||||
"""
|
||||
if 'lang' in kwargs and self._lang is not None:
|
||||
kwargs['lang'] = self._lang
|
||||
return proc(self, *args, **kwargs)
|
||||
|
||||
def classify(self) -> SupportedPdfParseMethod:
|
||||
"""classify the dataset.
|
||||
|
||||
Returns:
|
||||
SupportedPdfParseMethod: _description_
|
||||
"""
|
||||
if self._classify_result is None:
|
||||
self._classify_result = classify(self._data_bits)
|
||||
return self._classify_result
|
||||
|
||||
def clone(self):
|
||||
"""clone this dataset."""
|
||||
return PymuDocDataset(self._raw_data)
|
||||
|
||||
def set_images(self, images):
|
||||
for i in range(len(self._records)):
|
||||
self._records[i].set_image(images[i])
|
||||
|
||||
class ImageDataset(Dataset):
|
||||
def __init__(self, bits: bytes, lang=None):
|
||||
"""Initialize the dataset, which wraps the pymudoc documents.
|
||||
|
||||
Args:
|
||||
bits (bytes): the bytes of the photo which will be converted to pdf first. then converted to pymudoc.
|
||||
"""
|
||||
pdf_bytes = fitz.open(stream=bits).convert_to_pdf()
|
||||
self._raw_fitz = fitz.open('pdf', pdf_bytes)
|
||||
self._records = [Doc(v) for v in self._raw_fitz]
|
||||
self._raw_data = bits
|
||||
self._data_bits = pdf_bytes
|
||||
|
||||
if lang == '':
|
||||
self._lang = None
|
||||
elif lang == 'auto':
|
||||
from magic_pdf.model.sub_modules.language_detection.utils import \
|
||||
auto_detect_lang
|
||||
self._lang = auto_detect_lang(self._data_bits)
|
||||
logger.info(f'lang: {lang}, detect_lang: {self._lang}')
|
||||
else:
|
||||
self._lang = lang
|
||||
# logger.info(f'lang: {lang}')
|
||||
|
||||
def __len__(self) -> int:
|
||||
"""The length of the dataset."""
|
||||
return len(self._records)
|
||||
|
||||
def __iter__(self) -> Iterator[PageableData]:
|
||||
"""Yield the page object."""
|
||||
return iter(self._records)
|
||||
|
||||
def supported_methods(self):
|
||||
"""The method supported by this dataset.
|
||||
|
||||
Returns:
|
||||
list[SupportedPdfParseMethod]: the supported methods
|
||||
"""
|
||||
return [SupportedPdfParseMethod.OCR]
|
||||
|
||||
def data_bits(self) -> bytes:
|
||||
"""The pdf bits used to create this dataset."""
|
||||
return self._data_bits
|
||||
|
||||
def get_page(self, page_id: int) -> PageableData:
|
||||
"""The page doc object.
|
||||
|
||||
Args:
|
||||
page_id (int): the page doc index
|
||||
|
||||
Returns:
|
||||
PageableData: the page doc object
|
||||
"""
|
||||
return self._records[page_id]
|
||||
|
||||
def dump_to_file(self, file_path: str):
|
||||
"""Dump the file.
|
||||
|
||||
Args:
|
||||
file_path (str): the file path
|
||||
"""
|
||||
dir_name = os.path.dirname(file_path)
|
||||
if dir_name not in ('', '.', '..'):
|
||||
os.makedirs(dir_name, exist_ok=True)
|
||||
self._raw_fitz.save(file_path)
|
||||
|
||||
def apply(self, proc: Callable, *args, **kwargs):
|
||||
"""Apply callable method which.
|
||||
|
||||
Args:
|
||||
proc (Callable): invoke proc as follows:
|
||||
proc(dataset, *args, **kwargs)
|
||||
|
||||
Returns:
|
||||
Any: return the result generated by proc
|
||||
"""
|
||||
return proc(self, *args, **kwargs)
|
||||
|
||||
def classify(self) -> SupportedPdfParseMethod:
|
||||
"""classify the dataset.
|
||||
|
||||
Returns:
|
||||
SupportedPdfParseMethod: _description_
|
||||
"""
|
||||
return SupportedPdfParseMethod.OCR
|
||||
|
||||
def clone(self):
|
||||
"""clone this dataset."""
|
||||
return ImageDataset(self._raw_data)
|
||||
|
||||
def set_images(self, images):
|
||||
for i in range(len(self._records)):
|
||||
self._records[i].set_image(images[i])
|
||||
|
||||
class Doc(PageableData):
|
||||
"""Initialized with pymudoc object."""
|
||||
|
||||
def __init__(self, doc: fitz.Page):
|
||||
self._doc = doc
|
||||
self._img = None
|
||||
|
||||
def get_image(self):
|
||||
"""Return the image info.
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
img: np.ndarray,
|
||||
width: int,
|
||||
height: int
|
||||
}
|
||||
"""
|
||||
if self._img is None:
|
||||
self._img = fitz_doc_to_image(self._doc)
|
||||
return self._img
|
||||
|
||||
def set_image(self, img):
|
||||
"""
|
||||
Args:
|
||||
img (np.ndarray): the image
|
||||
"""
|
||||
if self._img is None:
|
||||
self._img = img
|
||||
|
||||
def get_doc(self) -> fitz.Page:
|
||||
"""Get the pymudoc object.
|
||||
|
||||
Returns:
|
||||
fitz.Page: the pymudoc object
|
||||
"""
|
||||
return self._doc
|
||||
|
||||
def get_page_info(self) -> PageInfo:
|
||||
"""Get the page info of the page.
|
||||
|
||||
Returns:
|
||||
PageInfo: the page info of this page
|
||||
"""
|
||||
page_w = self._doc.rect.width
|
||||
page_h = self._doc.rect.height
|
||||
return PageInfo(w=page_w, h=page_h)
|
||||
|
||||
def __getattr__(self, name):
|
||||
if hasattr(self._doc, name):
|
||||
return getattr(self._doc, name)
|
||||
|
||||
def draw_rect(self, rect_coords, color, fill, fill_opacity, width, overlay):
|
||||
"""draw rectangle.
|
||||
|
||||
Args:
|
||||
rect_coords (list[float]): four elements array contain the top-left and bottom-right coordinates, [x0, y0, x1, y1]
|
||||
color (list[float] | None): three element tuple which describe the RGB of the board line, None means no board line
|
||||
fill (list[float] | None): fill the board with RGB, None means will not fill with color
|
||||
fill_opacity (float): opacity of the fill, range from [0, 1]
|
||||
width (float): the width of board
|
||||
overlay (bool): fill the color in foreground or background. True means fill in background.
|
||||
"""
|
||||
self._doc.draw_rect(
|
||||
rect_coords,
|
||||
color=color,
|
||||
fill=fill,
|
||||
fill_opacity=fill_opacity,
|
||||
width=width,
|
||||
overlay=overlay,
|
||||
)
|
||||
|
||||
def insert_text(self, coord, content, fontsize, color):
|
||||
"""insert text.
|
||||
|
||||
Args:
|
||||
coord (list[float]): four elements array contain the top-left and bottom-right coordinates, [x0, y0, x1, y1]
|
||||
content (str): the text content
|
||||
fontsize (int): font size of the text
|
||||
color (list[float] | None): three element tuple which describe the RGB of the board line, None will use the default font color!
|
||||
"""
|
||||
self._doc.insert_text(coord, content, fontsize=fontsize, color=color)
|
@ -0,0 +1,6 @@
|
||||
|
||||
from magic_pdf.data.io.base import IOReader, IOWriter # noqa: F401
|
||||
from magic_pdf.data.io.http import HttpReader, HttpWriter # noqa: F401
|
||||
from magic_pdf.data.io.s3 import S3Reader, S3Writer # noqa: F401
|
||||
|
||||
__all__ = ['IOReader', 'IOWriter', 'HttpReader', 'HttpWriter', 'S3Reader', 'S3Writer']
|
@ -0,0 +1,42 @@
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
class IOReader(ABC):
|
||||
@abstractmethod
|
||||
def read(self, path: str) -> bytes:
|
||||
"""Read the file.
|
||||
|
||||
Args:
|
||||
path (str): file path to read
|
||||
|
||||
Returns:
|
||||
bytes: the content of the file
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def read_at(self, path: str, offset: int = 0, limit: int = -1) -> bytes:
|
||||
"""Read at offset and limit.
|
||||
|
||||
Args:
|
||||
path (str): the path of file, if the path is relative path, it will be joined with parent_dir.
|
||||
offset (int, optional): the number of bytes skipped. Defaults to 0.
|
||||
limit (int, optional): the length of bytes want to read. Defaults to -1.
|
||||
|
||||
Returns:
|
||||
bytes: the content of file
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class IOWriter(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def write(self, path: str, data: bytes) -> None:
|
||||
"""Write file with data.
|
||||
|
||||
Args:
|
||||
path (str): the path of file, if the path is relative path, it will be joined with parent_dir.
|
||||
data (bytes): the data want to write
|
||||
"""
|
||||
pass
|
@ -0,0 +1,37 @@
|
||||
|
||||
import io
|
||||
|
||||
import requests
|
||||
|
||||
from magic_pdf.data.io.base import IOReader, IOWriter
|
||||
|
||||
|
||||
class HttpReader(IOReader):
|
||||
|
||||
def read(self, url: str) -> bytes:
|
||||
"""Read the file.
|
||||
|
||||
Args:
|
||||
path (str): file path to read
|
||||
|
||||
Returns:
|
||||
bytes: the content of the file
|
||||
"""
|
||||
return requests.get(url).content
|
||||
|
||||
def read_at(self, path: str, offset: int = 0, limit: int = -1) -> bytes:
|
||||
"""Not Implemented."""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class HttpWriter(IOWriter):
|
||||
def write(self, url: str, data: bytes) -> None:
|
||||
"""Write file with data.
|
||||
|
||||
Args:
|
||||
path (str): the path of file, if the path is relative path, it will be joined with parent_dir.
|
||||
data (bytes): the data want to write
|
||||
"""
|
||||
files = {'file': io.BytesIO(data)}
|
||||
response = requests.post(url, files=files)
|
||||
assert 300 > response.status_code and response.status_code > 199
|