github-actions[bot] commited on
Commit
6393d69
·
0 Parent(s):

GitHub deploy: 0e36c177beb1e59f34a551efe698d81596c54b41

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +175 -0
  2. .gitattributes +2 -0
  3. .github/FUNDING.yml +15 -0
  4. .github/ISSUE_TEMPLATE/blank.yaml +25 -0
  5. .github/ISSUE_TEMPLATE/config.yml +1 -0
  6. .github/ISSUE_TEMPLATE/功能请求_cn.yaml +36 -0
  7. .github/ISSUE_TEMPLATE/功能请求_en.yaml +37 -0
  8. .github/ISSUE_TEMPLATE/问题反馈_cn.yaml +100 -0
  9. .github/ISSUE_TEMPLATE/问题反馈_en.yaml +99 -0
  10. .github/dependabot.yml +21 -0
  11. .github/release-drafter.yml +55 -0
  12. .github/workflows/black.format.yml +10 -0
  13. .github/workflows/exe-build.yml +171 -0
  14. .github/workflows/fork-build.yml +323 -0
  15. .github/workflows/fork-test.yml +24 -0
  16. .github/workflows/python-publish.yml +572 -0
  17. .github/workflows/python-test.yml +71 -0
  18. .github/workflows/sync-and-deploy.yml +185 -0
  19. .gitignore +174 -0
  20. .pre-commit-config.yaml +14 -0
  21. Dockerfile +14 -0
  22. LICENSE +661 -0
  23. README.md +8 -0
  24. app.json +5 -0
  25. docker-compose.yml +49 -0
  26. docs/ADVANCED.md +356 -0
  27. docs/APIS.md +95 -0
  28. docs/CODE_OF_CONDUCT.md +128 -0
  29. docs/README_GUI.md +40 -0
  30. docs/README_ja-JP.md +389 -0
  31. docs/README_ko-KR.md +382 -0
  32. docs/README_zh-CN.md +312 -0
  33. docs/README_zh-TW.md +366 -0
  34. docs/images/after.png +3 -0
  35. docs/images/banner.png +3 -0
  36. docs/images/before.png +3 -0
  37. docs/images/cmd.explained.png +3 -0
  38. docs/images/cmd.explained.zh.png +3 -0
  39. docs/images/gui.gif +0 -0
  40. docs/images/preview.gif +0 -0
  41. entrypoint.sh +80 -0
  42. pdf2zh/__init__.py +8 -0
  43. pdf2zh/backend.py +96 -0
  44. pdf2zh/cache.py +146 -0
  45. pdf2zh/config.py +214 -0
  46. pdf2zh/converter.py +532 -0
  47. pdf2zh/doclayout.py +179 -0
  48. pdf2zh/gui.py +888 -0
  49. pdf2zh/high_level.py +425 -0
  50. pdf2zh/mcp_server.py +108 -0
.dockerignore ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .github
2
+ docs
3
+ .git
4
+ .pre-commit-config.yaml
5
+ uv.lock
6
+ pdf2zh_files
7
+ gui/pdf2zh_files
8
+ gradio_files
9
+ tmp
10
+ gui/gradio_files
11
+ gui/tmp
12
+ # Byte-compiled / optimized / DLL files
13
+ __pycache__/
14
+ *.py[cod]
15
+ *$py.class
16
+
17
+ # C extensions
18
+ *.so
19
+
20
+ # Distribution / packaging
21
+ .Python
22
+ build/
23
+ develop-eggs/
24
+ dist/
25
+ downloads/
26
+ eggs/
27
+ .eggs/
28
+ lib/
29
+ lib64/
30
+ parts/
31
+ sdist/
32
+ var/
33
+ wheels/
34
+ share/python-wheels/
35
+ *.egg-info/
36
+ .installed.cfg
37
+ *.egg
38
+ MANIFEST
39
+
40
+ # PyInstaller
41
+ # Usually these files are written by a python script from a template
42
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
43
+ *.manifest
44
+ *.spec
45
+
46
+ # Installer logs
47
+ pip-log.txt
48
+ pip-delete-this-directory.txt
49
+
50
+ # Unit test / coverage reports
51
+ htmlcov/
52
+ .tox/
53
+ .nox/
54
+ .coverage
55
+ .coverage.*
56
+ .cache
57
+ nosetests.xml
58
+ coverage.xml
59
+ *.cover
60
+ *.py,cover
61
+ .hypothesis/
62
+ .pytest_cache/
63
+ cover/
64
+
65
+ # Translations
66
+ *.mo
67
+ *.pot
68
+
69
+ # Django stuff:
70
+ *.log
71
+ local_settings.py
72
+ db.sqlite3
73
+ db.sqlite3-journal
74
+
75
+ # Flask stuff:
76
+ instance/
77
+ .webassets-cache
78
+
79
+ # Scrapy stuff:
80
+ .scrapy
81
+
82
+ # Sphinx documentation
83
+ docs/_build/
84
+
85
+ # PyBuilder
86
+ .pybuilder/
87
+ target/
88
+
89
+ # Jupyter Notebook
90
+ .ipynb_checkpoints
91
+
92
+ # IPython
93
+ profile_default/
94
+ ipython_config.py
95
+
96
+ # pyenv
97
+ # For a library or package, you might want to ignore these files since the code is
98
+ # intended to run in multiple environments; otherwise, check them in:
99
+ # .python-version
100
+
101
+ # pipenv
102
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
103
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
104
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
105
+ # install all needed dependencies.
106
+ #Pipfile.lock
107
+
108
+ # poetry
109
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
110
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
111
+ # commonly ignored for libraries.
112
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
113
+ #poetry.lock
114
+
115
+ # pdm
116
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
117
+ #pdm.lock
118
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
119
+ # in version control.
120
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
121
+ .pdm.toml
122
+ .pdm-python
123
+ .pdm-build/
124
+
125
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
126
+ __pypackages__/
127
+
128
+ # Celery stuff
129
+ celerybeat-schedule
130
+ celerybeat.pid
131
+
132
+ # SageMath parsed files
133
+ *.sage.py
134
+
135
+ # Environments
136
+ .env
137
+ .venv
138
+ env/
139
+ venv/
140
+ ENV/
141
+ env.bak/
142
+ venv.bak/
143
+
144
+ # Spyder project settings
145
+ .spyderproject
146
+ .spyproject
147
+
148
+ # Rope project settings
149
+ .ropeproject
150
+
151
+ # mkdocs documentation
152
+ /site
153
+
154
+ # mypy
155
+ .mypy_cache/
156
+ .dmypy.json
157
+ dmypy.json
158
+
159
+ # Pyre type checker
160
+ .pyre/
161
+
162
+ # pytype static type analyzer
163
+ .pytype/
164
+
165
+ # Cython debug symbols
166
+ cython_debug/
167
+
168
+ # PyCharm
169
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
170
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
171
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
172
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
173
+ .idea/
174
+ .vscode
175
+ .DS_Store
.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ *.png filter=lfs diff=lfs merge=lfs -text
2
+ *.pdf filter=lfs diff=lfs merge=lfs -text
.github/FUNDING.yml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # These are supported funding model platforms
2
+
3
+ github: [Byaidu, reycn, Wybxc, hellofinch] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4
+ patreon: # Replace with a single Patreon username
5
+ open_collective: # Replace with a single Open Collective username
6
+ ko_fi: # Replace with a single Ko-fi username
7
+ tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8
+ community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9
+ liberapay: # Replace with a single Liberapay username
10
+ issuehunt: # Replace with a single IssueHunt username
11
+ lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
12
+ polar: # Replace with a single Polar username
13
+ buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
14
+ thanks_dev: # Replace with a single thanks.dev username
15
+ custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
.github/ISSUE_TEMPLATE/blank.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Blank Issue
2
+ description: Create a blank issue for discussion
3
+ body:
4
+ - type: markdown
5
+ attributes:
6
+ value: |
7
+ ## 2.0 is released! new repo is [HERE](https://github.com/PDFMathTranslate/PDFMathTranslate-next)
8
+ - type: checkboxes
9
+ id: checks
10
+ attributes:
11
+ label: Before you asking
12
+ options:
13
+ - label: I have tried the PDFMathTranslate-next and give feedback in PDFMathTranslate-next
14
+ required: true
15
+ - type: checkboxes
16
+ id: checks
17
+ attributes:
18
+ label: before ...
19
+ options:
20
+ - label: This issue is not about question or bug.
21
+ required: true
22
+ - type: textarea
23
+ id: describe
24
+ attributes:
25
+ label: Add a description
.github/ISSUE_TEMPLATE/config.yml ADDED
@@ -0,0 +1 @@
 
 
1
+ blank_issues_enabled: false
.github/ISSUE_TEMPLATE/功能请求_cn.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 功能请求
2
+ description: 使用中文进行功能请求
3
+ labels: ['enhancement']
4
+ body:
5
+ - type: markdown
6
+ attributes:
7
+ value: |
8
+ ## 2.0 is released! new repo is [HERE](https://github.com/PDFMathTranslate/PDFMathTranslate-next)
9
+ - type: checkboxes
10
+ id: checks
11
+ attributes:
12
+ label: 在提问之前...
13
+ options:
14
+ - label: 我已经尝试了PDFMathTranslate-next,并在PDFMathTranslate-next提交了issue
15
+ required: true
16
+ - type: textarea
17
+ id: describe
18
+ attributes:
19
+ label: 在什么场景下,需要你请求的功能?
20
+ description: 简要描述相关的使用场景
21
+ validations:
22
+ required: false
23
+ - type: textarea
24
+ id: solution
25
+ attributes:
26
+ label: 解决方案
27
+ description: 描述你想要的解决方案
28
+ validations:
29
+ required: false
30
+ - type: textarea
31
+ id: additional
32
+ attributes:
33
+ label: 其他内容
34
+ description: 关于该功能请求的任何其他项目。
35
+ validations:
36
+ required: false
.github/ISSUE_TEMPLATE/功能请求_en.yaml ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Feature request
2
+ description: Suggest an idea for this project
3
+ labels: ['enhancement']
4
+ body:
5
+ - type: markdown
6
+ attributes:
7
+ value: |
8
+ ## 2.0 is released! new repo is [HERE](https://github.com/PDFMathTranslate/PDFMathTranslate-next)
9
+ - type: checkboxes
10
+ id: checks
11
+ attributes:
12
+ label: Before you asking
13
+ options:
14
+ - label: I have tried the PDFMathTranslate-next and give feedback in PDFMathTranslate-next
15
+ required: true
16
+ - type: textarea
17
+ id: describe
18
+ attributes:
19
+ label: Is your feature request related to a problem?
20
+ description: A clear and concise description of what the problem is
21
+ placeholder: Ex. I'm always frustrated when ...
22
+ validations:
23
+ required: false
24
+ - type: textarea
25
+ id: solution
26
+ attributes:
27
+ label: Describe the solution you'd like
28
+ description: A clear and concise description of what you want to happen
29
+ validations:
30
+ required: false
31
+ - type: textarea
32
+ id: additional
33
+ attributes:
34
+ label: Additional context
35
+ description: Add any other projects about the feature request here.
36
+ validations:
37
+ required: false
.github/ISSUE_TEMPLATE/问题反馈_cn.yaml ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 上报 Bug
2
+ description: 使用中文进行 Bug 报告
3
+ labels: ['bug']
4
+ body:
5
+ - type: markdown
6
+ attributes:
7
+ value: |
8
+ ## 2.0 is released! new repo is [HERE](https://github.com/PDFMathTranslate/PDFMathTranslate-next)
9
+ - type: checkboxes
10
+ id: checks
11
+ attributes:
12
+ label: 在提问之前...
13
+ options:
14
+ - label: 我已经尝试了PDFMathTranslate-next,并在PDFMathTranslate-next提交了issue
15
+ required: true
16
+ - label: 我已经搜索了现有的 issues
17
+ required: true
18
+ - label: 我在提问题之前至少花费了 5 分钟来思考和准备
19
+ required: true
20
+ - label: 我已经认真且完整的阅读了 wiki
21
+ required: true
22
+ - label: 我已经认真检查了问题和网络环境无关(包括但不限于Google不可用,模型下载失败)
23
+ required: true
24
+ - type: markdown
25
+ attributes:
26
+ value: |
27
+ 感谢您使用本项目并反馈!
28
+ 请再次确认上述复选框所述的内容已经认真执行!
29
+ - type: textarea
30
+ id: environment
31
+ attributes:
32
+ label: 使用的环境
33
+ placeholder: |
34
+ - **OS**: Ubuntu 24.10
35
+ - **Python**: 3.12.0
36
+ - **pdf2zh**: 1.9.0
37
+ render: markdown
38
+ validations:
39
+ required: false
40
+ - type: dropdown
41
+ id: install
42
+ attributes:
43
+ label: 请选择安装方式
44
+ options:
45
+ - pip
46
+ - exe
47
+ - 源码
48
+ - docker
49
+ validations:
50
+ required: true
51
+ - type: textarea
52
+ id: describe
53
+ attributes:
54
+ label: 描述你的问题
55
+ description: 简要描述你的问题
56
+ validations:
57
+ required: true
58
+ - type: textarea
59
+ id: reproduce
60
+ attributes:
61
+ label: 如何复现
62
+ description: 重现该行为的步骤
63
+ value: |
64
+ 1. 执行 '...'
65
+ 2. 选择 '....'
66
+ 3. 出现问题
67
+ validations:
68
+ required: false
69
+ - type: textarea
70
+ id: expected
71
+ attributes:
72
+ label: 预期行为
73
+ description: 简要描述你期望得到的反馈
74
+ validations:
75
+ required: false
76
+ - type: textarea
77
+ id: logs
78
+ attributes:
79
+ label: 相关 Logs
80
+ description: 请复制并粘贴任何相关的日志输出。
81
+ render: Text
82
+ validations:
83
+ required: false
84
+ - type: textarea
85
+ id: PDFfile
86
+ attributes:
87
+ label: 原始PDF文件
88
+ description: |
89
+ 如果涉及到排版错误的问题,请一定提供原始的PDF文件,方便复现错误。
90
+ validations:
91
+ required: false
92
+ - type: textarea
93
+ id: others
94
+ attributes:
95
+ label: 还有别的吗?
96
+ description: |
97
+ 相关的配置?链接?参考资料?
98
+ 任何能让我们对你所遇到的问题有更多了解的东西。
99
+ validations:
100
+ required: false
.github/ISSUE_TEMPLATE/问题反馈_en.yaml ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Bug Report
2
+ description: Create a report to help us improve
3
+ labels: ['bug']
4
+ body:
5
+ - type: markdown
6
+ attributes:
7
+ value: |
8
+ ## 2.0 is released! new repo is [HERE](https://github.com/PDFMathTranslate/PDFMathTranslate-next)
9
+ - type: checkboxes
10
+ id: checks
11
+ attributes:
12
+ label: Before you asking
13
+ options:
14
+ - label: I have tried the PDFMathTranslate-next and give feedback in PDFMathTranslate-next
15
+ required: true
16
+ - label: I have searched the existing issues
17
+ required: true
18
+ - label: I spend at least 5 minutes for thinking and preparing
19
+ required: true
20
+ - label: I have thoroughly and completely read the wiki.
21
+ required: true
22
+ - label: I have carefully checked the issue, and it is unrelated to the network environment.
23
+ required: true
24
+ - type: markdown
25
+ attributes:
26
+ value: |
27
+ Thank you for using this project and providing feedback!
28
+ - type: textarea
29
+ id: environment
30
+ attributes:
31
+ label: Environment
32
+ placeholder: |
33
+ - **OS**: Ubuntu 24.10
34
+ - **Python**: 3.12.0
35
+ - **pdf2zh**: 1.9.0
36
+ render: markdown
37
+ validations:
38
+ required: false
39
+ - type: dropdown
40
+ id: install
41
+ attributes:
42
+ label: How to install pdf2zh
43
+ options:
44
+ - pip
45
+ - exe
46
+ - source
47
+ - docker
48
+ validations:
49
+ required: true
50
+ - type: textarea
51
+ id: describe
52
+ attributes:
53
+ label: Describe the bug
54
+ description: A clear and concise description of what the bug is.
55
+ validations:
56
+ required: true
57
+ - type: textarea
58
+ id: reproduce
59
+ attributes:
60
+ label: To Reproduce
61
+ description: Steps to reproduce the behavior
62
+ value: |
63
+ 1. execute '...'
64
+ 2. select '....'
65
+ 3. see errors
66
+ validations:
67
+ required: false
68
+ - type: textarea
69
+ id: expected
70
+ attributes:
71
+ label: Expected behavior
72
+ description: A clear and concise description of what you expected to happen.
73
+ validations:
74
+ required: false
75
+ - type: textarea
76
+ id: logs
77
+ attributes:
78
+ label: Relevant log output
79
+ description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
80
+ render: Text
81
+ validations:
82
+ required: false
83
+ - type: textarea
84
+ id: PDFfile
85
+ attributes:
86
+ label: Origin PDF file
87
+ description: |
88
+ If the issue involves formatting errors, please provide the original PDF file to facilitate reproduction of the error.
89
+ validations:
90
+ required: false
91
+ - type: textarea
92
+ id: others
93
+ attributes:
94
+ label: Anything else?
95
+ description: |
96
+ Related configs? Links? References?
97
+ Anything that will give us more context about the issue you are encountering!
98
+ validations:
99
+ required: false
.github/dependabot.yml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: github-actions
4
+ directory: "/"
5
+ schedule:
6
+ interval: weekly
7
+ # - package-ecosystem: pip
8
+ # directory: "/.github/workflows"
9
+ # schedule:
10
+ # interval: weekly
11
+ # - package-ecosystem: pip
12
+ # directory: "/docs"
13
+ # schedule:
14
+ # interval: weekly
15
+ - package-ecosystem: pip
16
+ directory: "/"
17
+ schedule:
18
+ interval: weekly
19
+ versioning-strategy: lockfile-only
20
+ allow:
21
+ - dependency-type: "all"
.github/release-drafter.yml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name-template: 'v$RESOLVED_VERSION'
2
+ tag-template: 'v$RESOLVED_VERSION'
3
+ categories:
4
+ - title: '🚀 Features'
5
+ labels:
6
+ - 'feature'
7
+ - 'enhancement'
8
+ - title: '🐛 Bug Fixes'
9
+ labels:
10
+ - 'fix'
11
+ - 'bugfix'
12
+ - 'bug'
13
+ - title: '🧰 Maintenance'
14
+ labels:
15
+ - 'chore'
16
+ - 'maintenance'
17
+ - 'refactor'
18
+ - title: '📝 Documentation'
19
+ labels:
20
+ - 'docs'
21
+ - 'documentation'
22
+ change-template: '- $TITLE @$AUTHOR (#$NUMBER)'
23
+ change-title-escapes: '\<*_&' # You can add # and @ to disable mentions
24
+ version-resolver:
25
+ major:
26
+ labels:
27
+ - 'major'
28
+ minor:
29
+ labels:
30
+ - 'minor'
31
+ patch:
32
+ labels:
33
+ - 'patch'
34
+ default: patch
35
+ template: |
36
+ ## Changes
37
+
38
+ $CHANGES
39
+
40
+ ## Contributors
41
+
42
+ $CONTRIBUTORS
43
+
44
+ ## Windows Specific
45
+
46
+ If you cannot open it after downloading, please install https://aka.ms/vs/17/release/vc_redist.x64.exe and try again.
47
+
48
+ ## Assets
49
+
50
+ - pdf2zh-v$RESOLVED_VERSION-win64.zip: pdf2zh **without** assets(font, model, etc.)
51
+ - pdf2zh-v$RESOLVED_VERSION-with-assets-win64.zip: (**Recommended**) pdf2zh **with** assets(font, model, etc.)
52
+
53
+ > [!NOTE]
54
+ >
55
+ > The version without assets will also dynamically download resources when running, but the download may fail due to network issues.
.github/workflows/black.format.yml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Format Code with Black
2
+
3
+ on: [push, pull_request]
4
+
5
+ jobs:
6
+ lint:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v4
10
+ - uses: psf/black@stable
.github/workflows/exe-build.yml ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: windows exe Release Workflow
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ release_version:
7
+ description: 'Release Version (e.g., v1.0.0)'
8
+ required: true
9
+ type: string
10
+ # push:
11
+ # debug purpose
12
+ env:
13
+ WIN_EXE_PYTHON_VERSION: 3.12.9
14
+ jobs:
15
+ build-win64-exe:
16
+ runs-on: windows-latest
17
+ steps:
18
+ - name: checkout babeldoc metadata
19
+ uses: actions/checkout@v4
20
+ with:
21
+ repository: funstory-ai/BabelDOC
22
+ path: babeldoctemp1234567
23
+ token: ${{ secrets.GITHUB_TOKEN }}
24
+ sparse-checkout: babeldoc/assets/embedding_assets_metadata.py
25
+ - name: Cached Assets
26
+ id: cache-assets
27
+ uses: actions/[email protected]
28
+ with:
29
+ path: ~/.cache/babeldoc
30
+ key: test-1-babeldoc-assets-${{ hashFiles('babeldoctemp1234567/babeldoc/assets/embedding_assets_metadata.py') }}
31
+ - name: 检出代码
32
+ uses: actions/checkout@v4
33
+
34
+ - name: Setup uv with Python ${{ env.WIN_EXE_PYTHON_VERSION }}
35
+ uses: astral-sh/setup-uv@f94ec6bedd8674c4426838e6b50417d36b6ab231 # v5.3.1
36
+ with:
37
+ python-version: ${{ env.WIN_EXE_PYTHON_VERSION }}
38
+ enable-cache: true
39
+ cache-dependency-glob: "pyproject.toml"
40
+
41
+ - name: 执行所有任务(创建目录、下载、解压、复制文件、安装依赖)
42
+ shell: pwsh
43
+ run: |
44
+ Write-Host "==== 删除 babeldoctemp1234567 文件夹 ===="
45
+ if (Test-Path "./babeldoctemp1234567") {
46
+ Remove-Item -Path "./babeldoctemp1234567" -Recurse -Force
47
+ Write-Host "babeldoctemp1234567 文件夹已成功删除"
48
+ } else {
49
+ Write-Host "babeldoctemp1234567 文件夹不存在,无需删除"
50
+ }
51
+ Write-Host "==== 创建必要的目录 ===="
52
+ New-Item -Path "./build" -ItemType Directory -Force
53
+ New-Item -Path "./build/runtime" -ItemType Directory -Force
54
+ New-Item -Path "./dep_build" -ItemType Directory -Force
55
+
56
+ Write-Host "==== 复制代码到 dep_build ===="
57
+ Get-ChildItem -Path "./" -Exclude "dep_build", "build" | Copy-Item -Destination "./dep_build" -Recurse -Force
58
+
59
+ Write-Host "==== 下载并解压 Python ${{ env.WIN_EXE_PYTHON_VERSION }} ===="
60
+ Write-Host "pythonUrl: https://www.python.org/ftp/python/${{ env.WIN_EXE_PYTHON_VERSION }}/python-${{ env.WIN_EXE_PYTHON_VERSION }}-embed-amd64.zip"
61
+ $pythonUrl = "https://www.python.org/ftp/python/${{ env.WIN_EXE_PYTHON_VERSION }}/python-${{ env.WIN_EXE_PYTHON_VERSION }}-embed-amd64.zip"
62
+ $pythonZip = "./dep_build/python.zip"
63
+ Invoke-WebRequest -Uri $pythonUrl -OutFile $pythonZip
64
+ Expand-Archive -Path $pythonZip -DestinationPath "./build/runtime" -Force
65
+
66
+ Write-Host "==== 下载并解压 PyStand ===="
67
+ $pystandUrl = "https://github.com/skywind3000/PyStand/releases/download/1.1.4/PyStand-v1.1.4-exe.zip"
68
+ $pystandZip = "./dep_build/PyStand.zip"
69
+ Invoke-WebRequest -Uri $pystandUrl -OutFile $pystandZip
70
+ Expand-Archive -Path $pystandZip -DestinationPath "./dep_build/PyStand" -Force
71
+
72
+ Write-Host "==== 复制 PyStand.exe 到 build 并重命名 ===="
73
+ $pystandExe = "./dep_build/PyStand/PyStand-x64-CLI/PyStand.exe"
74
+ $destExe = "./build/pdf2zh.exe"
75
+ if (Test-Path $pystandExe) {
76
+ Copy-Item -Path $pystandExe -Destination $destExe -Force
77
+ } else {
78
+ Write-Host "错误: PyStand.exe 未找到!"
79
+ exit 1
80
+ }
81
+ Write-Host "==== 创建 Python venv 在 dep_build ===="
82
+ uv venv ./dep_build/venv
83
+
84
+ ./dep_build/venv/Scripts/activate
85
+
86
+ Write-Host "==== 在 venv 环境中安装项目依赖 ===="
87
+ uv pip install .
88
+
89
+ Write-Host "==== 复制 venv/Lib/site-packages 到 build/ ===="
90
+ Copy-Item -Path "./dep_build/venv/Lib/site-packages" -Destination "./build/site-packages" -Recurse -Force
91
+
92
+ Write-Host "==== 复制 script/_pystand_static.int 到 build/ ===="
93
+ $staticFile = "./script/_pystand_static.int"
94
+ $destStatic = "./build/_pystand_static.int"
95
+ if (Test-Path $staticFile) {
96
+ Copy-Item -Path $staticFile -Destination $destStatic -Force
97
+ } else {
98
+ Write-Host "错误: script/_pystand_static.int 未找到!"
99
+ exit 1
100
+ }
101
+
102
+ uv run --active babeldoc --generate-offline-assets ./build
103
+
104
+ - name: Upload build artifact
105
+ uses: actions/upload-artifact@v4
106
+ with:
107
+ name: win64-exe
108
+ path: ./build
109
+ if-no-files-found: error
110
+ compression-level: 9
111
+ include-hidden-files: true
112
+
113
+ test-win64-exe:
114
+ needs:
115
+ - build-win64-exe
116
+ runs-on: windows-latest
117
+ steps:
118
+ - name: 检出代码
119
+ uses: actions/checkout@v4
120
+
121
+ - name: Download build artifact
122
+ uses: actions/download-artifact@v4
123
+ with:
124
+ name: win64-exe
125
+ path: ./build
126
+
127
+ - name: Test show version
128
+ run: |
129
+ ./build/pdf2zh.exe --version
130
+
131
+ - name: Test - Translate a PDF file with plain text only
132
+ run: |
133
+ ./build/pdf2zh.exe ./test/file/translate.cli.plain.text.pdf -o ./test/file
134
+
135
+ - name: Test - Translate a PDF file figure
136
+ run: |
137
+ ./build/pdf2zh.exe ./test/file/translate.cli.text.with.figure.pdf -o ./test/file
138
+
139
+ - name: Delete offline assets and cache
140
+ shell: pwsh
141
+ run: |
142
+ Write-Host "==== 查找并删除离线资源包 ===="
143
+ $offlineAssetsPath = Get-ChildItem -Path "./build" -Filter "offline_assets_*.zip" -Recurse | Select-Object -First 1 -ExpandProperty FullName
144
+ if ($offlineAssetsPath) {
145
+ Write-Host "找到离线资源包: $offlineAssetsPath"
146
+ Remove-Item -Path $offlineAssetsPath -Force
147
+ Write-Host "已删除离线资源包"
148
+ } else {
149
+ Write-Host "未找到离线资源包"
150
+ }
151
+
152
+ Write-Host "==== 删除缓存目录 ===="
153
+ $cachePath = "$env:USERPROFILE/.cache/babeldoc"
154
+ if (Test-Path $cachePath) {
155
+ Remove-Item -Path $cachePath -Recurse -Force
156
+ Write-Host "已删除缓存目录: $cachePath"
157
+ } else {
158
+ Write-Host "缓存目录不存在: $cachePath"
159
+ }
160
+
161
+ - name: Test - Translate without offline assets
162
+ run: |
163
+ ./build/pdf2zh.exe ./test/file/translate.cli.plain.text.pdf -o ./test/file
164
+
165
+ - name: Upload test results
166
+ uses: actions/upload-artifact@v4
167
+ with:
168
+ name: test-results
169
+ path: ./test/file/
170
+
171
+
.github/workflows/fork-build.yml ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: fork-build
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ # debug purpose
6
+ # push:
7
+
8
+ env:
9
+ REGISTRY: ghcr.io
10
+ REPO_LOWER: ${{ github.repository_owner }}/${{ github.event.repository.name }}
11
+ GHCR_REPO: ghcr.io/${{ github.repository }}
12
+ WIN_EXE_PYTHON_VERSION: 3.12.9
13
+ jobs:
14
+ check-repository:
15
+ name: Check if running in main repository
16
+ runs-on: ubuntu-latest
17
+ outputs:
18
+ is_main_repo: ${{ github.repository == 'Byaidu/PDFMathTranslate' }}
19
+ steps:
20
+ - run: echo "Running repository check"
21
+
22
+ test:
23
+ uses: ./.github/workflows/python-test.yml
24
+ needs: check-repository
25
+ if: needs.check-repository.outputs.is_main_repo != 'true'
26
+
27
+ build:
28
+ strategy:
29
+ fail-fast: false
30
+ matrix:
31
+ include:
32
+ - platform: linux/amd64
33
+ runner: ubuntu-latest
34
+ - platform: linux/arm64
35
+ runner: ubuntu-24.04-arm
36
+ runs-on: ${{ matrix.runner }}
37
+ needs:
38
+ - check-repository
39
+ - test
40
+ if: needs.check-repository.outputs.is_main_repo != 'true'
41
+ permissions:
42
+ contents: read
43
+ packages: write
44
+
45
+ steps:
46
+ - name: Convert to lowercase
47
+ run: |
48
+ echo "GHCR_REPO_LOWER=$(echo ${{ env.GHCR_REPO }} | tr '[:upper:]' '[:lower:]')" >> $GITHUB_ENV
49
+
50
+ - name: Prepare
51
+ run: |
52
+ platform=${{ matrix.platform }}
53
+ echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
54
+
55
+ - name: Checkout repository
56
+ uses: actions/checkout@v4
57
+
58
+ - name: Docker meta
59
+ id: meta
60
+ uses: docker/metadata-action@v5
61
+ with:
62
+ images: |
63
+ ${{ env.GHCR_REPO_LOWER }}
64
+
65
+ - name: Login to GHCR
66
+ uses: docker/login-action@v3
67
+ with:
68
+ registry: ghcr.io
69
+ username: ${{ github.repository_owner }}
70
+ password: ${{ secrets.GITHUB_TOKEN }}
71
+
72
+
73
+ - name: Set up Docker Buildx
74
+ uses: docker/setup-buildx-action@v3
75
+
76
+ - name: Build and push by digest
77
+ id: build
78
+ uses: docker/build-push-action@v6
79
+ with:
80
+ platforms: ${{ matrix.platform }}
81
+ labels: ${{ steps.meta.outputs.labels }}
82
+ outputs: type=image,name=${{ env.GHCR_REPO_LOWER }},push-by-digest=true,name-canonical=true,push=true
83
+ cache-from: ${{ matrix.platform == 'linux/amd64' && 'type=gha' || '' }}
84
+ cache-to: ${{ matrix.platform == 'linux/amd64' && 'type=gha,mode=max' || '' }}
85
+
86
+ - name: Export digest
87
+ run: |
88
+ mkdir -p ${{ runner.temp }}/digests
89
+ digest="${{ steps.build.outputs.digest }}"
90
+ touch "${{ runner.temp }}/digests/${digest#sha256:}"
91
+
92
+ - name: Upload digest
93
+ uses: actions/upload-artifact@v4
94
+ with:
95
+ name: digests-${{ env.PLATFORM_PAIR }}
96
+ path: ${{ runner.temp }}/digests/*
97
+ if-no-files-found: error
98
+ retention-days: 1
99
+
100
+ merge:
101
+ runs-on: ubuntu-latest
102
+ needs:
103
+ - check-repository
104
+ - test
105
+ - build
106
+ if: needs.check-repository.outputs.is_main_repo != 'true'
107
+ permissions:
108
+ contents: read
109
+ packages: write
110
+
111
+ steps:
112
+ - name: Convert to lowercase
113
+ run: |
114
+ echo "GHCR_REPO_LOWER=$(echo ${{ env.GHCR_REPO }} | tr '[:upper:]' '[:lower:]')" >> $GITHUB_ENV
115
+
116
+ - name: Download digests
117
+ uses: actions/download-artifact@v4
118
+ with:
119
+ path: ${{ runner.temp }}/digests
120
+ pattern: digests-*
121
+ merge-multiple: true
122
+
123
+ - name: Login to GHCR
124
+ uses: docker/login-action@v3
125
+ with:
126
+ registry: ghcr.io
127
+ username: ${{ github.repository_owner }}
128
+ password: ${{ secrets.GITHUB_TOKEN }}
129
+
130
+ - name: Set up Docker Buildx
131
+ uses: docker/setup-buildx-action@v3
132
+
133
+ - name: Docker meta
134
+ id: meta
135
+ uses: docker/metadata-action@v5
136
+ with:
137
+ images: |
138
+ ${{ env.GHCR_REPO_LOWER }}
139
+ tags: |
140
+ type=raw,value=dev
141
+ type=semver,pattern={{version}}
142
+ type=semver,pattern={{major}}.{{minor}}
143
+
144
+ - name: Create manifest list and push
145
+ working-directory: ${{ runner.temp }}/digests
146
+ run: |
147
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
148
+ $(printf '${{ env.GHCR_REPO_LOWER }}@sha256:%s ' *)
149
+
150
+ - name: Inspect image
151
+ run: |
152
+ docker buildx imagetools inspect ${{ env.GHCR_REPO_LOWER }}:${{ steps.meta.outputs.version }}
153
+
154
+ build-win64-exe:
155
+ runs-on: windows-latest
156
+ needs:
157
+ - check-repository
158
+ if: needs.check-repository.outputs.is_main_repo != 'true'
159
+ steps:
160
+ - name: 检出代码
161
+ uses: actions/checkout@v4
162
+
163
+ - name: Setup uv with Python ${{ env.WIN_EXE_PYTHON_VERSION }}
164
+ uses: astral-sh/setup-uv@f94ec6bedd8674c4426838e6b50417d36b6ab231 # v5.3.1
165
+ with:
166
+ python-version: ${{ env.WIN_EXE_PYTHON_VERSION }}
167
+ enable-cache: true
168
+ cache-dependency-glob: "pyproject.toml"
169
+
170
+ - name: 执行所有任务(创建目录、下载、解压、复制文件、安装依赖)
171
+ shell: pwsh
172
+ run: |
173
+ Write-Host "==== 创建必要的目录 ===="
174
+ New-Item -Path "./build" -ItemType Directory -Force
175
+ New-Item -Path "./build/runtime" -ItemType Directory -Force
176
+ New-Item -Path "./dep_build" -ItemType Directory -Force
177
+
178
+ Write-Host "==== 复制代码到 dep_build ===="
179
+ Get-ChildItem -Path "./" -Exclude "dep_build", "build" | Copy-Item -Destination "./dep_build" -Recurse -Force
180
+
181
+ Write-Host "==== 下载并解压 Python ${{ env.WIN_EXE_PYTHON_VERSION }} ===="
182
+ Write-Host "pythonUrl: https://www.python.org/ftp/python/${{ env.WIN_EXE_PYTHON_VERSION }}/python-${{ env.WIN_EXE_PYTHON_VERSION }}-embed-amd64.zip"
183
+ $pythonUrl = "https://www.python.org/ftp/python/${{ env.WIN_EXE_PYTHON_VERSION }}/python-${{ env.WIN_EXE_PYTHON_VERSION }}-embed-amd64.zip"
184
+ $pythonZip = "./dep_build/python.zip"
185
+ Invoke-WebRequest -Uri $pythonUrl -OutFile $pythonZip
186
+ Expand-Archive -Path $pythonZip -DestinationPath "./build/runtime" -Force
187
+
188
+ Write-Host "==== 下载 Visual C++ Redistributable 安装程序 ===="
189
+ $vcRedistUrl = "https://aka.ms/vs/17/release/vc_redist.x64.exe"
190
+ $vcRedistPath = "./build/无法运行请安装vc_redist.x64.exe"
191
+ Invoke-WebRequest -Uri $vcRedistUrl -OutFile $vcRedistPath
192
+ Write-Host "已下载 Visual C++ Redistributable 安装程序到: $vcRedistPath"
193
+
194
+ Write-Host "==== 下载并解压 PyStand ===="
195
+ $pystandUrl = "https://github.com/skywind3000/PyStand/releases/download/1.1.4/PyStand-v1.1.4-exe.zip"
196
+ $pystandZip = "./dep_build/PyStand.zip"
197
+ Invoke-WebRequest -Uri $pystandUrl -OutFile $pystandZip
198
+ Expand-Archive -Path $pystandZip -DestinationPath "./dep_build/PyStand" -Force
199
+
200
+ Write-Host "==== 复制 PyStand.exe 到 build 并重命名 ===="
201
+ $pystandExe = "./dep_build/PyStand/PyStand-x64-CLI/PyStand.exe"
202
+ $destExe = "./build/pdf2zh.exe"
203
+ if (Test-Path $pystandExe) {
204
+ Copy-Item -Path $pystandExe -Destination $destExe -Force
205
+ } else {
206
+ Write-Host "错误: PyStand.exe 未找到!"
207
+ exit 1
208
+ }
209
+ Write-Host "==== 创建 Python venv 在 dep_build ===="
210
+ uv venv ./dep_build/venv
211
+
212
+ ./dep_build/venv/Scripts/activate
213
+
214
+ Write-Host "==== 在 venv 环境中安装项目依赖 ===="
215
+ uv pip install .
216
+
217
+ Write-Host "==== 复制 venv/Lib/site-packages 到 build/ ===="
218
+ Copy-Item -Path "./dep_build/venv/Lib/site-packages" -Destination "./build/site-packages" -Recurse -Force
219
+
220
+ Write-Host "==== 复制 script/_pystand_static.int 到 build/ ===="
221
+ $staticFile = "./script/_pystand_static.int"
222
+ $destStatic = "./build/_pystand_static.int"
223
+ if (Test-Path $staticFile) {
224
+ Copy-Item -Path $staticFile -Destination $destStatic -Force
225
+ } else {
226
+ Write-Host "错误: script/_pystand_static.int 未找到!"
227
+ exit 1
228
+ }
229
+
230
+ - name: Upload build artifact
231
+ uses: actions/upload-artifact@v4
232
+ with:
233
+ name: win64-exe
234
+ path: ./build
235
+ if-no-files-found: error
236
+ compression-level: 1
237
+ include-hidden-files: true
238
+
239
+ test-win64-exe:
240
+ needs:
241
+ - build-win64-exe
242
+ - check-repository
243
+ if: needs.check-repository.outputs.is_main_repo != 'true'
244
+ runs-on: windows-latest
245
+ steps:
246
+ - name: 检出代码
247
+ uses: actions/checkout@v4
248
+
249
+ - name: Download build artifact
250
+ uses: actions/download-artifact@v4
251
+ with:
252
+ name: win64-exe
253
+ path: ./build
254
+
255
+ - name: Test show version (online mode)
256
+ run: |
257
+ ./build/pdf2zh.exe --version
258
+
259
+ - name: Test - Translate a PDF file with plain text only (online mode)
260
+ run: |
261
+ ./build/pdf2zh.exe ./test/file/translate.cli.plain.text.pdf -o ./test/file
262
+
263
+ - name: Test - Translate a PDF file figure
264
+ run: |
265
+ ./build/pdf2zh.exe ./test/file/translate.cli.text.with.figure.pdf -o ./test/file
266
+
267
+ - name: Test - Translate without offline assets (online mode)
268
+ run: |
269
+ ./build/pdf2zh.exe ./test/file/translate.cli.plain.text.pdf -o ./test/file
270
+
271
+ - name: Upload test results
272
+ uses: actions/upload-artifact@v4
273
+ with:
274
+ name: test-results
275
+ path: ./test/file/
276
+ if-no-files-found: error
277
+
278
+ - name: Setup uv with Python ${{ env.WIN_EXE_PYTHON_VERSION }}
279
+ uses: astral-sh/setup-uv@f94ec6bedd8674c4426838e6b50417d36b6ab231 # v5.3.1
280
+ with:
281
+ python-version: ${{ env.WIN_EXE_PYTHON_VERSION }}
282
+ enable-cache: true
283
+ cache-dependency-glob: "pyproject.toml"
284
+
285
+ - name: Generate offline assets
286
+ shell: pwsh
287
+ run: |
288
+ Write-Host "==== 生成离线资源包 ===="
289
+ uv run --active babeldoc --generate-offline-assets ./build
290
+
291
+ - name: Delete cache
292
+ shell: pwsh
293
+ run: |
294
+ Write-Host "==== 删除缓存目录 ===="
295
+ $cachePath = "$env:USERPROFILE/.cache/babeldoc"
296
+ if (Test-Path $cachePath) {
297
+ Remove-Item -Path $cachePath -Recurse -Force
298
+ Write-Host "已删除缓存目录: $cachePath"
299
+ } else {
300
+ Write-Host "缓存目录不存在: $cachePath"
301
+ }
302
+
303
+ - name: Test - Translate with offline assets (offline mode)
304
+ run: |
305
+ Write-Host "==== 测试离线资源包 ===="
306
+ New-Item -Path "./test/file/offline_result" -ItemType Directory -Force
307
+ ./build/pdf2zh.exe ./test/file/translate.cli.plain.text.pdf -o ./test/file/offline_result
308
+
309
+ - name: Upload offline test results
310
+ uses: actions/upload-artifact@v4
311
+ with:
312
+ name: offline-test-results
313
+ path: ./test/file/offline_result/
314
+ if-no-files-found: error
315
+
316
+ - name: Upload build with offline assets artifact
317
+ uses: actions/upload-artifact@v4
318
+ with:
319
+ name: win64-exe-with-assets
320
+ path: ./build
321
+ if-no-files-found: error
322
+ compression-level: 1
323
+ include-hidden-files: true
.github/workflows/fork-test.yml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: fork-test
2
+
3
+ on:
4
+ push:
5
+ branches: [ "main", "master" ]
6
+
7
+ env:
8
+ REGISTRY: ghcr.io
9
+ REPO_LOWER: ${{ github.repository_owner }}/${{ github.event.repository.name }}
10
+ GHCR_REPO: ghcr.io/${{ github.repository }}
11
+ WIN_EXE_PYTHON_VERSION: 3.12.9
12
+ jobs:
13
+ check-repository:
14
+ name: Check if running in main repository
15
+ runs-on: ubuntu-latest
16
+ outputs:
17
+ is_main_repo: ${{ github.repository == 'Byaidu/PDFMathTranslate' }}
18
+ steps:
19
+ - run: echo "Running repository check"
20
+
21
+ test:
22
+ uses: ./.github/workflows/python-test.yml
23
+ needs: check-repository
24
+ if: needs.check-repository.outputs.is_main_repo != 'true'
.github/workflows/python-publish.yml ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Test and Release
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ - master
8
+
9
+ permissions:
10
+ id-token: write
11
+ contents: write
12
+ pull-requests: write
13
+
14
+ env:
15
+ REGISTRY: ghcr.io
16
+ REPO_LOWER: ${{ github.repository_owner }}/${{ github.event.repository.name }}
17
+ GHCR_REPO: ghcr.io/${{ github.repository }}
18
+ DOCKERHUB_REPO: byaidu/pdf2zh
19
+ WIN_EXE_PYTHON_VERSION: "3.12.9"
20
+
21
+ jobs:
22
+ check-repository:
23
+ name: Check if running in main repository
24
+ runs-on: ubuntu-latest
25
+ outputs:
26
+ # debug purpose
27
+ is_main_repo: ${{ github.repository == 'Byaidu/PDFMathTranslate' }}
28
+ steps:
29
+ - run: echo "Running repository check"
30
+
31
+ test:
32
+ needs: check-repository
33
+ uses: ./.github/workflows/python-test.yml
34
+ if: needs.check-repository.outputs.is_main_repo == 'true'
35
+
36
+ build:
37
+ name: Build distribution 📦
38
+ needs: [test, check-repository]
39
+ if: needs.check-repository.outputs.is_main_repo == 'true'
40
+ runs-on: ubuntu-latest
41
+ outputs:
42
+ is_release: ${{ steps.check-version.outputs.tag }}
43
+ version: ${{ steps.check-version.outputs.tag && steps.get-release-version.outputs.version || steps.get-dev-version.outputs.version }}
44
+ steps:
45
+ - uses: actions/checkout@v4
46
+ with:
47
+ persist-credentials: true
48
+ fetch-depth: 2
49
+ token: ${{ secrets.GITHUB_TOKEN }}
50
+
51
+ - name: Setup uv with Python 3.12
52
+ uses: astral-sh/setup-uv@f94ec6bedd8674c4426838e6b50417d36b6ab231 # v5.3.1
53
+ with:
54
+ python-version: "3.12"
55
+ enable-cache: true
56
+ cache-dependency-glob: "pyproject.toml"
57
+
58
+ - name: Check if there is a parent commit
59
+ id: check-parent-commit
60
+ run: |
61
+ echo "sha=$(git rev-parse --verify --quiet HEAD^)" >> $GITHUB_OUTPUT
62
+
63
+ - name: Detect and tag new version
64
+ id: check-version
65
+ if: steps.check-parent-commit.outputs.sha
66
+ uses: salsify/action-detect-and-tag-new-version@b1778166f13188a9d478e2d1198f993011ba9864 # v2.0.3
67
+ with:
68
+ version-command: |
69
+ cat pyproject.toml | grep "version = " | head -n 1 | awk -F'"' '{print $2}'
70
+ tag-template: 'v{VERSION}'
71
+
72
+ - name: Install Dependencies
73
+ run: |
74
+ uv sync
75
+
76
+ - name: Bump version for developmental release
77
+ if: "!steps.check-version.outputs.tag"
78
+ id: get-dev-version
79
+ run: |
80
+ version=$(bumpver update --patch --tag=final --dry 2>&1 | grep "New Version" | awk '{print $NF}')
81
+ echo "version=$version.dev$(date +%s)" >> $GITHUB_OUTPUT
82
+ bumpver update --set-version $version.dev$(date +%s)
83
+
84
+ - name: Get release version
85
+ if: steps.check-version.outputs.tag
86
+ id: get-release-version
87
+ run: |
88
+ version=$(cat pyproject.toml | grep "version = " | head -n 1 | awk -F'"' '{print $2}')
89
+ echo "version=$version" >> $GITHUB_OUTPUT
90
+
91
+ - name: Build package
92
+ run: "uv build"
93
+
94
+ - name: Store the distribution packages
95
+ uses: actions/[email protected]
96
+ with:
97
+ name: python-package-distributions
98
+ path: dist/
99
+
100
+ publish-to-pypi:
101
+ name: Publish Python 🐍 distribution 📦 to PyPI
102
+ if: needs.build.outputs.is_release != ''
103
+ needs:
104
+ - check-repository
105
+ - build
106
+ - test-win64-exe
107
+ runs-on: ubuntu-latest
108
+ environment:
109
+ name: pypi
110
+ url: https://pypi.org/p/pdf2zh
111
+
112
+ permissions:
113
+ id-token: write
114
+
115
+ steps:
116
+ - name: Download all the dists
117
+ uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
118
+ with:
119
+ name: python-package-distributions
120
+ path: dist/
121
+
122
+ - name: Publish distribution 📦 to PyPI
123
+ uses: pypa/gh-action-pypi-publish@76f52bc884231f62b9a034ebfe128415bbaabdfc # v1.12.4
124
+
125
+ publish-to-testpypi:
126
+ name: Publish Python 🐍 distribution 📦 to TestPyPI
127
+ if: needs.build.outputs.is_release == ''
128
+ needs:
129
+ - check-repository
130
+ - build
131
+ - test-win64-exe
132
+ runs-on: ubuntu-latest
133
+ environment:
134
+ name: testpypi
135
+ url: https://test.pypi.org/p/pdf2zh
136
+
137
+ permissions:
138
+ id-token: write
139
+
140
+ steps:
141
+ - name: Download all the dists
142
+ uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
143
+ with:
144
+ name: python-package-distributions
145
+ path: dist/
146
+
147
+ - name: Publish distribution 📦 to TestPyPI
148
+ uses: pypa/gh-action-pypi-publish@76f52bc884231f62b9a034ebfe128415bbaabdfc # v1.12.4
149
+ with:
150
+ repository-url: https://test.pypi.org/legacy/
151
+
152
+ build-docker-image:
153
+ strategy:
154
+ fail-fast: false
155
+ matrix:
156
+ include:
157
+ - platform: linux/amd64
158
+ runner: ubuntu-latest
159
+ - platform: linux/arm64
160
+ runner: ubuntu-24.04-arm
161
+ runs-on: ${{ matrix.runner }}
162
+ needs:
163
+ - build
164
+ - check-repository
165
+ if: needs.check-repository.outputs.is_main_repo == 'true'
166
+ environment:
167
+ name: ${{ needs.build.outputs.is_release != '' && 'pypi' || 'testpypi' }}
168
+ url: ${{ needs.build.outputs.is_release != '' && 'https://hub.docker.com/r/byaidu/pdf2zh/tags?name=latest' || 'https://hub.docker.com/r/byaidu/pdf2zh/tags?name=dev' }}
169
+ permissions:
170
+ contents: read
171
+ packages: write
172
+
173
+ steps:
174
+ - name: Convert to lowercase
175
+ run: |
176
+ echo "GHCR_REPO_LOWER=$(echo ${{ env.GHCR_REPO }} | tr '[:upper:]' '[:lower:]')" >> $GITHUB_ENV
177
+
178
+ - name: Prepare
179
+ run: |
180
+ platform=${{ matrix.platform }}
181
+ echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
182
+
183
+ - name: Checkout repository
184
+ uses: actions/checkout@v4
185
+
186
+ - name: Setup uv with Python 3.12
187
+ uses: astral-sh/setup-uv@f94ec6bedd8674c4426838e6b50417d36b6ab231 # v5.3.1
188
+ with:
189
+ python-version: "3.12"
190
+ enable-cache: true
191
+ cache-dependency-glob: "pyproject.toml"
192
+
193
+ - name: Set version from build job
194
+ if: needs.build.outputs.is_release == ''
195
+ run: |
196
+ uv tool install bumpver
197
+ echo "Using version: ${{ needs.build.outputs.version }}"
198
+ bumpver update --set-version ${{ needs.build.outputs.version }}
199
+
200
+ - name: Docker meta
201
+ id: meta
202
+ uses: docker/metadata-action@v5
203
+ with:
204
+ images: |
205
+ ${{ env.DOCKERHUB_REPO }}
206
+ ${{ env.GHCR_REPO_LOWER }}
207
+ tags: |
208
+ type=raw,value=dev
209
+ type=raw,value=${{ needs.build.outputs.version }},enable=${{ needs.build.outputs.is_release != '' }}
210
+ type=raw,value=latest,enable=${{ needs.build.outputs.is_release != '' }}
211
+
212
+ - name: Login to Docker.io
213
+ uses: docker/login-action@v3
214
+ with:
215
+ registry: docker.io
216
+ username: ${{ secrets.DOCKER_USERNAME }}
217
+ password: ${{ secrets.DOCKER_PASSWORD }}
218
+
219
+ - name: Login to GHCR
220
+ uses: docker/login-action@v3
221
+ with:
222
+ registry: ghcr.io
223
+ username: ${{ github.repository_owner }}
224
+ password: ${{ secrets.GITHUB_TOKEN }}
225
+
226
+ - name: Set up Docker Buildx
227
+ uses: docker/setup-buildx-action@v3
228
+
229
+ - name: Build and push by digest
230
+ id: build
231
+ uses: docker/build-push-action@v6
232
+ with:
233
+ platforms: ${{ matrix.platform }}
234
+ labels: ${{ steps.meta.outputs.labels }}
235
+ outputs: type=image,"name=${{ env.DOCKERHUB_REPO }},${{ env.GHCR_REPO_LOWER }}",push-by-digest=true,name-canonical=true,push=true
236
+ cache-from: ${{ matrix.platform == 'linux/amd64' && 'type=gha' || '' }}
237
+ cache-to: ${{ matrix.platform == 'linux/amd64' && 'type=gha,mode=max' || '' }}
238
+
239
+ - name: Export digest
240
+ run: |
241
+ mkdir -p ${{ runner.temp }}/digests
242
+ digest="${{ steps.build.outputs.digest }}"
243
+ touch "${{ runner.temp }}/digests/${digest#sha256:}"
244
+
245
+ - name: Upload digest
246
+ uses: actions/upload-artifact@v4
247
+ with:
248
+ name: digests-${{ env.PLATFORM_PAIR }}
249
+ path: ${{ runner.temp }}/digests/*
250
+ if-no-files-found: error
251
+ retention-days: 1
252
+
253
+ merge-docker-image:
254
+ runs-on: ubuntu-latest
255
+ permissions:
256
+ packages: write
257
+ needs:
258
+ - build-docker-image
259
+ - check-repository
260
+ - test-win64-exe
261
+ - build
262
+ if: needs.check-repository.outputs.is_main_repo == 'true'
263
+ steps:
264
+ - name: Convert to lowercase
265
+ run: |
266
+ echo "GHCR_REPO_LOWER=$(echo ${{ env.GHCR_REPO }} | tr '[:upper:]' '[:lower:]')" >> $GITHUB_ENV
267
+
268
+ - name: Download digests
269
+ uses: actions/download-artifact@v4
270
+ with:
271
+ path: ${{ runner.temp }}/digests
272
+ pattern: digests-*
273
+ merge-multiple: true
274
+
275
+ - name: Login to Docker.io
276
+ uses: docker/login-action@v3
277
+ with:
278
+ registry: docker.io
279
+ username: ${{ secrets.DOCKER_USERNAME }}
280
+ password: ${{ secrets.DOCKER_PASSWORD }}
281
+
282
+ - name: Login to GHCR
283
+ uses: docker/login-action@v3
284
+ with:
285
+ registry: ghcr.io
286
+ username: ${{ github.repository_owner }}
287
+ password: ${{ secrets.GITHUB_TOKEN }}
288
+
289
+ - name: Set up Docker Buildx
290
+ uses: docker/setup-buildx-action@v3
291
+
292
+ - name: Docker meta
293
+ id: meta
294
+ uses: docker/metadata-action@v5
295
+ with:
296
+ images: |
297
+ ${{ env.DOCKERHUB_REPO }}
298
+ ${{ env.GHCR_REPO_LOWER }}
299
+ tags: |
300
+ type=raw,value=dev
301
+ type=raw,value=${{ needs.build.outputs.version }},enable=${{ needs.build.outputs.is_release != '' && 'true' || 'false' }}
302
+ type=raw,value=latest,enable=${{ needs.build.outputs.is_release != '' && 'true' || 'false' }}
303
+
304
+ - name: Create manifest list and push
305
+ working-directory: ${{ runner.temp }}/digests
306
+ run: |
307
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
308
+ $(printf '${{ env.DOCKERHUB_REPO }}@sha256:%s ' *)
309
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
310
+ $(printf '${{ env.GHCR_REPO_LOWER }}@sha256:%s ' *)
311
+
312
+ - name: Inspect image
313
+ run: |
314
+ docker buildx imagetools inspect ${{ env.DOCKERHUB_REPO }}:${{ steps.meta.outputs.version }}
315
+ docker buildx imagetools inspect ${{ env.GHCR_REPO_LOWER }}:${{ steps.meta.outputs.version }}
316
+
317
+
318
+ build-win64-exe:
319
+ runs-on: windows-latest
320
+ needs:
321
+ - check-repository
322
+ if: needs.check-repository.outputs.is_main_repo == 'true'
323
+ steps:
324
+ - name: checkout babeldoc metadata
325
+ uses: actions/checkout@v4
326
+ with:
327
+ repository: funstory-ai/BabelDOC
328
+ path: babeldoctemp1234567
329
+ token: ${{ secrets.GITHUB_TOKEN }}
330
+ sparse-checkout: babeldoc/assets/embedding_assets_metadata.py
331
+ - name: Cached Assets
332
+ id: cache-assets
333
+ uses: actions/[email protected]
334
+ with:
335
+ path: ~/.cache/babeldoc
336
+ key: test-1-babeldoc-assets-${{ hashFiles('babeldoctemp1234567/babeldoc/assets/embedding_assets_metadata.py') }}
337
+ - name: 检出代码
338
+ uses: actions/checkout@v4
339
+
340
+ - name: Setup uv with Python ${{ env.WIN_EXE_PYTHON_VERSION }}
341
+ uses: astral-sh/setup-uv@f94ec6bedd8674c4426838e6b50417d36b6ab231 # v5.3.1
342
+ with:
343
+ python-version: ${{ env.WIN_EXE_PYTHON_VERSION }}
344
+ enable-cache: true
345
+ cache-dependency-glob: "pyproject.toml"
346
+
347
+ - name: 执行所有任务(创建目录、下载、解压、复制文件、安装依赖)
348
+ shell: pwsh
349
+ run: |
350
+ Write-Host "==== 创建必要的目录 ===="
351
+ New-Item -Path "./build" -ItemType Directory -Force
352
+ New-Item -Path "./build/runtime" -ItemType Directory -Force
353
+ New-Item -Path "./dep_build" -ItemType Directory -Force
354
+
355
+ Write-Host "==== 复制代码到 dep_build ===="
356
+ Get-ChildItem -Path "./" -Exclude "dep_build", "build" | Copy-Item -Destination "./dep_build" -Recurse -Force
357
+
358
+ Write-Host "==== 下载并解压 Python ${{ env.WIN_EXE_PYTHON_VERSION }} ===="
359
+ Write-Host "pythonUrl: https://www.python.org/ftp/python/${{ env.WIN_EXE_PYTHON_VERSION }}/python-${{ env.WIN_EXE_PYTHON_VERSION }}-embed-amd64.zip"
360
+ $pythonUrl = "https://www.python.org/ftp/python/${{ env.WIN_EXE_PYTHON_VERSION }}/python-${{ env.WIN_EXE_PYTHON_VERSION }}-embed-amd64.zip"
361
+ $pythonZip = "./dep_build/python.zip"
362
+ Invoke-WebRequest -Uri $pythonUrl -OutFile $pythonZip
363
+ Expand-Archive -Path $pythonZip -DestinationPath "./build/runtime" -Force
364
+
365
+ Write-Host "==== 下载 Visual C++ Redistributable 安装程序 ===="
366
+ $vcRedistUrl = "https://aka.ms/vs/17/release/vc_redist.x64.exe"
367
+ $vcRedistPath = "./build/无法运行请安装vc_redist.x64.exe"
368
+ Invoke-WebRequest -Uri $vcRedistUrl -OutFile $vcRedistPath
369
+ Write-Host "已下载 Visual C++ Redistributable 安装程序到: $vcRedistPath"
370
+
371
+ Write-Host "==== 下载并解压 PyStand ===="
372
+ $pystandUrl = "https://github.com/skywind3000/PyStand/releases/download/1.1.4/PyStand-v1.1.4-exe.zip"
373
+ $pystandZip = "./dep_build/PyStand.zip"
374
+ Invoke-WebRequest -Uri $pystandUrl -OutFile $pystandZip
375
+ Expand-Archive -Path $pystandZip -DestinationPath "./dep_build/PyStand" -Force
376
+
377
+ Write-Host "==== 复制 PyStand.exe 到 build 并重命名 ===="
378
+ $pystandExe = "./dep_build/PyStand/PyStand-x64-CLI/PyStand.exe"
379
+ $destExe = "./build/pdf2zh.exe"
380
+ if (Test-Path $pystandExe) {
381
+ Copy-Item -Path $pystandExe -Destination $destExe -Force
382
+ } else {
383
+ Write-Host "错误: PyStand.exe 未找到!"
384
+ exit 1
385
+ }
386
+ Write-Host "==== 创建 Python venv 在 dep_build ===="
387
+ uv venv ./dep_build/venv
388
+
389
+ ./dep_build/venv/Scripts/activate
390
+
391
+ Write-Host "==== 在 venv 环境中安装项目依赖 ===="
392
+ uv pip install .
393
+
394
+ Write-Host "==== 复制 venv/Lib/site-packages 到 build/ ===="
395
+ Copy-Item -Path "./dep_build/venv/Lib/site-packages" -Destination "./build/site-packages" -Recurse -Force
396
+
397
+ Write-Host "==== 复制 script/_pystand_static.int 到 build/ ===="
398
+ $staticFile = "./script/_pystand_static.int"
399
+ $destStatic = "./build/_pystand_static.int"
400
+ if (Test-Path $staticFile) {
401
+ Copy-Item -Path $staticFile -Destination $destStatic -Force
402
+ } else {
403
+ Write-Host "错误: script/_pystand_static.int 未找到!"
404
+ exit 1
405
+ }
406
+
407
+ # - name: Upload build artifact
408
+ # uses: actions/upload-artifact@v4
409
+ # with:
410
+ # name: win64-exe
411
+ # path: ./build
412
+ # if-no-files-found: error
413
+ # compression-level: 1
414
+ # include-hidden-files: true
415
+
416
+ - name: Generate offline assets
417
+ shell: pwsh
418
+ run: |
419
+ Write-Host "==== 生成离线资源包 ===="
420
+ uv run --active babeldoc --generate-offline-assets ./build
421
+
422
+ - name: Upload build with offline assets artifact
423
+ uses: actions/upload-artifact@v4
424
+ with:
425
+ name: win64-exe-with-assets
426
+ path: ./build
427
+ if-no-files-found: error
428
+ compression-level: 1
429
+ include-hidden-files: true
430
+
431
+
432
+ test-win64-exe:
433
+ needs:
434
+ - build-win64-exe
435
+ - check-repository
436
+ if: needs.check-repository.outputs.is_main_repo == 'true'
437
+ runs-on: windows-latest
438
+ steps:
439
+ - name: 检出代码
440
+ uses: actions/checkout@v4
441
+
442
+ - name: Download build artifact
443
+ uses: actions/download-artifact@v4
444
+ with:
445
+ name: win64-exe-with-assets
446
+ path: ./build
447
+
448
+ - name: Test show version
449
+ run: |
450
+ ./build/pdf2zh.exe --version
451
+
452
+ - name: Test - Translate a PDF file with plain text only
453
+ run: |
454
+ ./build/pdf2zh.exe ./test/file/translate.cli.plain.text.pdf -o ./test/file
455
+
456
+ - name: Test - Translate a PDF file figure
457
+ run: |
458
+ ./build/pdf2zh.exe ./test/file/translate.cli.text.with.figure.pdf -o ./test/file
459
+
460
+ - name: Delete offline assets and cache
461
+ shell: pwsh
462
+ run: |
463
+ Write-Host "==== 查找并删除离线资源包 ===="
464
+ $offlineAssetsPath = Get-ChildItem -Path "./build" -Filter "offline_assets_*.zip" -Recurse | Select-Object -First 1 -ExpandProperty FullName
465
+ if ($offlineAssetsPath) {
466
+ Write-Host "找到离线资源包: $offlineAssetsPath"
467
+ Remove-Item -Path $offlineAssetsPath -Force
468
+ Write-Host "已删除离线资源包"
469
+ } else {
470
+ Write-Host "未找到离线资源包"
471
+ }
472
+
473
+ Write-Host "==== 删除缓存目录 ===="
474
+ $cachePath = "$env:USERPROFILE/.cache/babeldoc"
475
+ if (Test-Path $cachePath) {
476
+ Remove-Item -Path $cachePath -Recurse -Force
477
+ Write-Host "已删除缓存目录: $cachePath"
478
+ } else {
479
+ Write-Host "缓存目录不存在: $cachePath"
480
+ }
481
+
482
+ - name: Test - Translate without offline assets
483
+ run: |
484
+ Write-Host "==== 测试离线资源包 ===="
485
+ New-Item -Path "./test/file/offline_result" -ItemType Directory -Force
486
+ ./build/pdf2zh.exe ./test/file/translate.cli.plain.text.pdf -o ./test/file/offline_result
487
+
488
+
489
+ - name: Upload test results
490
+ uses: actions/upload-artifact@v4
491
+ with:
492
+ name: test-results
493
+ path: ./test/file/
494
+
495
+
496
+
497
+ release-draft:
498
+ name: Release Draft Tasks
499
+ needs:
500
+ - check-repository
501
+ - build
502
+ - publish-to-pypi
503
+ - publish-to-testpypi
504
+ - merge-docker-image
505
+ - test-win64-exe
506
+ if: |
507
+ always() && needs.check-repository.outputs.is_main_repo == 'true' &&
508
+ (needs.publish-to-pypi.result == 'success' || needs.publish-to-testpypi.result == 'success') &&
509
+ needs.merge-docker-image.result == 'success' &&
510
+ needs.test-win64-exe.result == 'success'
511
+ runs-on: ubuntu-latest
512
+ permissions:
513
+ contents: write
514
+ pull-requests: write
515
+ outputs:
516
+ tag_name: ${{ steps.release-drafter.outputs.tag_name }}
517
+ steps:
518
+ - uses: actions/checkout@v4
519
+ with:
520
+ persist-credentials: true
521
+ fetch-depth: 2
522
+ token: ${{ secrets.GITHUB_TOKEN }}
523
+
524
+ - name: Publish the release notes
525
+ id: release-drafter
526
+ uses: release-drafter/release-drafter@b1476f6e6eb133afa41ed8589daba6dc69b4d3f5 # v6.1.0
527
+ with:
528
+ publish: ${{ needs.build.outputs.is_release != '' }}
529
+ tag: ${{ needs.build.outputs.is_release }}
530
+ env:
531
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
532
+
533
+
534
+ upload-release:
535
+ needs: [release-draft, check-repository]
536
+ runs-on: ubuntu-latest
537
+ if: always() && needs.check-repository.outputs.is_main_repo == 'true' &&
538
+ needs.release-draft.result == 'success'
539
+ steps:
540
+ - name: 检出代码
541
+ uses: actions/checkout@v4
542
+
543
+ - name: Download build artifact
544
+ uses: actions/download-artifact@v4
545
+ with:
546
+ name: win64-exe-with-assets
547
+ path: ./build
548
+
549
+ - name: Create release zip
550
+ run: |
551
+ mv ./build ./pdf2zh
552
+ zip -9qr "pdf2zh-${{ needs.release-draft.outputs.tag_name }}-with-assets-win64.zip" ./pdf2zh/*
553
+
554
+ # 查找并删除离线资源文件
555
+ find ./pdf2zh -name "offline_assets_*.zip" -type f -print -delete
556
+ # 确保删除操作成功
557
+ echo "Remaining offline assets files (should be empty):"
558
+ find ./pdf2zh -name "offline_assets_*.zip" -type f
559
+
560
+ zip -9qr "pdf2zh-${{ needs.release-draft.outputs.tag_name }}-win64.zip" ./pdf2zh/*
561
+
562
+ - name: Upload to latest release
563
+ env:
564
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
565
+ run: |
566
+ # Get the latest release (including drafts and pre-releases)
567
+ LATEST_RELEASE=${{ needs.release-draft.outputs.tag_name }}
568
+ echo "Latest release tag: $LATEST_RELEASE"
569
+
570
+ # Upload the zip file to the release
571
+ gh release upload "$LATEST_RELEASE" "pdf2zh-${{ needs.release-draft.outputs.tag_name }}-win64.zip" --clobber
572
+ gh release upload "$LATEST_RELEASE" "pdf2zh-${{ needs.release-draft.outputs.tag_name }}-with-assets-win64.zip" --clobber
.github/workflows/python-test.yml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Test and Build Python Package
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - '**'
7
+ - '!main'
8
+ - '!master'
9
+ pull_request:
10
+ workflow_call:
11
+
12
+ jobs:
13
+ build-and-test:
14
+ runs-on: ${{ matrix.runner }}
15
+ strategy:
16
+ fail-fast: false
17
+ matrix:
18
+ python-version: ["3.10", "3.11", "3.12"]
19
+ runner:
20
+ - ubuntu-latest
21
+ - ubuntu-24.04-arm
22
+ steps:
23
+ - name: checkout babeldoc metadata
24
+ uses: actions/checkout@v4
25
+ with:
26
+ repository: funstory-ai/BabelDOC
27
+ path: babeldoctemp1234567
28
+ token: ${{ secrets.GITHUB_TOKEN }}
29
+ sparse-checkout: babeldoc/assets/embedding_assets_metadata.py
30
+ - name: Cached Assets
31
+ id: cache-assets
32
+ uses: actions/[email protected]
33
+ with:
34
+ path: ~/.cache/babeldoc
35
+ key: test-1-babeldoc-assets-${{ hashFiles('babeldoctemp1234567/babeldoc/assets/embedding_assets_metadata.py') }}
36
+ - uses: actions/checkout@v4
37
+ - name: Setup uv with Python ${{ matrix.python-version }}
38
+ uses: astral-sh/setup-uv@f94ec6bedd8674c4426838e6b50417d36b6ab231 # v5.3.1
39
+ with:
40
+ python-version: ${{ matrix.python-version }}
41
+ enable-cache: true
42
+ cache-dependency-glob: "pyproject.toml"
43
+ - name: Install dependencies
44
+ run: |
45
+ uv sync
46
+
47
+ - name: Test - Unit Test
48
+ run: |
49
+ uv run pytest .
50
+
51
+ - name: Test - Translate a PDF file with plain text only
52
+ run: uv run pdf2zh ./test/file/translate.cli.plain.text.pdf -o ./test/file
53
+
54
+ - name: Test - Translate a PDF file figure
55
+ run: uv run pdf2zh ./test/file/translate.cli.text.with.figure.pdf -o ./test/file
56
+
57
+ # - name: Test - Translate a PDF file with unknown font
58
+ # run:
59
+ # pdf2zh ./test/file/translate.cli.font.unknown.pdf
60
+
61
+ - name: Test - Start GUI and exit
62
+ run: timeout 10 uv run pdf2zh -i || code=$?; if [[ $code -ne 124 && $code -ne 0 ]]; then exit $code; fi
63
+
64
+ - name: Build as a package
65
+ run: uv build
66
+
67
+ - name: Upload test results
68
+ uses: actions/upload-artifact@v4
69
+ with:
70
+ name: test-results-${{ matrix.python-version }}-${{ matrix.runner }}
71
+ path: ./test/file/
.github/workflows/sync-and-deploy.yml ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync and Deploy
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ schedule:
8
+ - cron: "0 0 * * *" # daily at midnight
9
+ workflow_dispatch:
10
+
11
+ jobs:
12
+ sync:
13
+ name: Sync latest commits from upstream repo
14
+ runs-on: ubuntu-latest
15
+ if: ${{ github.event.repository.fork }}
16
+ outputs:
17
+ changes: ${{ steps.check_changes.outputs.changes }}
18
+ steps:
19
+ - name: Checkout target repo
20
+ uses: actions/checkout@v3
21
+ - name: Sync upstream changes
22
+ id: sync
23
+ uses: aormsby/[email protected]
24
+ with:
25
+ upstream_sync_repo: Byaidu/PDFMathTranslate
26
+ upstream_sync_branch: main
27
+ target_sync_branch: main
28
+ target_repo_token: ${{ secrets.GITHUB_TOKEN }}
29
+ test_mode: false
30
+ - name: Check if there were changes
31
+ id: check_changes
32
+ run: |
33
+ if [[ ${{ steps.sync.outputs.has_new_commits }} == "true" ]]; then
34
+ echo "changes=true" >> $GITHUB_OUTPUT
35
+ else
36
+ echo "changes=false" >> $GITHUB_OUTPUT
37
+ fi
38
+
39
+ deploy:
40
+ needs: sync
41
+ if: |
42
+ always() &&
43
+ (needs.sync.result == 'success' || needs.sync.result == 'skipped') &&
44
+ (github.event_name == 'push' || (github.event_name == 'schedule' && needs.sync.outputs.changes == 'true') || github.event_name == 'workflow_dispatch')
45
+ runs-on: ubuntu-latest
46
+ steps:
47
+ - name: Checkout repository
48
+ uses: actions/checkout@v4
49
+ - name: Check for HF_TOKEN
50
+ id: check_token
51
+ env:
52
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
53
+ run: |
54
+ if [[ -n "$HF_TOKEN" ]]; then
55
+ echo "token_exists=true" >> $GITHUB_OUTPUT
56
+ else
57
+ echo "token_exists=false" >> $GITHUB_OUTPUT
58
+ fi
59
+ - name: Deploy to HuggingFace Spaces
60
+ if: steps.check_token.outputs.token_exists == 'true'
61
+ env:
62
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
63
+ run: |
64
+ # Remove git history
65
+ rm -rf .git
66
+ rm -f README.md Dockerfile
67
+ cat <<EOF > Dockerfile
68
+ FROM python:3.12
69
+ RUN useradd -m appuser
70
+ WORKDIR /app
71
+ COPY . .
72
+ RUN chown -R appuser:appuser /app
73
+ RUN apt-get update && apt-get install -y libgl1 inotify-tools
74
+ ENV HF_HOME="/app/hf_cache"
75
+ RUN pip install .
76
+ COPY entrypoint.sh /app/entrypoint.sh
77
+ RUN chmod +x /app/entrypoint.sh
78
+ USER appuser
79
+ EXPOSE 7860
80
+ ENV PYTHONUNBUFFERED=1
81
+ ENTRYPOINT ["/app/entrypoint.sh"]
82
+ EOF
83
+ cat <<EOF > README.md
84
+ ---
85
+ title: PDFMathTranslate Demo
86
+ sdk: docker
87
+ pinned: false
88
+ license: agpl-3.0
89
+ short_description: 'Demo for https://github.com/Byaidu/PDFMathTranslate'
90
+ ---
91
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
92
+ EOF
93
+ cat <<'EOF' > entrypoint.sh
94
+ #!/bin/bash
95
+ set -euo pipefail
96
+ UPLOADED_FILES_RECORD="/app/uploaded_files.txt"
97
+ WATCH_DIR="pdf2zh_files"
98
+ cleanup() {
99
+ echo "正在退出..."
100
+ exit 0
101
+ }
102
+ trap cleanup SIGTERM SIGINT
103
+ echo "$APP_USERS" > /app/users.txt
104
+ chmod 600 /app/users.txt
105
+ cat > /app/config.json << CONFIG_EOF
106
+ {
107
+ "translators": [
108
+ {
109
+ "name": "openai",
110
+ "envs": {
111
+ "OPENAI_BASE_URL": "${OPENAI_BASE_URL}",
112
+ "OPENAI_API_KEY": "${OPENAI_API_KEY}",
113
+ "OPENAI_MODEL": "${OPENAI_MODEL}"
114
+ }
115
+ }
116
+ ],
117
+ "ENABLED_SERVICES": [
118
+ "OpenAI"
119
+ ],
120
+ "HIDDEN_GRADIO_DETAILS": true
121
+ }
122
+ CONFIG_EOF
123
+ pdf2zh -i --authorized /app/users.txt --config /app/config.json &
124
+ if [ ! -f "$UPLOADED_FILES_RECORD" ]; then
125
+ touch "$UPLOADED_FILES_RECORD"
126
+ fi
127
+ if [ ! -d "$WATCH_DIR" ]; then
128
+ mkdir "$WATCH_DIR"
129
+ fi
130
+ upload_file() {
131
+ local file="$1"
132
+ (
133
+ flock -n 9 || exit 1
134
+
135
+ if grep -Fxq "$file" "$UPLOADED_FILES_RECORD"; then
136
+ echo "文件 $file 已经上传过,跳过。"
137
+ exit 0
138
+ fi
139
+ echo "正在上传 $file..."
140
+ encoded_file=$(python3 -c "import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1]))" "$file")
141
+ if curl -T "$WATCH_DIR/$file" "$WEBDAV_URL/$encoded_file" --user "$WEBDAV_USER:$WEBDAV_PASS"; then
142
+ echo "成功上传 $file"
143
+ echo "$file" >> "$UPLOADED_FILES_RECORD"
144
+ else
145
+ echo "上�� $file 失败" >&2
146
+ fi
147
+
148
+ ) 9>>"$UPLOADED_FILES_RECORD.lock"
149
+ }
150
+ if command -v inotifywait >/dev/null 2>&1; then
151
+ echo "开始监控 $WATCH_DIR 文件夹..."
152
+ inotifywait -m -e create -e moved_to --format '%f' "$WATCH_DIR" |
153
+ while read -r filename; do
154
+ # 检查文件是否为 PDF,并且存在
155
+ if [[ "$filename" =~ \.pdf$ ]] && [ -f "$WATCH_DIR/$filename" ]; then
156
+ upload_file "$filename"
157
+ fi
158
+ done
159
+ else
160
+ echo "未安装 inotifywait,使用定期检查方式。您可以通过 'sudo apt-get install inotify-tools' 安装 inotifywait。"
161
+ while true; do
162
+ for local_file in "$WATCH_DIR"/*.pdf; do
163
+ if [ -f "$local_file" ]; then
164
+ filename=$(basename "$local_file")
165
+ # 检查文件是否已上传
166
+ if ! grep -Fxq "$filename" "$UPLOADED_FILES_RECORD"; then
167
+ upload_file "$filename"
168
+ fi
169
+ fi
170
+ done
171
+ sleep 60
172
+ done
173
+ fi
174
+ EOF
175
+ # Configure git
176
+ git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
177
+ git config --global user.name "github-actions[bot]"
178
+ # Set up Git and push to Space
179
+ git init --initial-branch=main
180
+ git lfs install
181
+ git lfs track "*.png"
182
+ git lfs track "*.pdf"
183
+ git add .
184
+ git commit -m "GitHub deploy: ${{ github.sha }}"
185
+ git push --force https://xnwh:${HF_TOKEN}@huggingface.co/spaces/xnwh/pz main
.gitignore ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pdf2zh_files
2
+ gui/pdf2zh_files
3
+ gradio_files
4
+ tmp
5
+ gui/gradio_files
6
+ gui/tmp
7
+ # Byte-compiled / optimized / DLL files
8
+ __pycache__/
9
+ *.py[cod]
10
+ *$py.class
11
+
12
+ # C extensions
13
+ *.so
14
+
15
+ # Distribution / packaging
16
+ .Python
17
+ build/
18
+ develop-eggs/
19
+ dist/
20
+ downloads/
21
+ eggs/
22
+ .eggs/
23
+ lib/
24
+ lib64/
25
+ parts/
26
+ sdist/
27
+ var/
28
+ wheels/
29
+ share/python-wheels/
30
+ *.egg-info/
31
+ .installed.cfg
32
+ *.egg
33
+ MANIFEST
34
+
35
+ # PyInstaller
36
+ # Usually these files are written by a python script from a template
37
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
38
+ *.manifest
39
+ *.spec
40
+
41
+ # Installer logs
42
+ pip-log.txt
43
+ pip-delete-this-directory.txt
44
+
45
+ # Unit test / coverage reports
46
+ htmlcov/
47
+ .tox/
48
+ .nox/
49
+ .coverage
50
+ .coverage.*
51
+ .cache
52
+ nosetests.xml
53
+ coverage.xml
54
+ *.cover
55
+ *.py,cover
56
+ .hypothesis/
57
+ .pytest_cache/
58
+ cover/
59
+
60
+ # Translations
61
+ *.mo
62
+ *.pot
63
+
64
+ # Django stuff:
65
+ *.log
66
+ local_settings.py
67
+ db.sqlite3
68
+ db.sqlite3-journal
69
+
70
+ # Flask stuff:
71
+ instance/
72
+ .webassets-cache
73
+
74
+ # Scrapy stuff:
75
+ .scrapy
76
+
77
+ # Sphinx documentation
78
+ docs/_build/
79
+
80
+ # PyBuilder
81
+ .pybuilder/
82
+ target/
83
+
84
+ # Jupyter Notebook
85
+ .ipynb_checkpoints
86
+
87
+ # IPython
88
+ profile_default/
89
+ ipython_config.py
90
+
91
+ # pyenv
92
+ # For a library or package, you might want to ignore these files since the code is
93
+ # intended to run in multiple environments; otherwise, check them in:
94
+ # .python-version
95
+
96
+ # pipenv
97
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
98
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
99
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
100
+ # install all needed dependencies.
101
+ #Pipfile.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+ pdf2zh-dev/
139
+
140
+ # Spyder project settings
141
+ .spyderproject
142
+ .spyproject
143
+
144
+ # Rope project settings
145
+ .ropeproject
146
+
147
+ # mkdocs documentation
148
+ /site
149
+
150
+ # mypy
151
+ .mypy_cache/
152
+ .dmypy.json
153
+ dmypy.json
154
+
155
+ # Pyre type checker
156
+ .pyre/
157
+
158
+ # pytype static type analyzer
159
+ .pytype/
160
+
161
+ # Cython debug symbols
162
+ cython_debug/
163
+
164
+ # PyCharm
165
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
166
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
167
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
168
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
169
+ .idea/
170
+ .vscode
171
+ .DS_Store
172
+ uv.lock
173
+ *.pdf
174
+ *.docx
.pre-commit-config.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # See https://pre-commit.com for more information
2
+ # See https://pre-commit.com/hooks.html for more hooks
3
+ files: '^.*\.py$'
4
+ repos:
5
+ - repo: local
6
+ hooks:
7
+ - id: black
8
+ name: black
9
+ entry: black --check --diff --color
10
+ language: python
11
+ - id: flake8
12
+ name: flake8
13
+ entry: flake8 --ignore E203,E261,E501,W503,E741
14
+ language: python
Dockerfile ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12
2
+ RUN useradd -m appuser
3
+ WORKDIR /app
4
+ COPY . .
5
+ RUN chown -R appuser:appuser /app
6
+ RUN apt-get update && apt-get install -y libgl1 inotify-tools
7
+ ENV HF_HOME="/app/hf_cache"
8
+ RUN pip install .
9
+ COPY entrypoint.sh /app/entrypoint.sh
10
+ RUN chmod +x /app/entrypoint.sh
11
+ USER appuser
12
+ EXPOSE 7860
13
+ ENV PYTHONUNBUFFERED=1
14
+ ENTRYPOINT ["/app/entrypoint.sh"]
LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
README.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: PDFMathTranslate Demo
3
+ sdk: docker
4
+ pinned: false
5
+ license: agpl-3.0
6
+ short_description: 'Demo for https://github.com/Byaidu/PDFMathTranslate'
7
+ ---
8
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "name": "PDFMathTranslate",
3
+ "description": "PDF scientific paper translation and bilingual comparison.",
4
+ "repository": "https://github.com/Byaidu/PDFMathTranslate"
5
+ }
docker-compose.yml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This is the final, recommended configuration.
2
+ # It builds a single, self-contained image with all dependencies.
3
+
4
+ services:
5
+ pdf2zh:
6
+ build:
7
+ context: .
8
+ # All the setup steps are now part of a one-time build process.
9
+ dockerfile_inline: |
10
+ FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim
11
+
12
+ WORKDIR /app
13
+
14
+ # 1. Install system-level dependencies FIRST.
15
+ # This is what solves the "libGL.so.1 not found" error.
16
+ RUN apt-get update && \
17
+ apt-get install --no-install-recommends -y libgl1 libglib2.0-0 libxext6 libsm6 libxrender1 && \
18
+ rm -rf /var/lib/apt/lists/*
19
+
20
+ # 2. Copy only the dependency file and install Python packages.
21
+ # This layer is cached and only re-runs if pyproject.toml changes.
22
+ COPY pyproject.toml .
23
+ RUN uv pip install --system --no-cache -r pyproject.toml
24
+
25
+ # 3. Copy the rest of your application code.
26
+ COPY . .
27
+
28
+ # 4. Install the local package and perform final updates/warmups.
29
+ RUN uv pip install --system --no-cache . && \
30
+ uv pip install --system --no-cache -U "babeldoc<0.3.0" "pymupdf<1.25.3" "pdfminer-six==20250416" && \
31
+ babeldoc --warmup
32
+
33
+ # The rest of the configuration is for RUNNING the built image.
34
+ ports:
35
+ - "7860:7860"
36
+
37
+ environment:
38
+ - PYTHONUNBUFFERED=1
39
+ # The UV_LINK_MODE warning happens during build, so we can set it there if needed,
40
+ # but it's generally harmless.
41
+
42
+ command: ["pdf2zh", "-i"]
43
+
44
+ # Optional: Mount a volume for persistent data I/O if needed
45
+ # volumes:
46
+ # - ./data:/app/data
47
+
48
+ stdin_open: true
49
+ tty: true
docs/ADVANCED.md ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [**Documentation**](https://github.com/Byaidu/PDFMathTranslate) > **Advanced Usage** _(current)_
2
+
3
+ ---
4
+
5
+ <h3 id="toc">Table of Contents</h3>
6
+
7
+ - [Full / partial translation](#partial)
8
+ - [Specify source and target languages](#language)
9
+ - [Translate with different services](#services)
10
+ - [Translate wih exceptions](#exceptions)
11
+ - [Multi-threads](#threads)
12
+ - [Custom prompt](#prompt)
13
+ - [Authorization](#auth)
14
+ - [Custom configuration file](#cofig)
15
+ - [Fonts Subseting](#fonts-subset)
16
+ - [Translation cache](#cache)
17
+
18
+ ---
19
+
20
+ <h3 id="partial">Full / partial translation</h3>
21
+
22
+ - Entire document
23
+
24
+ ```bash
25
+ pdf2zh example.pdf
26
+ ```
27
+
28
+ - Part of the document
29
+
30
+ ```bash
31
+ pdf2zh example.pdf -p 1-3,5
32
+ ```
33
+
34
+ [⬆️ Back to top](#toc)
35
+
36
+ ---
37
+
38
+ <h3 id="language">Specify source and target languages</h3>
39
+
40
+ See [Google Languages Codes](https://developers.google.com/admin-sdk/directory/v1/languages), [DeepL Languages Codes](https://developers.deepl.com/docs/resources/supported-languages)
41
+
42
+ ```bash
43
+ pdf2zh example.pdf -li en -lo ja
44
+ ```
45
+
46
+ [⬆️ Back to top](#toc)
47
+
48
+ ---
49
+
50
+ <h3 id="services">Translate with different services</h3>
51
+
52
+ We've provided a detailed table on the required [environment variables](https://chatgpt.com/share/6734a83d-9d48-800e-8a46-f57ca6e8bcb4) for each translation service. Make sure to set them before using the respective service.
53
+
54
+ | **Translator** | **Service** | **Environment Variables** | **Default Values** | **Notes** |
55
+ |----------------------|----------------|-----------------------------------------------------------------------|----------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
56
+ | **Google (Default)** | `google` | None | N/A | None |
57
+ | **Bing** | `bing` | None | N/A | None |
58
+ | **DeepL** | `deepl` | `DEEPL_AUTH_KEY` | `[Your Key]` | See [DeepL](https://support.deepl.com/hc/en-us/articles/360020695820-API-Key-for-DeepL-s-API) |
59
+ | **DeepLX** | `deeplx` | `DEEPLX_ENDPOINT` | `https://api.deepl.com/translate` | See [DeepLX](https://github.com/OwO-Network/DeepLX) |
60
+ | **Ollama** | `ollama` | `OLLAMA_HOST`, `OLLAMA_MODEL` | `http://127.0.0.1:11434`, `gemma2` | See [Ollama](https://github.com/ollama/ollama) |
61
+ | **Xinference** | `xinference` | `XINFERENCE_HOST`, `XINFERENCE_MODEL` | `http://127.0.0.1:9997`, `gemma-2-it` | See [Xinference](https://github.com/xorbitsai/inference) |
62
+ | **OpenAI** | `openai` | `OPENAI_BASE_URL`, `OPENAI_API_KEY`, `OPENAI_MODEL` | `https://api.openai.com/v1`, `[Your Key]`, `gpt-4o-mini` | See [OpenAI](https://platform.openai.com/docs/overview) |
63
+ | **AzureOpenAI** | `azure-openai` | `AZURE_OPENAI_BASE_URL`, `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_MODEL` | `[Your Endpoint]`, `[Your Key]`, `gpt-4o-mini` | See [Azure OpenAI](https://learn.microsoft.com/zh-cn/azure/ai-services/openai/chatgpt-quickstart?tabs=command-line%2Cjavascript-keyless%2Ctypescript-keyless%2Cpython&pivots=programming-language-python) |
64
+ | **Zhipu** | `zhipu` | `ZHIPU_API_KEY`, `ZHIPU_MODEL` | `[Your Key]`, `glm-4-flash` | See [Zhipu](https://open.bigmodel.cn/dev/api/thirdparty-frame/openai-sdk) |
65
+ | **ModelScope** | `modelscope` | `MODELSCOPE_API_KEY`, `MODELSCOPE_MODEL` | `[Your Key]`, `Qwen/Qwen2.5-Coder-32B-Instruct` | See [ModelScope](https://www.modelscope.cn/docs/model-service/API-Inference/intro) |
66
+ | **Silicon** | `silicon` | `SILICON_API_KEY`, `SILICON_MODEL` | `[Your Key]`, `Qwen/Qwen2.5-7B-Instruct` | See [SiliconCloud](https://docs.siliconflow.cn/quickstart) |
67
+ | **Gemini** | `gemini` | `GEMINI_API_KEY`, `GEMINI_MODEL` | `[Your Key]`, `gemini-1.5-flash` | See [Gemini](https://ai.google.dev/gemini-api/docs/openai) |
68
+ | **Azure** | `azure` | `AZURE_ENDPOINT`, `AZURE_API_KEY` | `https://api.translator.azure.cn`, `[Your Key]` | See [Azure](https://docs.azure.cn/en-us/ai-services/translator/text-translation-overview) |
69
+ | **Tencent** | `tencent` | `TENCENTCLOUD_SECRET_ID`, `TENCENTCLOUD_SECRET_KEY` | `[Your ID]`, `[Your Key]` | See [Tencent](https://www.tencentcloud.com/products/tmt?from_qcintl=122110104) |
70
+ | **Dify** | `dify` | `DIFY_API_URL`, `DIFY_API_KEY` | `[Your DIFY URL]`, `[Your Key]` | See [Dify](https://github.com/langgenius/dify),Three variables, lang_out, lang_in, and text, need to be defined in Dify's workflow input. |
71
+ | **AnythingLLM** | `anythingllm` | `AnythingLLM_URL`, `AnythingLLM_APIKEY` | `[Your AnythingLLM URL]`, `[Your Key]` | See [anything-llm](https://github.com/Mintplex-Labs/anything-llm) |
72
+ |**Argos Translate**|`argos`| | |See [argos-translate](https://github.com/argosopentech/argos-translate)|
73
+ |**Grok**|`grok`| `GORK_API_KEY`, `GORK_MODEL` | `[Your GORK_API_KEY]`, `grok-2-1212` |See [Grok](https://docs.x.ai/docs/overview)|
74
+ |**Groq**|`groq`| `GROQ_API_KEY`, `GROQ_MODEL` | `[Your GROQ_API_KEY]`, `llama-3-3-70b-versatile` |See [Groq](https://console.groq.com/docs/models)|
75
+ |**DeepSeek**|`deepseek`| `DEEPSEEK_API_KEY`, `DEEPSEEK_MODEL` | `[Your DEEPSEEK_API_KEY]`, `deepseek-chat` |See [DeepSeek](https://www.deepseek.com/)|
76
+ |**OpenAI-Liked**|`openailiked`| `OPENAILIKED_BASE_URL`, `OPENAILIKED_API_KEY`, `OPENAILIKED_MODEL` | `url`, `[Your Key]`, `model name` | None |
77
+ |**Ali Qwen Translation**|`qwen-mt`| `ALI_MODEL`, `ALI_API_KEY`, `ALI_DOMAINS` | `qwen-mt-turbo`, `[Your Key]`, `scientific paper` | Tranditional Chinese are not yet supported, it will be translated into Simplified Chinese. More see [Qwen MT](https://bailian.console.aliyun.com/?spm=5176.28197581.0.0.72e329a4HRxe99#/model-market/detail/qwen-mt-turbo) |
78
+
79
+ For large language models that are compatible with the OpenAI API but not listed in the table above, you can set environment variables using the same method outlined for OpenAI in the table.
80
+
81
+ Use `-s service` or `-s service:model` to specify service:
82
+
83
+ ```bash
84
+ pdf2zh example.pdf -s openai:gpt-4o-mini
85
+ ```
86
+
87
+ Or specify model with environment variables:
88
+
89
+ ```bash
90
+ set OPENAI_MODEL=gpt-4o-mini
91
+ pdf2zh example.pdf -s openai
92
+ ```
93
+
94
+ For PowerShell user:
95
+
96
+ ```shell
97
+ $env:OPENAI_MODEL = gpt-4o-mini
98
+ pdf2zh example.pdf -s openai
99
+ ```
100
+
101
+ [⬆️ Back to top](#toc)
102
+
103
+ ---
104
+
105
+ <h3 id="exceptions">Translate wih exceptions</h3>
106
+
107
+ Use regex to specify formula fonts and characters that need to be preserved:
108
+
109
+ ```bash
110
+ pdf2zh example.pdf -f "(CM[^RT].*|MS.*|.*Ital)" -c "(\(|\||\)|\+|=|\d|[\u0080-\ufaff])"
111
+ ```
112
+
113
+ Preserve `Latex`, `Mono`, `Code`, `Italic`, `Symbol` and `Math` fonts by default:
114
+
115
+ ```bash
116
+ pdf2zh example.pdf -f "(CM[^R]|MS.M|XY|MT|BL|RM|EU|LA|RS|LINE|LCIRCLE|TeX-|rsfs|txsy|wasy|stmary|.*Mono|.*Code|.*Ital|.*Sym|.*Math)"
117
+ ```
118
+
119
+ [⬆️ Back to top](#toc)
120
+
121
+ ---
122
+
123
+ <h3 id="threads">Multi-threads</h3>
124
+
125
+ Use `-t` to specify how many threads to use in translation:
126
+
127
+ ```bash
128
+ pdf2zh example.pdf -t 1
129
+ ```
130
+
131
+ [⬆️ Back to top](#toc)
132
+
133
+ ---
134
+
135
+ <h3 id="prompt">Custom prompt</h3>
136
+
137
+ Note: System prompt is currently not supported. See [this change](https://github.com/Byaidu/PDFMathTranslate/pull/637).
138
+
139
+ Use `--prompt` to specify which prompt to use in llm:
140
+
141
+ ```bash
142
+ pdf2zh example.pdf --prompt prompt.txt
143
+ ```
144
+
145
+ For example:
146
+
147
+ ```txt
148
+ You are a professional, authentic machine translation engine. Only Output the translated text, do not include any other text.
149
+
150
+ Translate the following markdown source text to ${lang_out}. Keep the formula notation {v*} unchanged. Output translation directly without any additional text.
151
+
152
+ Source Text: ${text}
153
+
154
+ Translated Text:
155
+ ```
156
+
157
+ In custom prompt file, there are three variables can be used.
158
+
159
+ |**variables**|**comment**|
160
+ |-|-|
161
+ |`lang_in`|input language|
162
+ |`lang_out`|output language|
163
+ |`text`|text need to be translated|
164
+
165
+ [⬆️ Back to top](#toc)
166
+
167
+ ---
168
+
169
+ <h3 id="auth">Authorization</h3>
170
+
171
+ Use `--authorized` to specify which user to use Web UI and custom the login page:
172
+
173
+ ```bash
174
+ pdf2zh example.pdf --authorized users.txt auth.html
175
+ ```
176
+
177
+ example users.txt
178
+ Each line contains two elements, username, and password, separated by a comma.
179
+
180
+ ```
181
+ admin,123456
182
+ user1,password1
183
+ user2,abc123
184
+ guest,guest123
185
+ test,test123
186
+ ```
187
+
188
+ example auth.html
189
+
190
+ ```html
191
+ <!DOCTYPE html>
192
+ <html>
193
+ <head>
194
+ <title>Simple HTML</title>
195
+ </head>
196
+ <body>
197
+ <h1>Hello, World!</h1>
198
+ <p>Welcome to my simple HTML page.</p>
199
+ </body>
200
+ </html>
201
+ ```
202
+
203
+ [⬆️ Back to top](#toc)
204
+
205
+ ---
206
+
207
+ <h3 id="cofig">Custom configuration file</h3>
208
+
209
+ Use `--config` to specify which file to configure the PDFMathTranslate:
210
+
211
+ ```bash
212
+ pdf2zh example.pdf --config config.json
213
+ ```
214
+
215
+ ```bash
216
+ pdf2zh -i --config config.json
217
+ ```
218
+
219
+ example config.json
220
+
221
+ ```json
222
+ {
223
+ "USE_MODELSCOPE": "0",
224
+ "PDF2ZH_LANG_FROM": "English",
225
+ "PDF2ZH_LANG_TO": "Simplified Chinese",
226
+ "NOTO_FONT_PATH": "/app/SourceHanSerifCN-Regular.ttf",
227
+ "translators": [
228
+ {
229
+ "name": "deeplx",
230
+ "envs": {
231
+ "DEEPLX_ENDPOINT": "http://localhost:1188/translate/",
232
+ "DEEPLX_ACCESS_TOKEN": null
233
+ }
234
+ },
235
+ {
236
+ "name": "ollama",
237
+ "envs": {
238
+ "OLLAMA_HOST": "http://127.0.0.1:11434",
239
+ "OLLAMA_MODEL": "gemma2"
240
+ }
241
+ }
242
+ ]
243
+ }
244
+ ```
245
+
246
+ By default, the config file is saved in the `~/.config/PDFMathTranslate/config.json`. The program will start by reading the contents of config.json, and after that it will read the contents of the environment variables. When an environment variable is available, the contents of the environment variable are used first and the file is updated.
247
+
248
+ [⬆️ Back to top](#toc)
249
+
250
+ ---
251
+
252
+ <h3 id="font-subset">Fonts subsetting</h3>
253
+
254
+ By default, PDFMathTranslate uses fonts subsetting to decrease sizes of output files. You can use `--skip-subset-fonts` option to disable fonts subsetting when encoutering compatibility issues.
255
+
256
+ ```bash
257
+ pdf2zh example.pdf --skip-subset-fonts
258
+ ```
259
+
260
+ [⬆️ Back to top](#toc)
261
+
262
+ ---
263
+
264
+ <h3 id="cache">Translation cache</h3>
265
+
266
+ PDFMathTranslate caches translated texts to increase speed and avoid unnecessary API calls for same contents. You can use `--ignore-cache` option to ignore translation cache and force retranslation.
267
+
268
+ ```bash
269
+ pdf2zh example.pdf --ignore-cache
270
+ ```
271
+
272
+ [⬆️ Back to top](#toc)
273
+
274
+ ---
275
+
276
+ <h3 id="public-services">Deployment as a public services</h3>
277
+
278
+ PDFMathTranslate has added the features of **enabling partial services** and **hiding Backend information** in
279
+ the configuration file. You can enable these by setting `ENABLED_SERVICES` and `HIDDEN_GRADIO_DETAILS` in the
280
+ configuration file. Among them:
281
+
282
+ - `ENABLED_SERVICES` allows you to choose to enable only certain options, limiting the number of available services.
283
+ - `HIDDEN_GRADIO_DETAILS` will hide the real API_KEY on the web, preventing users from obtaining server-side keys.
284
+
285
+ A usable configuration is as follows:
286
+
287
+ ```json
288
+ {
289
+ "USE_MODELSCOPE": "0",
290
+ "translators": [
291
+ {
292
+ "name": "grok",
293
+ "envs": {
294
+ "GORK_API_KEY": null,
295
+ "GORK_MODEL": "grok-2-1212"
296
+ }
297
+ },
298
+ {
299
+ "name": "openai",
300
+ "envs": {
301
+ "OPENAI_BASE_URL": "https://api.openai.com/v1",
302
+ "OPENAI_API_KEY": "sk-xxxx",
303
+ "OPENAI_MODEL": "gpt-4o-mini"
304
+ }
305
+ }
306
+ ],
307
+ "ENABLED_SERVICES": [
308
+ "OpenAI",
309
+ "Grok"
310
+ ],
311
+ "HIDDEN_GRADIO_DETAILS": true,
312
+ "PDF2ZH_LANG_FROM": "English",
313
+ "PDF2ZH_LANG_TO": "Simplified Chinese",
314
+ "NOTO_FONT_PATH": "/app/SourceHanSerifCN-Regular.ttf"
315
+ }
316
+ ```
317
+
318
+ [⬆️ Back to top](#toc)
319
+
320
+
321
+ ---
322
+
323
+ <h3 id="mcp">MCP</h3>
324
+
325
+ PDFMathTranslate can run as MCP server. To use this, you need to run `uv pip install pdf2zh`, and config `claude_desktop_config.json`, an example config is as follows:
326
+
327
+ ``` json
328
+ {
329
+ "mcpServers": {
330
+ "filesystem": {
331
+ "command": "npx",
332
+ "args": [
333
+ "-y",
334
+ "@modelcontextprotocol/server-filesystem",
335
+ "/path/to/Document"
336
+ ]
337
+ },
338
+ "translate_pdf": {
339
+ "command": "uv",
340
+ "args": [
341
+ "run",
342
+ "pdf2zh",
343
+ "--mcp"
344
+ ]
345
+ }
346
+ }
347
+ }
348
+ ```
349
+
350
+ [filesystem](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem) is a reuqired mcp server to find pdf file, and `translate_pdf` is our mcp server.
351
+
352
+ To test if the mcp server works, you can open claude desktop and tell
353
+
354
+ ```
355
+ find the `test.pdf` in my Document folder and translate it to Chinese
356
+ ```
docs/APIS.md ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [**Documentation**](https://github.com/Byaidu/PDFMathTranslate) > **API Details** _(current)_
2
+
3
+ <h2 id="toc">Table of Content</h2>
4
+ The present project supports two types of APIs, All methods need the Redis;
5
+
6
+ - [Functional calls in Python](#api-python)
7
+ - [HTTP protocols](#api-http)
8
+
9
+ ---
10
+
11
+ <h2 id="api-python">Python</h2>
12
+
13
+ As `pdf2zh` is an installed module in Python, we expose two methods for other programs to call in any Python scripts.
14
+
15
+ For example, if you want translate a document from English to Chinese using Google Translate, you may use the following code:
16
+
17
+ ```python
18
+ from pdf2zh import translate, translate_stream
19
+
20
+ params = {
21
+ 'lang_in': 'en',
22
+ 'lang_out': 'zh',
23
+ 'service': 'google',
24
+ 'thread': 4,
25
+ }
26
+ ```
27
+ Translate with files:
28
+ ```python
29
+ (file_mono, file_dual) = translate(files=['example.pdf'], **params)[0]
30
+ ```
31
+ Translate with stream:
32
+ ```python
33
+ with open('example.pdf', 'rb') as f:
34
+ (stream_mono, stream_dual) = translate_stream(stream=f.read(), **params)
35
+ ```
36
+
37
+ [⬆️ Back to top](#toc)
38
+
39
+ ---
40
+
41
+ <h2 id="api-http">HTTP</h2>
42
+
43
+ In a more flexible way, you can communicate with the program using HTTP protocols, if:
44
+
45
+ 1. Install and run backend
46
+
47
+ ```bash
48
+ pip install pdf2zh[backend]
49
+ pdf2zh --flask
50
+ pdf2zh --celery worker
51
+ ```
52
+
53
+ 2. Using HTTP protocols as follows:
54
+
55
+ - Submit translate task
56
+
57
+ ```bash
58
+ curl http://localhost:11008/v1/translate -F "[email protected]" -F "data={\"lang_in\":\"en\",\"lang_out\":\"zh\",\"service\":\"google\",\"thread\":4}"
59
+ {"id":"d9894125-2f4e-45ea-9d93-1a9068d2045a"}
60
+ ```
61
+
62
+ - Check Progress
63
+
64
+ ```bash
65
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
66
+ {"info":{"n":13,"total":506},"state":"PROGRESS"}
67
+ ```
68
+
69
+ - Check Progress _(if finished)_
70
+
71
+ ```bash
72
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
73
+ {"state":"SUCCESS"}
74
+ ```
75
+
76
+ - Save monolingual file
77
+
78
+ ```bash
79
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/mono --output example-mono.pdf
80
+ ```
81
+
82
+ - Save bilingual file
83
+
84
+ ```bash
85
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/dual --output example-dual.pdf
86
+ ```
87
+
88
+ - Interrupt if running and delete the task
89
+ ```bash
90
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a -X DELETE
91
+ ```
92
+
93
+ [⬆️ Back to top](#toc)
94
+
95
+ ---
docs/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, religion, or sexual identity
10
+ and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the
26
+ overall community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or
31
+ advances of any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email
35
+ address, without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official e-mail address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series
86
+ of actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or
93
+ permanent ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within
113
+ the community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.0, available at
119
+ https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120
+
121
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
122
+ enforcement ladder](https://github.com/mozilla/diversity).
123
+
124
+ [homepage]: https://www.contributor-covenant.org
125
+
126
+ For answers to common questions about this code of conduct, see the FAQ at
127
+ https://www.contributor-covenant.org/faq. Translations are available at
128
+ https://www.contributor-covenant.org/translations.
docs/README_GUI.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Interact with GUI
2
+
3
+ This subfolder provides the GUI mode of `pdf2zh`.
4
+
5
+ ## Usage
6
+
7
+ 1. Run `pdf2zh -i`
8
+
9
+ 2. Drop the PDF file into the window and click `Translate`.
10
+
11
+ ### Environment Variables
12
+
13
+ You can set the source and target languages using environment variables:
14
+
15
+ - `PDF2ZH_LANG_FROM`: Sets the source language. Defaults to "English".
16
+ - `PDF2ZH_LANG_TO`: Sets the target language. Defaults to "Simplified Chinese".
17
+
18
+ ### Supported Languages
19
+
20
+ The following languages are supported:
21
+
22
+ - English
23
+ - Simplified Chinese
24
+ - Traditional Chinese
25
+ - French
26
+ - German
27
+ - Japanese
28
+ - Korean
29
+ - Russian
30
+ - Spanish
31
+ - Italian
32
+
33
+ ## Preview
34
+
35
+ <img src="./images/before.png" width="500"/>
36
+ <img src="./images/after.png" width="500"/>
37
+
38
+ ## Maintainance
39
+
40
+ GUI maintained by [Rongxin](https://github.com/reycn)
docs/README_ja-JP.md ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ [English](../README.md) | [简体中文](README_zh-CN.md) | [繁體中文](README_zh-TW.md) | 日本語
4
+
5
+ <img src="./images/banner.png" width="320px" alt="PDF2ZH"/>
6
+
7
+ <h2 id="title">PDFMathTranslate</h2>
8
+
9
+ <p>
10
+ <!-- PyPI -->
11
+ <a href="https://pypi.org/project/pdf2zh/">
12
+ <img src="https://img.shields.io/pypi/v/pdf2zh"/></a>
13
+ <a href="https://pepy.tech/projects/pdf2zh">
14
+ <img src="https://static.pepy.tech/badge/pdf2zh"></a>
15
+ <a href="https://hub.docker.com/repository/docker/byaidu/pdf2zh">
16
+ <img src="https://img.shields.io/docker/pulls/byaidu/pdf2zh"></a>
17
+ <!-- License -->
18
+ <a href="./LICENSE">
19
+ <img src="https://img.shields.io/github/license/Byaidu/PDFMathTranslate"/></a>
20
+ <a href="https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker">
21
+ <img src="https://img.shields.io/badge/%F0%9F%A4%97-Online%20Demo-FF9E0D"/></a>
22
+ <a href="https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate">
23
+ <img src="https://img.shields.io/badge/ModelScope-Demo-blue"></a>
24
+ <a href="https://github.com/Byaidu/PDFMathTranslate/pulls">
25
+ <img src="https://img.shields.io/badge/contributions-welcome-green"/></a>
26
+ <a href="https://gitcode.com/Byaidu/PDFMathTranslate/overview">
27
+ <img src="https://gitcode.com/Byaidu/PDFMathTranslate/star/badge.svg"></a>
28
+ <a href="https://t.me/+Z9_SgnxmsmA5NzBl">
29
+ <img src="https://img.shields.io/badge/Telegram-2CA5E0?style=flat-squeare&logo=telegram&logoColor=white"/></a>
30
+ </p>
31
+
32
+ <a href="https://trendshift.io/repositories/12424" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12424" alt="Byaidu%2FPDFMathTranslate | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
33
+
34
+ </div>
35
+
36
+ 科学 PDF 文書の翻訳およびバイリンガル比較ツール
37
+
38
+ - 📊 数式、チャート、目次、注釈を保持 *([プレビュー](#preview))*
39
+ - 🌐 [複数の言語](#language) と [多様な翻訳サービス](#services) をサポート
40
+ - 🤖 [コマンドラインツール](#usage)、[インタラクティブユーザーインターフェース](#gui)、および [Docker](#docker) を提供
41
+
42
+ フィードバックは [GitHub Issues](https://github.com/Byaidu/PDFMathTranslate/issues)、[Telegram グループ](https://t.me/+Z9_SgnxmsmA5NzBl)
43
+
44
+ <h2 id="updates">最近の更新</h2>
45
+
46
+ - [2024年11月26日] CLIがオンラインファイルをサポートするようになりました *(by [@reycn](https://github.com/reycn))*
47
+ - [2024年11月24日] 依存関係のサイズを削減するために [ONNX](https://github.com/onnx/onnx) サポートを追加しました *(by [@Wybxc](https://github.com/Wybxc))*
48
+ - [2024年11月23日] 🌟 [公共サービス](#demo) がオンラインになりました! *(by [@Byaidu](https://github.com/Byaidu))*
49
+ - [2024年11月23日] ウェブボットを防ぐためのファイアウォールを追加しました *(by [@Byaidu](https://github.com/Byaidu))*
50
+ - [2024年11月22日] GUIがイタリア語をサポートし、改善されました *(by [@Byaidu](https://github.com/Byaidu), [@reycn](https://github.com/reycn))*
51
+ - [2024年11月22日] デプロイされたサービスを他の人と共有できるようになりました *(by [@Zxis233](https://github.com/Zxis233))*
52
+ - [2024年11月22日] Tencent翻訳をサポートしました *(by [@hellofinch](https://github.com/hellofinch))*
53
+ - [2024年11月21日] GUIがバイリンガルドキュメントのダウンロードをサポートするようになりました *(by [@reycn](https://github.com/reycn))*
54
+ - [2024年11月20日] 🌟 [デモ](#demo) がオンラインになりました! *(by [@reycn](https://github.com/reycn))*
55
+
56
+ <h2 id="preview">プレビュー</h2>
57
+
58
+ <div align="center">
59
+ <img src="./images/preview.gif" width="80%"/>
60
+ </div>
61
+
62
+ <h2 id="demo">公共サービス 🌟</h2>
63
+
64
+ ### 無料サービス (<https://pdf2zh.com/>)
65
+
66
+ インストールなしで [公共サービス](https://pdf2zh.com/) をオンラインで試すことができます。
67
+
68
+ ### デモ
69
+
70
+ インストールなしで [HuggingFace上のデモ](https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker), [ModelScope上のデモ](https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate) を試すことができます。
71
+ デモの計算リソースは限られているため、乱用しないようにしてください。
72
+
73
+ <h2 id="install">インストールと使用方法</h2>
74
+
75
+ このプロジェクトを使用するための4つの方法を提供しています:[コマンドライン](#cmd)、[ポータブル](#portable)、[GUI](#gui)、および [Docker](#docker)。
76
+
77
+ pdf2zhの実行には追加モデル(`wybxc/DocLayout-YOLO-DocStructBench-onnx`)が必要です。このモデルはModelScopeでも見つけることができます。起動時にこのモデルのダウンロードに問題がある場合は、以下の環境変数を使用してください:
78
+
79
+ ```shell
80
+ set HF_ENDPOINT=https://hf-mirror.com
81
+ ```
82
+
83
+ For PowerShell user:
84
+ ```shell
85
+ $env:HF_ENDPOINT = https://hf-mirror.com
86
+ ```
87
+
88
+ <h3 id="cmd">方法1. コマンドライン</h3>
89
+
90
+ 1. Pythonがインストールされていること (バージョン3.10 <= バージョン <= 3.12)
91
+ 2. パッケージをインストールします:
92
+
93
+ ```bash
94
+ pip install pdf2zh
95
+ ```
96
+
97
+ 3. 翻訳を実行し、[現在の作業ディレクトリ](https://chatgpt.com/share/6745ed36-9acc-800e-8a90-59204bd13444) にファイルを生成します:
98
+
99
+ ```bash
100
+ pdf2zh document.pdf
101
+ ```
102
+
103
+ <h3 id="portable">方法2. ポータブル</h3>
104
+
105
+ Python環境を事前にインストールする必要はありません
106
+
107
+ [setup.bat](https://raw.githubusercontent.com/Byaidu/PDFMathTranslate/refs/heads/main/script/setup.bat) をダウンロードしてダブルクリックして実行します
108
+
109
+ <h3 id="gui">方法3. GUI</h3>
110
+
111
+ 1. Pythonがインストールされていること (バージョン3.10 <= バージョン <= 3.12)
112
+ 2. パッケージをインストールします:
113
+
114
+ ```bash
115
+ pip install pdf2zh
116
+ ```
117
+
118
+ 3. ブラウザで使用を開始します:
119
+
120
+ ```bash
121
+ pdf2zh -i
122
+ ```
123
+
124
+ 4. ブラウザが自動的に起動しない場合は、次のURLを開きます:
125
+
126
+ ```bash
127
+ http://localhost:7860/
128
+ ```
129
+
130
+ <img src="./images/gui.gif" width="500"/>
131
+
132
+ 詳細については、[GUIのドキュメント](./README_GUI.md) を参照してください。
133
+
134
+ <h3 id="docker">方法4. Docker</h3>
135
+
136
+ 1. プルして実行します:
137
+
138
+ ```bash
139
+ docker pull byaidu/pdf2zh
140
+ docker run -d -p 7860:7860 byaidu/pdf2zh
141
+ ```
142
+
143
+ 2. ブラウザで開きます:
144
+
145
+ ```
146
+ http://localhost:7860/
147
+ ```
148
+
149
+ クラウドサービスでのDockerデプロイメント用:
150
+
151
+ <div>
152
+ <a href="https://www.heroku.com/deploy?template=https://github.com/Byaidu/PDFMathTranslate">
153
+ <img src="https://www.herokucdn.com/deploy/button.svg" alt="Deploy" height="26"></a>
154
+ <a href="https://render.com/deploy">
155
+ <img src="https://render.com/images/deploy-to-render-button.svg" alt="Deploy to Koyeb" height="26"></a>
156
+ <a href="https://zeabur.com/templates/5FQIGX?referralCode=reycn">
157
+ <img src="https://zeabur.com/button.svg" alt="Deploy on Zeabur" height="26"></a>
158
+ <a href="https://app.koyeb.com/deploy?type=git&builder=buildpack&repository=github.com/Byaidu/PDFMathTranslate&branch=main&name=pdf-math-translate">
159
+ <img src="https://www.koyeb.com/static/images/deploy/button.svg" alt="Deploy to Koyeb" height="26"></a>
160
+ </div>
161
+
162
+ <h2 id="usage">高度なオプション</h2>
163
+
164
+ コマンドラインで翻訳コマンドを実行し、現在の作業ディレクトリに翻訳されたドキュメント `example-mono.pdf` とバイリンガルドキュメント `example-dual.pdf` を生成します。デフォルトではGoogle翻訳サービスを使用します。More support translation services can find [HERE](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#services).
165
+
166
+
167
+ <img src="./images/cmd.explained.png" width="580px" alt="cmd"/>
168
+
169
+ 以下の表に、参考のためにすべての高度なオプションをリストしました:
170
+
171
+ | オプション | 機能 | 例 |
172
+ | -------- | ------- |------- |
173
+ | files | ローカルファイル | `pdf2zh ~/local.pdf` |
174
+ | links | オンラインファイル | `pdf2zh http://arxiv.org/paper.pdf` |
175
+ | `-i` | [GUIに入る](#gui) | `pdf2zh -i` |
176
+ | `-p` | [部分的なドキュメント翻訳](#partial) | `pdf2zh example.pdf -p 1` |
177
+ | `-li` | [ソース言語](#languages) | `pdf2zh example.pdf -li en` |
178
+ | `-lo` | [ターゲット言語](#languages) | `pdf2zh example.pdf -lo zh` |
179
+ | `-s` | [翻訳サービス](#services) | `pdf2zh example.pdf -s deepl` |
180
+ | `-t` | [マルチスレッド](#threads) | `pdf2zh example.pdf -t 1` |
181
+ | `-o` | 出力ディレクトリ | `pdf2zh example.pdf -o output` |
182
+ | `-f`, `-c` | [例外](#exceptions) | `pdf2zh example.pdf -f "(MS.*)"` |
183
+ | `--share` | [gradio公開リンクを取得] | `pdf2zh -i --share` |
184
+ | `--authorized` | [[ウェブ認証とカスタム認証ページの追加](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.)] | `pdf2zh -i --authorized users.txt [auth.html]` |
185
+ | `--prompt` | [カスタムビッグモデルのプロンプトを使用する] | `pdf2zh --prompt [prompt.txt]` |
186
+ | `--onnx` | [カスタムDocLayout-YOLO ONNXモデルの使用] | `pdf2zh --onnx [onnx/model/path]` |
187
+ | `--serverport` | [カスタムWebUIポートを使用する] | `pdf2zh --serverport 7860` |
188
+ | `--dir` | [batch translate] | `pdf2zh --dir /path/to/translate/` |
189
+ | `--config` | [configuration file](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#cofig) | `pdf2zh --config /path/to/config/config.json` |
190
+ | `--serverport` | [custom gradio server port] | `pdf2zh --serverport 7860` |
191
+
192
+ <h3 id="partial">全文または部分的なドキュメント翻訳</h3>
193
+
194
+ - **全文翻訳**
195
+
196
+ ```bash
197
+ pdf2zh example.pdf
198
+ ```
199
+
200
+ - **部分翻訳**
201
+
202
+ ```bash
203
+ pdf2zh example.pdf -p 1-3,5
204
+ ```
205
+
206
+ <h3 id="language">ソース言語とターゲット言語を指定</h3>
207
+
208
+ [Google Languages Codes](https://developers.google.com/admin-sdk/directory/v1/languages)、[DeepL Languages Codes](https://developers.deepl.com/docs/resources/supported-languages) を参照してください
209
+
210
+ ```bash
211
+ pdf2zh example.pdf -li en -lo ja
212
+ ```
213
+
214
+ <h3 id="services">異なるサービスで翻訳</h3>
215
+
216
+ 以下の表は、各翻訳サービスに必要な [環境変数](https://chatgpt.com/share/6734a83d-9d48-800e-8a46-f57ca6e8bcb4) を示しています。各サービスを使用する前に、これらの変数を設定してください。
217
+
218
+ |**Translator**|**Service**|**Environment Variables**|**Default Values**|**Notes**|
219
+ |-|-|-|-|-|
220
+ |**Google (Default)**|`google`|None|N/A|None|
221
+ |**Bing**|`bing`|None|N/A|None|
222
+ |**DeepL**|`deepl`|`DEEPL_AUTH_KEY`|`[Your Key]`|See [DeepL](https://support.deepl.com/hc/en-us/articles/360020695820-API-Key-for-DeepL-s-API)|
223
+ |**DeepLX**|`deeplx`|`DEEPLX_ENDPOINT`|`https://api.deepl.com/translate`|See [DeepLX](https://github.com/OwO-Network/DeepLX)|
224
+ |**Ollama**|`ollama`|`OLLAMA_HOST`, `OLLAMA_MODEL`|`http://127.0.0.1:11434`, `gemma2`|See [Ollama](https://github.com/ollama/ollama)|
225
+ |**OpenAI**|`openai`|`OPENAI_BASE_URL`, `OPENAI_API_KEY`, `OPENAI_MODEL`|`https://api.openai.com/v1`, `[Your Key]`, `gpt-4o-mini`|See [OpenAI](https://platform.openai.com/docs/overview)|
226
+ |**AzureOpenAI**|`azure-openai`|`AZURE_OPENAI_BASE_URL`, `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_MODEL`|`[Your Endpoint]`, `[Your Key]`, `gpt-4o-mini`|See [Azure OpenAI](https://learn.microsoft.com/zh-cn/azure/ai-services/openai/chatgpt-quickstart?tabs=command-line%2Cjavascript-keyless%2Ctypescript-keyless%2Cpython&pivots=programming-language-python)|
227
+ |**Zhipu**|`zhipu`|`ZHIPU_API_KEY`, `ZHIPU_MODEL`|`[Your Key]`, `glm-4-flash`|See [Zhipu](https://open.bigmodel.cn/dev/api/thirdparty-frame/openai-sdk)|
228
+ | **ModelScope** | `modelscope` |`MODELSCOPE_API_KEY`, `MODELSCOPE_MODEL`|`[Your Key]`, `Qwen/Qwen2.5-Coder-32B-Instruct`| See [ModelScope](https://www.modelscope.cn/docs/model-service/API-Inference/intro)|
229
+ |**Silicon**|`silicon`|`SILICON_API_KEY`, `SILICON_MODEL`|`[Your Key]`, `Qwen/Qwen2.5-7B-Instruct`|See [SiliconCloud](https://docs.siliconflow.cn/quickstart)|
230
+ |**Gemini**|`gemini`|`GEMINI_API_KEY`, `GEMINI_MODEL`|`[Your Key]`, `gemini-1.5-flash`|See [Gemini](https://ai.google.dev/gemini-api/docs/openai)|
231
+ |**Azure**|`azure`|`AZURE_ENDPOINT`, `AZURE_API_KEY`|`https://api.translator.azure.cn`, `[Your Key]`|See [Azure](https://docs.azure.cn/en-us/ai-services/translator/text-translation-overview)|
232
+ |**Tencent**|`tencent`|`TENCENTCLOUD_SECRET_ID`, `TENCENTCLOUD_SECRET_KEY`|`[Your ID]`, `[Your Key]`|See [Tencent](https://www.tencentcloud.com/products/tmt?from_qcintl=122110104)|
233
+ |**Dify**|`dify`|`DIFY_API_URL`, `DIFY_API_KEY`|`[Your DIFY URL]`, `[Your Key]`|See [Dify](https://github.com/langgenius/dify),Three variables, lang_out, lang_in, and text, need to be defined in Dify's workflow input.|
234
+ |**AnythingLLM**|`anythingllm`|`AnythingLLM_URL`, `AnythingLLM_APIKEY`|`[Your AnythingLLM URL]`, `[Your Key]`|See [anything-llm](https://github.com/Mintplex-Labs/anything-llm)|
235
+ |**Argos Translate**|`argos`| | |See [argos-translate](https://github.com/argosopentech/argos-translate)|
236
+ |**Grok**|`grok`| `GORK_API_KEY`, `GORK_MODEL` | `[Your GORK_API_KEY]`, `grok-2-1212` |See [Grok](https://docs.x.ai/docs/overview)|
237
+ |**DeepSeek**|`deepseek`| `DEEPSEEK_API_KEY`, `DEEPSEEK_MODEL` | `[Your DEEPSEEK_API_KEY]`, `deepseek-chat` |See [DeepSeek](https://www.deepseek.com/)|
238
+ |**OpenAI-Liked**|`openailiked`| `OPENAILIKED_BASE_URL`, `OPENAILIKED_API_KEY`, `OPENAILIKED_MODEL` | `url`, `[Your Key]`, `model name` | None |
239
+
240
+ (need Japenese translation)
241
+ For large language models that are compatible with the OpenAI API but not listed in the table above, you can set environment variables using the same method outlined for OpenAI in the table.
242
+
243
+ `-s service` または `-s service:model` を使用してサービスを指定します:
244
+
245
+ ```bash
246
+ pdf2zh example.pdf -s openai:gpt-4o-mini
247
+ ```
248
+
249
+ または環境変数でモデルを指定します:
250
+
251
+ ```bash
252
+ set OPENAI_MODEL=gpt-4o-mini
253
+ pdf2zh example.pdf -s openai
254
+ ```
255
+
256
+ For PowerShell user:
257
+ ```shell
258
+ $env:OPENAI_MODEL = gpt-4o-mini
259
+ pdf2zh example.pdf -s openai
260
+ ```
261
+
262
+ <h3 id="exceptions">例外を指定して翻訳</h3>
263
+
264
+ 正規表現を使用して保持する必要がある数式フォントと文字を指定します:
265
+
266
+ ```bash
267
+ pdf2zh example.pdf -f "(CM[^RT].*|MS.*|.*Ital)" -c "(\(|\||\)|\+|=|\d|[\u0080-\ufaff])"
268
+ ```
269
+
270
+ デフォルトで `Latex`、`Mono`、`Code`、`Italic`、`Symbol` および `Math` フォントを保持します:
271
+
272
+ ```bash
273
+ pdf2zh example.pdf -f "(CM[^R]|MS.M|XY|MT|BL|RM|EU|LA|RS|LINE|LCIRCLE|TeX-|rsfs|txsy|wasy|stmary|.*Mono|.*Code|.*Ital|.*Sym|.*Math)"
274
+ ```
275
+
276
+ <h3 id="threads">スレッド数を指定</h3>
277
+
278
+ `-t` を使用して翻訳に使用するスレッド数を指定します:
279
+
280
+ ```bash
281
+ pdf2zh example.pdf -t 1
282
+ ```
283
+
284
+ <h3 id="prompt">カスタム プロンプト</h3>
285
+
286
+ `--prompt`を使用して、LLMで使用するプロンプトを指定します:
287
+
288
+ ```bash
289
+ pdf2zh example.pdf -pr prompt.txt
290
+ ```
291
+
292
+
293
+ `prompt.txt`の例:
294
+
295
+ ```txt
296
+ [
297
+ {
298
+ "role": "system",
299
+ "content": "You are a professional,authentic machine translation engine.",
300
+ },
301
+ {
302
+ "role": "user",
303
+ "content": "Translate the following markdown source text to ${lang_out}. Keep the formula notation {{v*}} unchanged. Output translation directly without any additional text.\nSource Text: ${text}\nTranslated Text:",
304
+ },
305
+ ]
306
+ ```
307
+
308
+
309
+ カスタムプロンプトファイルでは、以下の3つの変数が使用できます。
310
+
311
+ |**変数**|**内容**|
312
+ |-|-|
313
+ |`lang_in`|ソース言語|
314
+ |`lang_out`|ターゲット言語|
315
+ |`text`|翻訳するテキスト|
316
+
317
+ <h2 id="todo">API</h2>
318
+
319
+ ### Python
320
+
321
+ ```python
322
+ from pdf2zh import translate, translate_stream
323
+
324
+ params = {"lang_in": "en", "lang_out": "zh", "service": "google", "thread": 4}
325
+ file_mono, file_dual = translate(files=["example.pdf"], **params)[0]
326
+ with open("example.pdf", "rb") as f:
327
+ stream_mono, stream_dual = translate_stream(stream=f.read(), **params)
328
+ ```
329
+
330
+ ### HTTP
331
+
332
+ ```bash
333
+ pip install pdf2zh[backend]
334
+ pdf2zh --flask
335
+ pdf2zh --celery worker
336
+ ```
337
+
338
+ ```bash
339
+ curl http://localhost:11008/v1/translate -F "[email protected]" -F "data={\"lang_in\":\"en\",\"lang_out\":\"zh\",\"service\":\"google\",\"thread\":4}"
340
+ {"id":"d9894125-2f4e-45ea-9d93-1a9068d2045a"}
341
+
342
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
343
+ {"info":{"n":13,"total":506},"state":"PROGRESS"}
344
+
345
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
346
+ {"state":"SUCCESS"}
347
+
348
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/mono --output example-mono.pdf
349
+
350
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/dual --output example-dual.pdf
351
+
352
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a -X DELETE
353
+ ```
354
+
355
+ <h2 id="acknowledgement">謝辞</h2>
356
+
357
+ - ドキュメントのマージ:[PyMuPDF](https://github.com/pymupdf/PyMuPDF)
358
+
359
+ - ドキュメントの解析:[Pdfminer.six](https://github.com/pdfminer/pdfminer.six)
360
+
361
+ - ドキュメントの抽出:[MinerU](https://github.com/opendatalab/MinerU)
362
+
363
+ - ドキュメントプレビュー:[Gradio PDF](https://github.com/freddyaboulton/gradio-pdf)
364
+
365
+ - マルチスレッド翻訳:[MathTranslate](https://github.com/SUSYUSTC/MathTranslate)
366
+
367
+ - レイアウト解析:[DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO)
368
+
369
+ - ドキュメント標準:[PDF Explained](https://zxyle.github.io/PDF-Explained/)、[PDF Cheat Sheets](https://pdfa.org/resource/pdf-cheat-sheets/)
370
+
371
+ - 多言語フォント:[Go Noto Universal](https://github.com/satbyy/go-noto-universal)
372
+
373
+ <h2 id="contrib">貢献者</h2>
374
+
375
+ <a href="https://github.com/Byaidu/PDFMathTranslate/graphs/contributors">
376
+ <img src="https://opencollective.com/PDFMathTranslate/contributors.svg?width=890&button=false" />
377
+ </a>
378
+
379
+ ![Alt](https://repobeats.axiom.co/api/embed/dfa7583da5332a11468d686fbd29b92320a6a869.svg "Repobeats analytics image")
380
+
381
+ <h2 id="star_hist">スター履歴</h2>
382
+
383
+ <a href="https://star-history.com/#Byaidu/PDFMathTranslate&Date">
384
+ <picture>
385
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date&theme=dark" />
386
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date" />
387
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date"/>
388
+ </picture>
389
+ </a>
docs/README_ko-KR.md ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Create new file
2
+
3
+ <div align="center">
4
+
5
+ [English](../README.md) | [简体中文](README_zh-CN.md) | [繁體中文](README_zh-TW.md) | [日本語](README_ja-JP.md) | 한국어
6
+
7
+ <img src="./images/banner.png" width="320px" alt="PDF2ZH"/>
8
+
9
+ <h2 id="title">PDFMathTranslate</h2>
10
+
11
+ <p>
12
+ <!-- PyPI -->
13
+ <a href="https://pypi.org/project/pdf2zh/">
14
+ <img src="https://img.shields.io/pypi/v/pdf2zh"/></a>
15
+ <a href="https://pepy.tech/projects/pdf2zh">
16
+ <img src="https://static.pepy.tech/badge/pdf2zh"></a>
17
+ <a href="https://hub.docker.com/repository/docker/byaidu/pdf2zh">
18
+ <img src="https://img.shields.io/docker/pulls/byaidu/pdf2zh"></a>
19
+ <!-- License -->
20
+ <a href="./LICENSE">
21
+ <img src="https://img.shields.io/github/license/Byaidu/PDFMathTranslate"/></a>
22
+ <a href="https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker">
23
+ <img src="https://img.shields.io/badge/%F0%9F%A4%97-Online%20Demo-FF9E0D"/></a>
24
+ <a href="https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate">
25
+ <img src="https://img.shields.io/badge/ModelScope-Demo-blue"></a>
26
+ <a href="https://github.com/Byaidu/PDFMathTranslate/pulls">
27
+ <img src="https://img.shields.io/badge/contributions-welcome-green"/></a>
28
+ <a href="https://gitcode.com/Byaidu/PDFMathTranslate/overview">
29
+ <img src="https://gitcode.com/Byaidu/PDFMathTranslate/star/badge.svg"></a>
30
+ <a href="https://t.me/+Z9_SgnxmsmA5NzBl">
31
+ <img src="https://img.shields.io/badge/Telegram-2CA5E0?style=flat-squeare&logo=telegram&logoColor=white"/></a>
32
+ </p>
33
+
34
+ <a href="https://trendshift.io/repositories/12424" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12424" alt="Byaidu%2FPDFMathTranslate | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
35
+
36
+ </div>
37
+
38
+ 과학 PDF 문서 번역 및 이중 언어 비교 도구
39
+
40
+ - 📊 수식, 차트, 목차, 주석 유지 _([미리보기](#preview))_
41
+ - 🌐 [다양한 언어](#language)와 [다양한 번역 서비스](#services) 지원
42
+ - 🤖 [커맨드라인 도구](#usage), [대화형 사용자 인터페이스](#gui), 및 [Docker](#docker) 제공
43
+
44
+ 피드백은 [GitHub Issues](https://github.com/Byaidu/PDFMathTranslate/issues) 또는 [Telegram 그룹](https://t.me/+Z9_SgnxmsmA5NzBl)에서 해주세요.
45
+
46
+ <h2 id="updates">최근 업데이트</h2>
47
+
48
+ - [2024년 12월 24일] [Xinference](https://github.com/xorbitsai/inference) 실행 로컬 LLM 지원 추가 _(by [@imClumsyPanda](https://github.com/imClumsyPanda))_
49
+ - [2024년 11월 26일] CLI가 온라인 파일을 지원하게 되었습니다 _(by [@reycn](https://github.com/reycn))_
50
+ - [2024년 11월 24일] 의존성 크기를 줄이기 위해 [ONNX](https://github.com/onnx/onnx) 지원 추가 _(by [@Wybxc](https://github.com/Wybxc))_
51
+ - [2024년 11월 23일] 🌟 [무료 공공 서비스](#demo) 온라인! _(by [@Byaidu](https://github.com/Byaidu))_
52
+ - [2024년 11월 23일] 웹 봇을 방지하기 위한 방화벽 추가 _(by [@Byaidu](https://github.com/Byaidu))_
53
+ - [2024년 11월 22일] GUI가 이탈리아어를 지원하고 개선되었습니다 _(by [@Byaidu](https://github.com/Byaidu), [@reycn](https://github.com/reycn))_
54
+ - [2024년 11월 22일] 배포된 서비스를 다른 사람과 공유할 수 있게 되었습니다 _(by [@Zxis233](https://github.com/Zxis233))_
55
+ - [2024년 11월 22일] Tencent 번역 지원 _(by [@hellofinch](https://github.com/hellofinch))_
56
+ - [2024년 11월 21일] GUI가 이중 언어 문서 다운로드를 지원하게 되었습니다 _(by [@reycn](https://github.com/reycn))_
57
+ - [2024년 11월 20일] 🌟 [데모](#demo)가 온라인이 되었습니다! _(by [@reycn](https://github.com/reycn))_
58
+
59
+ <h2 id="preview">미리보기</h2>
60
+
61
+ <div align="center">
62
+ <img src="./images/preview.gif" width="80%"/>
63
+ </div>
64
+
65
+ <h2 id="demo">공공 서비스 🌟</h2>
66
+
67
+ ### 무료 서비스 (<https://pdf2zh.com/>)
68
+
69
+ 설치 없이 [무료 공공 서비스](https://pdf2zh.com/)를 온라인으로 사용해 볼 수 있습니다.
70
+
71
+ ### 데모
72
+
73
+ 설치 없이 [HuggingFace의 데모](https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker)와 [ModelScope의 데모](https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate)를 사용해 볼 수 있습니다.
74
+ 데모의 컴퓨팅 리소스가 제한되어 있으므로 남용하지 말아주세요.
75
+
76
+ <h2 id="install">설치 및 사용법</h2>
77
+
78
+ 이 프로젝트를 사용하는 4가지 방법을 제공합니다: [커맨드라인 도구](#cmd), [포터블](#portable), [GUI](#gui), 및 [Docker](#docker).
79
+
80
+ pdf2zh 실행에는 추가 모델(`wybxc/DocLayout-YOLO-DocStructBench-onnx`)이 필요합니다. 이 모델은 ModelScope에서도 찾을 수 있습니다. 시작할 때 이 모델 다운로드에 문제가 있다면 다음 환경 변수를 사용하세요:
81
+
82
+ ```shell
83
+ set HF_ENDPOINT=https://hf-mirror.com
84
+ ```
85
+
86
+ PowerShell 사용자의 경우:
87
+
88
+ ```shell
89
+ $env:HF_ENDPOINT = https://hf-mirror.com
90
+ ```
91
+
92
+ <h3 id="cmd">방법 1. 커맨드라인 도구</h3>
93
+
94
+ 1. Python이 설치되어 있어야 합니다 (버전 3.10 <= 버전 <= 3.12)
95
+ 2. 패키지를 설치합니다:
96
+
97
+ ```bash
98
+ pip install pdf2zh
99
+ ```
100
+
101
+ 3. 번역을 실행하고 [현재 작업 디렉토리](https://chatgpt.com/share/6745ed36-9acc-800e-8a90-59204bd13444)에 파일을 생성합니다:
102
+
103
+ ```bash
104
+ pdf2zh document.pdf
105
+ ```
106
+
107
+ <h3 id="portable">방법 2. 포터블</h3>
108
+
109
+ Python 환경을 미리 설치할 필요가 없습니다.
110
+
111
+ [setup.bat](https://raw.githubusercontent.com/Byaidu/PDFMathTranslate/refs/heads/main/script/setup.bat)을 다운로드하고 더블클릭하여 실행합니다.
112
+
113
+ <h3 id="gui">방법 3. GUI</h3>
114
+
115
+ 1. Python이 설치되어 있어야 합니다 (버전 3.10 <= 버전 <= 3.12)
116
+ 2. 패키지를 설치합니다:
117
+
118
+ ```bash
119
+ pip install pdf2zh
120
+ ```
121
+
122
+ 3. 브라우저에서 사용을 시작합니다:
123
+
124
+ ```bash
125
+ pdf2zh -i
126
+ ```
127
+
128
+ 4. 브라우저가 자동으로 시작되지 않으면 다음 URL을 엽니다:
129
+
130
+ ```bash
131
+ http://localhost:7860/
132
+ ```
133
+
134
+ <img src="./images/gui.gif" width="500"/>
135
+
136
+ 자세한 내용은 [GUI 문서](./README_GUI.md)를 참조하세요.
137
+
138
+ <h3 id="docker">방법 4. Docker</h3>
139
+
140
+ 1. 풀하고 실행합니다:
141
+
142
+ ```bash
143
+ docker pull byaidu/pdf2zh
144
+ docker run -d -p 7860:7860 byaidu/pdf2zh
145
+ ```
146
+
147
+ 2. 브라우저에서 엽니다:
148
+
149
+ ```
150
+ http://localhost:7860/
151
+ ```
152
+
153
+ 클라우드 서비스에서 Docker 배포용:
154
+
155
+ <div>
156
+ <a href="https://www.heroku.com/deploy?template=https://github.com/Byaidu/PDFMathTranslate">
157
+ <img src="https://www.herokucdn.com/deploy/button.svg" alt="Deploy" height="26"></a>
158
+ <a href="https://render.com/deploy">
159
+ <img src="https://render.com/images/deploy-to-render-button.svg" alt="Deploy to Koyeb" height="26"></a>
160
+ <a href="https://zeabur.com/templates/5FQIGX?referralCode=reycn">
161
+ <img src="https://zeabur.com/button.svg" alt="Deploy on Zeabur" height="26"></a>
162
+ <a href="https://app.koyeb.com/deploy?type=git&builder=buildpack&repository=github.com/Byaidu/PDFMathTranslate&branch=main&name=pdf-math-translate">
163
+ <img src="https://www.koyeb.com/static/images/deploy/button.svg" alt="Deploy to Koyeb" height="26"></a>
164
+ </div>
165
+
166
+ <h2 id="usage">고급 옵션</h2>
167
+
168
+ 커맨드라인에서 번역 명령을 실행하여 현재 작업 디렉토리에 번역된 문서 `example-mono.pdf`와 이중 언어 문서 `example-dual.pdf`를 생성합니다. 기본적으로 Google 번역 서비스를 사용합니다. 더 많은 지원 번역 서비스는 [여기](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#services)에서 찾을 수 있습니다.
169
+
170
+ <img src="./images/cmd.explained.png" width="580px" alt="cmd"/>
171
+
172
+ 다음 표에 참고용으로 모든 고급 옵션을 나열했습니다:
173
+
174
+ | 옵션 | 기능 | 예시 |
175
+ | -------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
176
+ | files | 로컬 파일 | `pdf2zh ~/local.pdf` |
177
+ | links | 온라인 파일 | `pdf2zh http://arxiv.org/paper.pdf` |
178
+ | `-i` | [GUI 진입](#gui) | `pdf2zh -i` |
179
+ | `-p` | [부분 문서 번역](#partial) | `pdf2zh example.pdf -p 1` |
180
+ | `-li` | [소스 언어](#languages) | `pdf2zh example.pdf -li en` |
181
+ | `-lo` | [대상 언어](#languages) | `pdf2zh example.pdf -lo zh` |
182
+ | `-s` | [번역 서비스](#services) | `pdf2zh example.pdf -s deepl` |
183
+ | `-t` | [멀티스레드](#threads) | `pdf2zh example.pdf -t 1` |
184
+ | `-o` | 출력 디렉토리 | `pdf2zh example.pdf -o output` |
185
+ | `-f`, `-c` | [예외](#exceptions) | `pdf2zh example.pdf -f "(MS.*)"` |
186
+ | `--share` | [gradio 공개 링크 얻기] | `pdf2zh -i --share` |
187
+ | `--authorized` | [[웹 인증 및 사용자 정의 인증 페이지 추가](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.)] | `pdf2zh -i --authorized users.txt [auth.html]` |
188
+ | `--prompt` | [사용자 정의 대형 모델 프롬프트 사용] | `pdf2zh --prompt [prompt.txt]` |
189
+ | `--onnx` | [사용자 정의 DocLayout-YOLO ONNX 모델 사용] | `pdf2zh --onnx [onnx/model/path]` |
190
+ | `--serverport` | [사용자 정의 WebUI 포트 사용] | `pdf2zh --serverport 7860` |
191
+ | `--dir` | [배치 번역] | `pdf2zh --dir /path/to/translate/` |
192
+ | `--config` | [구성 파일](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#cofig) | `pdf2zh --config /path/to/config/config.json` |
193
+
194
+ <h3 id="partial">전체 또는 부분 문서 번역</h3>
195
+
196
+ - **전체 번역**
197
+
198
+ ```bash
199
+ pdf2zh example.pdf
200
+ ```
201
+
202
+ - **부분 번역**
203
+
204
+ ```bash
205
+ pdf2zh example.pdf -p 1-3,5
206
+ ```
207
+
208
+ <h3 id="language">소스 언어와 대상 언어 지정</h3>
209
+
210
+ [Google Languages Codes](https://developers.google.com/admin-sdk/directory/v1/languages), [DeepL Languages Codes](https://developers.deepl.com/docs/resources/supported-languages) 참조
211
+
212
+ ```bash
213
+ pdf2zh example.pdf -li en -lo ko
214
+ ```
215
+
216
+ <h3 id="services">다른 서비스로 번역</h3>
217
+
218
+ 다음 표는 각 번역 서비스에 필요한 [환경 변수](https://chatgpt.com/share/6734a83d-9d48-800e-8a46-f57ca6e8bcb4)를 보여줍니다. 각 서비스를 사용하기 전에 이러한 변수를 설정하세요.
219
+
220
+ | **번역기** | **서비스** | **환경 변수** | **기본값** | **참고** |
221
+ | ------------------- | -------------- | --------------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
222
+ | **Google (기본)** | `google` | 없음 | N/A | 없음 |
223
+ | **Bing** | `bing` | 없음 | N/A | 없음 |
224
+ | **DeepL** | `deepl` | `DEEPL_AUTH_KEY` | `[Your Key]` | [DeepL](https://support.deepl.com/hc/en-us/articles/360020695820-API-Key-for-DeepL-s-API) 참조 |
225
+ | **DeepLX** | `deeplx` | `DEEPLX_ENDPOINT` | `https://api.deepl.com/translate` | [DeepLX](https://github.com/OwO-Network/DeepLX) 참조 |
226
+ | **Ollama** | `ollama` | `OLLAMA_HOST`, `OLLAMA_MODEL` | `http://127.0.0.1:11434`, `gemma2` | [Ollama](https://github.com/ollama/ollama) 참조 |
227
+ | **OpenAI** | `openai` | `OPENAI_BASE_URL`, `OPENAI_API_KEY`, `OPENAI_MODEL` | `https://api.openai.com/v1`, `[Your Key]`, `gpt-4o-mini` | [OpenAI](https://platform.openai.com/docs/overview) 참조 |
228
+ | **AzureOpenAI** | `azure-openai` | `AZURE_OPENAI_BASE_URL`, `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_MODEL` | `[Your Endpoint]`, `[Your Key]`, `gpt-4o-mini` | [Azure OpenAI](https://learn.microsoft.com/zh-cn/azure/ai-services/openai/chatgpt-quickstart?tabs=command-line%2Cjavascript-keyless%2Ctypescript-keyless%2Cpython&pivots=programming-language-python) 참조 |
229
+ | **Zhipu** | `zhipu` | `ZHIPU_API_KEY`, `ZHIPU_MODEL` | `[Your Key]`, `glm-4-flash` | [Zhipu](https://open.bigmodel.cn/dev/api/thirdparty-frame/openai-sdk) 참조 |
230
+ | **ModelScope** | `modelscope` | `MODELSCOPE_API_KEY`, `MODELSCOPE_MODEL` | `[Your Key]`, `Qwen/Qwen2.5-Coder-32B-Instruct` | [ModelScope](https://www.modelscope.cn/docs/model-service/API-Inference/intro) 참조 |
231
+ | **Silicon** | `silicon` | `SILICON_API_KEY`, `SILICON_MODEL` | `[Your Key]`, `Qwen/Qwen2.5-7B-Instruct` | [SiliconCloud](https://docs.siliconflow.cn/quickstart) 참조 |
232
+ | **Gemini** | `gemini` | `GEMINI_API_KEY`, `GEMINI_MODEL` | `[Your Key]`, `gemini-1.5-flash` | [Gemini](https://ai.google.dev/gemini-api/docs/openai) 참조 |
233
+ | **Azure** | `azure` | `AZURE_ENDPOINT`, `AZURE_API_KEY` | `https://api.translator.azure.cn`, `[Your Key]` | [Azure](https://docs.azure.cn/en-us/ai-services/translator/text-translation-overview) 참조 |
234
+ | **Tencent** | `tencent` | `TENCENTCLOUD_SECRET_ID`, `TENCENTCLOUD_SECRET_KEY` | `[Your ID]`, `[Your Key]` | [Tencent](https://www.tencentcloud.com/products/tmt?from_qcintl=122110104) 참조 |
235
+ | **Dify** | `dify` | `DIFY_API_URL`, `DIFY_API_KEY` | `[Your DIFY URL]`, `[Your Key]` | [Dify](https://github.com/langgenius/dify) 참조, Dify의 워크플로우 입력에서 lang_out, lang_in, text 세 변수를 정의해야 합니다. |
236
+ | **AnythingLLM** | `anythingllm` | `AnythingLLM_URL`, `AnythingLLM_APIKEY` | `[Your AnythingLLM URL]`, `[Your Key]` | [anything-llm](https://github.com/Mintplex-Labs/anything-llm) 참조 |
237
+ | **Argos Translate** | `argos` | | | [argos-translate](https://github.com/argosopentech/argos-translate) 참조 |
238
+ | **Grok** | `grok` | `GORK_API_KEY`, `GORK_MODEL` | `[Your GORK_API_KEY]`, `grok-2-1212` | [Grok](https://docs.x.ai/docs/overview) 참조 |
239
+ | **DeepSeek** | `deepseek` | `DEEPSEEK_API_KEY`, `DEEPSEEK_MODEL` | `[Your DEEPSEEK_API_KEY]`, `deepseek-chat` | [DeepSeek](https://www.deepseek.com/) 참조 |
240
+ | **OpenAI-Liked** | `openailiked` | `OPENAILIKED_BASE_URL`, `OPENAILIKED_API_KEY`, `OPENAILIKED_MODEL` | `url`, `[Your Key]`, `model name` | 없음 |
241
+
242
+ 위 표에 없는 OpenAI API와 호환되는 대형 언어 모델의 경우, 표의 OpenAI와 동일한 방식으로 환경 변수를 설정할 수 있습니다.
243
+
244
+ `-s service` 또는 `-s service:model`을 사��하여 번역 서비스를 지정합니다:
245
+
246
+ ```bash
247
+ pdf2zh example.pdf -s openai:gpt-4o-mini
248
+ ```
249
+
250
+ 또는 환경 변수로 모델을 지정합니다:
251
+
252
+ ```bash
253
+ set OPENAI_MODEL=gpt-4o-mini
254
+ pdf2zh example.pdf -s openai
255
+ ```
256
+
257
+ PowerShell 사용자의 경우:
258
+
259
+ ```shell
260
+ $env:OPENAI_MODEL = gpt-4o-mini
261
+ pdf2zh example.pdf -s openai
262
+ ```
263
+
264
+ <h3 id="exceptions">예외 지정</h3>
265
+
266
+ 정규식을 사용하여 보존해야 할 수식 폰트와 문자를 지정합니다:
267
+
268
+ ```bash
269
+ pdf2zh example.pdf -f "(CM[^RT].*|MS.*|.*Ital)" -c "(\(|\||\)|\+|=|\d|[\u0080-\ufaff])"
270
+ ```
271
+
272
+ 기본적으로 `Latex`, `Mono`, `Code`, `Italic`, `Symbol` 및 `Math` 폰트를 보존합니다:
273
+
274
+ ```bash
275
+ pdf2zh example.pdf -f "(CM[^R]|MS.M|XY|MT|BL|RM|EU|LA|RS|LINE|LCIRCLE|TeX-|rsfs|txsy|wasy|stmary|.*Mono|.*Code|.*Ital|.*Sym|.*Math)"
276
+ ```
277
+
278
+ <h3 id="threads">스레드 수 지정</h3>
279
+
280
+ `-t`를 사용하여 번역에 사용할 스레드 수를 지정합니다:
281
+
282
+ ```bash
283
+ pdf2zh example.pdf -t 1
284
+ ```
285
+
286
+ <h3 id="prompt">사용자 정의 프롬프트</h3>
287
+
288
+ `--prompt`를 사용하여 LLM에서 사용할 프롬프트를 지정합니다:
289
+
290
+ ```bash
291
+ pdf2zh example.pdf -pr prompt.txt
292
+ ```
293
+
294
+ `prompt.txt` 예시:
295
+
296
+ ```txt
297
+ [
298
+ {
299
+ "role": "system",
300
+ "content": "You are a professional,authentic machine translation engine.",
301
+ },
302
+ {
303
+ "role": "user",
304
+ "content": "Translate the following markdown source text to ${lang_out}. Keep the formula notation {{v*}} unchanged. Output translation directly without any additional text.\nSource Text: ${text}\nTranslated Text:",
305
+ },
306
+ ]
307
+ ```
308
+
309
+ 사용자 정의 프롬프트 파일에서는 다음 세 가지 변수를 사용할 수 있습니다:
310
+
311
+ | **변수** | **내용** |
312
+ | ---------- | ------------- |
313
+ | `lang_in` | 소스 언어 |
314
+ | `lang_out` | 대상 언어 |
315
+ | `text` | 번역할 텍스트 |
316
+
317
+ <h2 id="todo">API</h2>
318
+
319
+ ### Python
320
+
321
+ ```python
322
+ from pdf2zh import translate, translate_stream
323
+
324
+ params = {"lang_in": "en", "lang_out": "ko", "service": "google", "thread": 4}
325
+ file_mono, file_dual = translate(files=["example.pdf"], **params)[0]
326
+ with open("example.pdf", "rb") as f:
327
+ stream_mono, stream_dual = translate_stream(stream=f.read(), **params)
328
+ ```
329
+
330
+ ### HTTP
331
+
332
+ ```bash
333
+ pip install pdf2zh[backend]
334
+ pdf2zh --flask
335
+ pdf2zh --celery worker
336
+ ```
337
+
338
+ ```bash
339
+ curl http://localhost:11008/v1/translate -F "[email protected]" -F "data={\"lang_in\":\"en\",\"lang_out\":\"ko\",\"service\":\"google\",\"thread\":4}"
340
+ {"id":"d9894125-2f4e-45ea-9d93-1a9068d2045a"}
341
+
342
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
343
+ {"info":{"n":13,"total":506},"state":"PROGRESS"}
344
+
345
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
346
+ {"state":"SUCCESS"}
347
+
348
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/mono --output example-mono.pdf
349
+
350
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/dual --output example-dual.pdf
351
+
352
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a -X DELETE
353
+ ```
354
+
355
+ <h2 id="acknowledgement">감사의 말</h2>
356
+
357
+ - 문서 병합: [PyMuPDF](https://github.com/pymupdf/PyMuPDF)
358
+ - 문서 파싱: [Pdfminer.six](https://github.com/pdfminer/pdfminer.six)
359
+ - 문서 추출: [MinerU](https://github.com/opendatalab/MinerU)
360
+ - 문서 미리보기: [Gradio PDF](https://github.com/freddyaboulton/gradio-pdf)
361
+ - 멀티스레드 번역: [MathTranslate](https://github.com/SUSYUSTC/MathTranslate)
362
+ - 레이아웃 파싱: [DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO)
363
+ - 문서 표준: [PDF Explained](https://zxyle.github.io/PDF-Explained/), [PDF Cheat Sheets](https://pdfa.org/resource/pdf-cheat-sheets/)
364
+ - 다국어 폰트: [Go Noto Universal](https://github.com/satbyy/go-noto-universal)
365
+
366
+ <h2 id="contrib">기여자</h2>
367
+
368
+ <a href="https://github.com/Byaidu/PDFMathTranslate/graphs/contributors">
369
+ <img src="https://opencollective.com/PDFMathTranslate/contributors.svg?width=890&button=false" />
370
+ </a>
371
+
372
+ ![Alt](https://repobeats.axiom.co/api/embed/dfa7583da5332a11468d686fbd29b92320a6a869.svg "Repobeats analytics image")
373
+
374
+ <h2 id="star_hist">스타 히스토리</h2>
375
+
376
+ <a href="https://star-history.com/#Byaidu/PDFMathTranslate&Date">
377
+ <picture>
378
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date&theme=dark" />
379
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date" />
380
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date"/>
381
+ </picture>
382
+ </a>
docs/README_zh-CN.md ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ [English](../README.md) | 简体中文 | [繁體中文](README_zh-TW.md) | [日本語](README_ja-JP.md)
4
+
5
+ <img src="./images/banner.png" width="320px" alt="PDF2ZH"/>
6
+
7
+ <h2 id="title">PDFMathTranslate</h2>
8
+
9
+ <p>
10
+ <!-- PyPI -->
11
+ <a href="https://pypi.org/project/pdf2zh/">
12
+ <img src="https://img.shields.io/pypi/v/pdf2zh"/></a>
13
+ <a href="https://pepy.tech/projects/pdf2zh">
14
+ <img src="https://static.pepy.tech/badge/pdf2zh"></a>
15
+ <a href="https://hub.docker.com/repository/docker/byaidu/pdf2zh">
16
+ <img src="https://img.shields.io/docker/pulls/byaidu/pdf2zh"></a>
17
+ <!-- License -->
18
+ <a href="./LICENSE">
19
+ <img src="https://img.shields.io/github/license/Byaidu/PDFMathTranslate"/></a>
20
+ <a href="https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker">
21
+ <img src="https://img.shields.io/badge/%F0%9F%A4%97-Online%20Demo-FF9E0D"/></a>
22
+ <a href="https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate">
23
+ <img src="https://img.shields.io/badge/ModelScope-Demo-blue"></a>
24
+ <a href="https://github.com/Byaidu/PDFMathTranslate/pulls">
25
+ <img src="https://img.shields.io/badge/contributions-welcome-green"/></a>
26
+ <a href="https://gitcode.com/Byaidu/PDFMathTranslate/overview">
27
+ <img src="https://gitcode.com/Byaidu/PDFMathTranslate/star/badge.svg"></a>
28
+ <a href="https://t.me/+Z9_SgnxmsmA5NzBl">
29
+ <img src="https://img.shields.io/badge/Telegram-2CA5E0?style=flat-squeare&logo=telegram&logoColor=white"/></a>
30
+ </p>
31
+
32
+ <a href="https://trendshift.io/repositories/12424" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12424" alt="Byaidu%2FPDFMathTranslate | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
33
+
34
+ </div>
35
+
36
+ 科学 PDF 文档翻译及双语对照工具
37
+
38
+ - 📊 保留公式、图表、目录和注释 *([预览效果](#preview))*
39
+ - 🌐 支持 [多种语言](./ADVANCED.md#language) 和 [诸多翻译服务](./ADVANCED.md#services)
40
+ - 🤖 提供 [命令行工具](#usage),[图形交互界面](#gui),以及 [容器化部署](#docker)
41
+
42
+ 欢迎在 [GitHub Issues](https://github.com/Byaidu/PDFMathTranslate/issues) 或 [Telegram 用户群](https://t.me/+Z9_SgnxmsmA5NzBl)
43
+
44
+ 有关如何贡献的详细信息,请查阅 [贡献指南](https://github.com/Byaidu/PDFMathTranslate/wiki/Contribution-Guide---%E8%B4%A1%E7%8C%AE%E6%8C%87%E5%8D%97)
45
+
46
+ <h2 id="updates">更新</h2>
47
+
48
+ - [2025 年 2 月 22 日] 更好的发布 CI 和精心打包的 windows-amd64 exe (由 [@awwaawwa](https://github.com/awwaawwa) 提供)
49
+ - [2024 年 12 月 24 日] 翻译器现在支持在 [Xinference](https://github.com/xorbitsai/inference) 上使用本地模型 _(由 [@imClumsyPanda](https://github.com/imClumsyPanda) 提供)_
50
+ - [2024 年 12 月 19 日] 现在支持非 PDF/A 文档,使用 `-cp` _(由 [@reycn](https://github.com/reycn) 提供)_
51
+ - [2024 年 12 月 13 日] 额外支持后端 _(由 [@YadominJinta](https://github.com/YadominJinta) 提供)_
52
+ - [2024 年 12 月 10 日] 翻译器现在支持 Azure 上的 OpenAI 模型 _(由 [@yidasanqian](https://github.com/yidasanqian) 提供)_
53
+
54
+ <h2 id="preview">预览</h2>
55
+ <div align="center">
56
+ <img src="./images/preview.gif" width="80%"/>
57
+ </div>
58
+
59
+ <h2 id="demo">在线演示 🌟</h2>
60
+
61
+ <h2 id="demo">在线服务 🌟</h2>
62
+
63
+ 您可以通过以下演示尝试我们的应用程序:
64
+
65
+ - [公共免费服务](https://pdf2zh.com/) 在线使用,无需安装 _(推荐)_。
66
+ - [沉浸式翻译 - BabelDOC](https://app.immersivetranslate.com/babel-doc/) 每月免费 1000 页 _(推荐)_
67
+ - [在 HuggingFace 上托管的演示](https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker)
68
+ - [在 ModelScope 上托管的演示](https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate) 无需安装。
69
+
70
+ 请注意演示的计算资源有限,请避免滥用它们。
71
+ <h2 id="install">安装和使用</h2>
72
+
73
+ ### 方法
74
+
75
+ 针对不同的使用案例,我们提供不同的方法来使用我们的程序:
76
+
77
+ <details open>
78
+ <summary>1. UV 安装</summary>
79
+
80
+ 1. 安装 Python (3.10 <= 版本 <= 3.12)
81
+ 2. 安装我们的包:
82
+
83
+ ```bash
84
+ pip install uv
85
+ uv tool install --python 3.12 pdf2zh
86
+ ```
87
+
88
+ 3. 执行翻译,文件生成在 [当前工作目录](https://chatgpt.com/share/6745ed36-9acc-800e-8a90-59204bd13444):
89
+
90
+ ```bash
91
+ pdf2zh document.pdf
92
+ ```
93
+
94
+ </details>
95
+
96
+ <details>
97
+ <summary>2. Windows exe</summary>
98
+
99
+ 1. 从 [发布页面](https://github.com/Byaidu/PDFMathTranslate/releases) 下载 pdf2zh-version-win64.zip
100
+
101
+ 2. 解压缩并双击 `pdf2zh.exe` 运行。
102
+
103
+ </details>
104
+
105
+ <details>
106
+ <summary id="gui">3. 图形用户界面</summary>
107
+ 1. 安装 Python (3.10 <= 版本 <= 3.12)
108
+ 2. 安装我们的包:
109
+
110
+ ```bash
111
+ pip install pdf2zh
112
+ ```
113
+
114
+ 3. 在浏览器中开始使用:
115
+
116
+ ```bash
117
+ pdf2zh -i
118
+ ```
119
+
120
+ 4. 如果您的浏览器没有自动启动,请访问
121
+
122
+ ```bash
123
+ http://localhost:7860/
124
+ ```
125
+
126
+ <img src="./images/gui.gif" width="500"/>
127
+
128
+ 有关更多详细信息,请参阅 [GUI 文档](./README_GUI.md)���
129
+
130
+ </details>
131
+
132
+ <details>
133
+ <summary id="docker">4. Docker</summary>
134
+
135
+ 1. 拉取并运行:
136
+
137
+ ```bash
138
+ docker pull byaidu/pdf2zh
139
+ docker run -d -p 7860:7860 byaidu/pdf2zh
140
+ ```
141
+
142
+ 2. 在浏览器中打开:
143
+
144
+ ```
145
+ http://localhost:7860/
146
+ ```
147
+
148
+ 对于云服务上的 docker 部署:
149
+
150
+ <div>
151
+ <a href="https://www.heroku.com/deploy?template=https://github.com/Byaidu/PDFMathTranslate">
152
+ <img src="https://www.herokucdn.com/deploy/button.svg" alt="部署" height="26"></a>
153
+ <a href="https://render.com/deploy">
154
+ <img src="https://render.com/images/deploy-to-render-button.svg" alt="部署到 Koyeb" height="26"></a>
155
+ <a href="https://zeabur.com/templates/5FQIGX?referralCode=reycn">
156
+ <img src="https://zeabur.com/button.svg" alt="在 Zeabur 上部署" height="26"></a>
157
+ <a href="https://template.sealos.io/deploy?templateName=pdf2zh">
158
+ <img src="https://sealos.io/Deploy-on-Sealos.svg" alt="在 Sealos 上部署" height="26"></a>
159
+ <a href="https://app.koyeb.com/deploy?type=git&builder=buildpack&repository=github.com/Byaidu/PDFMathTranslate&branch=main&name=pdf-math-translate">
160
+ <img src="https://www.koyeb.com/static/images/deploy/button.svg" alt="部署到 Koyeb" height="26"></a>
161
+ </div>
162
+
163
+ </details>
164
+
165
+ <details>
166
+ <summary>5. Zotero 插件</summary>
167
+
168
+ 有关更多细节,请参见 [Zotero PDF2zh](https://github.com/guaguastandup/zotero-pdf2zh)。
169
+
170
+ </details>
171
+
172
+ <details>
173
+ <summary>6. 命令行</summary>
174
+
175
+ 1. 已安装 Python(3.10 <= 版本 <= 3.12)
176
+ 2. 安装我们的包:
177
+
178
+ ```bash
179
+ pip install pdf2zh
180
+ ```
181
+
182
+ 3. 执行翻译,文件生成在 [当前工作目录](https://chatgpt.com/share/6745ed36-9acc-800e-8a90-59204bd13444):
183
+
184
+ ```bash
185
+ pdf2zh document.pdf
186
+ ```
187
+
188
+ </details>
189
+
190
+ > [!TIP]
191
+ >
192
+ > - 如果你使用 Windows 并在下载后无法打开文件,请安装 [vc_redist.x64.exe](https://aka.ms/vs/17/release/vc_redist.x64.exe) 并重试。
193
+ >
194
+ > - 如果你无法访问 Docker Hub,请尝试在 [GitHub 容器注册中心](https://github.com/Byaidu/PDFMathTranslate/pkgs/container/pdfmathtranslate) 上使用该镜像。
195
+ > ```bash
196
+ > docker pull ghcr.io/byaidu/pdfmathtranslate
197
+ > docker run -d -p 7860:7860 ghcr.io/byaidu/pdfmathtranslate
198
+ > ```
199
+
200
+ ### 无法安装?
201
+
202
+ 当前程序在工作前需要一个 AI 模型 (`wybxc/DocLayout-YOLO-DocStructBench-onnx`),一些用户由于网络问题无法下载。如果你在下载此模型时遇到问题,我们提供以下环境变量的解决方法:
203
+
204
+ ```shell
205
+ set HF_ENDPOINT=https://hf-mirror.com
206
+ ```
207
+
208
+ 对于 PowerShell 用户:
209
+
210
+ ```shell
211
+ $env:HF_ENDPOINT = https://hf-mirror.com
212
+ ```
213
+
214
+ 如果此解决方案对您无效或您遇到其他问题,请参阅 [常见问题解答](https://github.com/Byaidu/PDFMathTranslate/wiki#-faq--%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98)。
215
+
216
+
217
+ <h2 id="usage">高级选项</h2>
218
+
219
+ 在命令行中执行翻译命令,在当前工作目录下生成译文文档 `example-mono.pdf` 和双语对照文档 `example-dual.pdf`,默认使用 Google 翻译服务,更多支持的服务在[这里](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#services))。
220
+
221
+ <img src="./images/cmd.explained.png" width="580px" alt="cmd"/>
222
+
223
+ 在下表中,我们列出了所有高级选项供参考:
224
+
225
+ | 选项 | 功能 | 示例 |
226
+ | ------------ | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
227
+ | files | 本地文件 | `pdf2zh ~/local.pdf` |
228
+ | links | 在线文件 | `pdf2zh http://arxiv.org/paper.pdf` |
229
+ | `-i` | [进入 GUI](#gui) | `pdf2zh -i` |
230
+ | `-p` | [部分文档翻译](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#partial) | `pdf2zh example.pdf -p 1` |
231
+ | `-li` | [源语言](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#languages) | `pdf2zh example.pdf -li en` |
232
+ | `-lo` | [目标语言](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#languages) | `pdf2zh example.pdf -lo zh` |
233
+ | `-s` | [翻译服务](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#services) | `pdf2zh example.pdf -s deepl` |
234
+ | `-t` | [多线程](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#threads) | `pdf2zh example.pdf -t 1` |
235
+ | `-o` | 输出目录 | `pdf2zh example.pdf -o output` |
236
+ | `-f`, `-c` | [异常](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#exceptions) | `pdf2zh example.pdf -f "(MS.*)"` |
237
+ | `-cp` | 兼容模式 | `pdf2zh example.pdf --compatible` |
238
+ | `--share` | 公开链接 | `pdf2zh -i --share` |
239
+ | `--authorized` | [授权](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#auth) | `pdf2zh -i --authorized users.txt [auth.html]` |
240
+ | `--prompt` | [自定义提示](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#prompt) | `pdf2zh --prompt [prompt.txt]` |
241
+ | `--onnx` | [使用自定义 DocLayout-YOLO ONNX 模型] | `pdf2zh --onnx [onnx/model/path]` |
242
+ | `--serverport` | [使用自定义 WebUI 端口] | `pdf2zh --serverport 7860` |
243
+ | `--dir` | [批量翻译] | `pdf2zh --dir /path/to/translate/` |
244
+ | `--config` | [配置文件](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.md#cofig) | `pdf2zh --config /path/to/config/config.json` |
245
+ | `--serverport` | [自定义 gradio 服务器端口] | `pdf2zh --serverport 7860` |
246
+ | `--babeldoc`| 使用实验性后端 [BabelDOC](https://funstory-ai.github.io/BabelDOC/) 翻译 |`pdf2zh --babeldoc` -s openai example.pdf|
247
+
248
+ 有关详细说明,请参阅我们的文档 [高级用法](./ADVANCED.md),以获取每个选项的完整列表。
249
+
250
+ <h2 id="downstream">二次开发 (API)</h2>
251
+
252
+ 当前的 pdf2zh API 暂时已弃用。API 将在 [pdf2zh 2.0](https://github.com/Byaidu/PDFMathTranslate/issues/586)发布后重新提供。对于需要程序化访问的用户,请使用[BabelDOC](https://github.com/funstory-ai/BabelDOC)的 `babeldoc.high_level.async_translate` 函数。
253
+
254
+ API 暂时弃用意味着:相关代码暂时不会被移除,但不会提供技术支持,也不会修复 bug。
255
+
256
+ <!-- 对于下游应用程序,请参阅我们的文档 [API 详细信息](./APIS.md),以获取更多信息:
257
+ - [Python API](./APIS.md#api-python),如何在其他 Python 程序中使用该程序
258
+ - [HTTP API](./APIS.md#api-http),如何与已安装该程序的服务器进行通信 -->
259
+
260
+ <h2 id="todo">待办事项</h2>
261
+
262
+ - [ ] 使用基于 DocLayNet 的模型解析布局,[PaddleX](https://github.com/PaddlePaddle/PaddleX/blob/17cc27ac3842e7880ca4aad92358d3ef8555429a/paddlex/repo_apis/PaddleDetection_api/object_det/official_categories.py#L81),[PaperMage](https://github.com/allenai/papermage/blob/9cd4bb48cbedab45d0f7a455711438f1632abebe/README.md?plain=1#L102),[SAM2](https://github.com/facebookresearch/sam2)
263
+
264
+ - [ ] 修复页面旋转、目录、列表格式
265
+
266
+ - [ ] 修复旧论文中的像素公式
267
+
268
+ - [ ] 异步重试,除了 KeyboardInterrupt
269
+
270
+ - [ ] 针对西方语言的 Knuth–Plass 算法
271
+
272
+ - [ ] 支持非 PDF/A 文件
273
+
274
+ - [ ] [Zotero](https://github.com/zotero/zotero) 和 [Obsidian](https://github.com/obsidianmd/obsidian-releases) 的插件
275
+
276
+ <h2 id="acknowledgement">致谢</h2>
277
+
278
+ - [Immersive Translation](https://immersivetranslate.com) 为此项目的活跃贡献者提供每月的专业会员兑换码,详细信息请查看:[CONTRIBUTOR_REWARD.md](https://github.com/funstory-ai/BabelDOC/blob/main/docs/CONTRIBUTOR_REWARD.md)
279
+
280
+ - 文档合并:[PyMuPDF](https://github.com/pymupdf/PyMuPDF)
281
+
282
+ - 文档解析:[Pdfminer.six](https://github.com/pdfminer/pdfminer.six)
283
+
284
+ - 文档提取:[MinerU](https://github.com/opendatalab/MinerU)
285
+
286
+ - 文档预览:[Gradio PDF](https://github.com/freddyaboulton/gradio-pdf)
287
+
288
+ - 多线程翻译:[MathTranslate](https://github.com/SUSYUSTC/MathTranslate)
289
+
290
+ - 布局解析:[DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO)
291
+
292
+ - 文档标准:[PDF Explained](https://zxyle.github.io/PDF-Explained/),[PDF Cheat Sheets](https://pdfa.org/resource/pdf-cheat-sheets/)
293
+
294
+ - 多语言字体:[Go Noto Universal](https://github.com/satbyy/go-noto-universal)
295
+
296
+ <h2 id="contrib">贡献者</h2>
297
+
298
+ <a href="https://github.com/Byaidu/PDFMathTranslate/graphs/contributors">
299
+ <img src="https://opencollective.com/PDFMathTranslate/contributors.svg?width=890&button=false" />
300
+ </a>
301
+
302
+ ![Alt](https://repobeats.axiom.co/api/embed/dfa7583da5332a11468d686fbd29b92320a6a869.svg "Repobeats analytics image")
303
+
304
+ <h2 id="star_hist">星标历史</h2>
305
+
306
+ <a href="https://star-history.com/#Byaidu/PDFMathTranslate&Date">
307
+ <picture>
308
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date&theme=dark" />
309
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date" />
310
+ <img alt="星标历史图表" src="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date"/>
311
+ </picture>
312
+ </a>
docs/README_zh-TW.md ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ [English](../README.md) | [简体中文](README_zh-CN.md) | 繁體中文 | [日本語](README_ja-JP.md)
4
+
5
+ <img src="./images/banner.png" width="320px" alt="PDF2ZH"/>
6
+
7
+ <h2 id="title">PDFMathTranslate</h2>
8
+
9
+ <p>
10
+ <!-- PyPI -->
11
+ <a href="https://pypi.org/project/pdf2zh/">
12
+ <img src="https://img.shields.io/pypi/v/pdf2zh"/></a>
13
+ <a href="https://pepy.tech/projects/pdf2zh">
14
+ <img src="https://static.pepy.tech/badge/pdf2zh"></a>
15
+ <a href="https://hub.docker.com/repository/docker/byaidu/pdf2zh">
16
+ <img src="https://img.shields.io/docker/pulls/byaidu/pdf2zh"></a>
17
+ <!-- License -->
18
+ <a href="./LICENSE">
19
+ <img src="https://img.shields.io/github/license/Byaidu/PDFMathTranslate"/></a>
20
+ <a href="https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker">
21
+ <img src="https://img.shields.io/badge/%F0%9F%A4%97-Online%20Demo-FF9E0D"/></a>
22
+ <a href="https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate">
23
+ <img src="https://img.shields.io/badge/ModelScope-Demo-blue"></a>
24
+ <a href="https://github.com/Byaidu/PDFMathTranslate/pulls">
25
+ <img src="https://img.shields.io/badge/contributions-welcome-green"/></a>
26
+ <a href="https://gitcode.com/Byaidu/PDFMathTranslate/overview">
27
+ <img src="https://gitcode.com/Byaidu/PDFMathTranslate/star/badge.svg"></a>
28
+ <a href="https://t.me/+Z9_SgnxmsmA5NzBl">
29
+ <img src="https://img.shields.io/badge/Telegram-2CA5E0?style=flat-squeare&logo=telegram&logoColor=white"/></a>
30
+ </p>
31
+
32
+ <a href="https://trendshift.io/repositories/12424" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12424" alt="Byaidu%2FPDFMathTranslate | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
33
+
34
+ </div>
35
+
36
+ 科學 PDF 文件翻譯及雙語對照工具
37
+
38
+ - 📊 保留公式、圖表、目錄和註釋 *([預覽效果](#preview))*
39
+ - 🌐 支援 [多種語言](#language) 和 [諸多翻譯服務](#services)
40
+ - 🤖 提供 [命令列工具](#usage)、[圖形使用者介面](#gui),以及 [容器化部署](#docker)
41
+
42
+ 歡迎在 [GitHub Issues](https://github.com/Byaidu/PDFMathTranslate/issues) 或 [Telegram 使用者群](https://t.me/+Z9_SgnxmsmA5NzBl)(https://qm.qq.com/q/DixZCxQej0) 中提出回饋
43
+
44
+ 如需瞭解如何貢獻的詳細資訊,請查閱 [貢獻指南](https://github.com/Byaidu/PDFMathTranslate/wiki/Contribution-Guide---%E8%B4%A1%E7%8C%AE%E6%8C%87%E5%8D%97)
45
+
46
+ <h2 id="updates">近期更新</h2>
47
+
48
+ - [Dec. 24 2024] 翻譯功能支援接入由 [Xinference](https://github.com/xorbitsai/inference) 執行的本機 LLM _(by [@imClumsyPanda](https://github.com/imClumsyPanda))_
49
+ - [Nov. 26 2024] CLI 現在已支援(多個)線上 PDF 檔 *(by [@reycn](https://github.com/reycn))*
50
+ - [Nov. 24 2024] 為了降低依賴大小,提供 [ONNX](https://github.com/onnx/onnx) 支援 *(by [@Wybxc](https://github.com/Wybxc))*
51
+ - [Nov. 23 2024] 🌟 [免費公共服務](#demo) 上線! *(by [@Byaidu](https://github.com/Byaidu))*
52
+ - [Nov. 23 2024] 新增防止網頁爬蟲的防火牆 *(by [@Byaidu](https://github.com/Byaidu))*
53
+ - [Nov. 22 2024] 圖形使用者介面現已支援義大利語並進行了一些更新 *(by [@Byaidu](https://github.com/Byaidu), [@reycn](https://github.com/reycn))*
54
+ - [Nov. 22 2024] 現在你可以將自己部署的服務分享給朋友 *(by [@Zxis233](https://github.com/Zxis233))*
55
+ - [Nov. 22 2024] 支援騰訊翻譯 *(by [@hellofinch](https://github.com/hellofinch))*
56
+ - [Nov. 21 2024] 圖形使用者介面現在支援下載雙語文件 *(by [@reycn](https://github.com/reycn))*
57
+ - [Nov. 20 2024] 🌟 提供了 [線上示範](#demo)! *(by [@reycn](https://github.com/reycn))*
58
+
59
+ <h2 id="preview">效果預覽</h2>
60
+
61
+ <div align="center">
62
+ <img src="./images/preview.gif" width="80%"/>
63
+ </div>
64
+
65
+ <h2 id="demo">線上示範 🌟</h2>
66
+
67
+ ### 免費服務 (<https://pdf2zh.com/>)
68
+
69
+ 你可以立即嘗試 [免費公共服務](https://pdf2zh.com/) 而無需安裝
70
+
71
+ ### 線上示範
72
+
73
+ 你可以直接在 [HuggingFace 上的線上示範](https://huggingface.co/spaces/reycn/PDFMathTranslate-Docker)和[魔搭的線上示範](https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate)進行嘗試,無需安裝。
74
+ 請注意,示範使用的運算資源有限,請勿濫用。
75
+
76
+ <h2 id="install">安裝與使用</h2>
77
+
78
+ 我們提供了四種使用此專案的方法:[命令列工具](#cmd)、[便攜式安裝](#portable)、[圖形使用者介面](#gui) 與 [容器化部署](#docker)。
79
+
80
+ pdf2zh 在執行時需要額外下載模型(`wybxc/DocLayout-YOLO-DocStructBench-onnx`),該模型也可在魔搭(ModelScope)上取得。如果在啟動時下載該模型時遇到問題,請使用如下環境變數:
81
+ ```shell
82
+ set HF_ENDPOINT=https://hf-mirror.com
83
+ ```
84
+
85
+ <h3 id="cmd">方法一、命令列工具</h3>
86
+
87
+ 1. 確保已安裝 Python 版本大於 3.10 且小於 3.12
88
+ 2. 安裝此程式:
89
+
90
+ ```bash
91
+ pip install pdf2zh
92
+ ```
93
+
94
+ 3. 執行翻譯,生成檔案位於 [目前工作目錄](https://chatgpt.com/share/6745ed36-9acc-800e-8a90-59204bd13444):
95
+
96
+ ```bash
97
+ pdf2zh document.pdf
98
+ ```
99
+
100
+ <h3 id="portable">方法二、便攜式安裝</h3>
101
+
102
+ 無需預先安裝 Python 環境
103
+
104
+ 下載 [setup.bat](https://raw.githubusercontent.com/Byaidu/PDFMathTranslate/refs/heads/main/script/setup.bat) 並直接雙擊執行
105
+
106
+ <h3 id="gui">方法三、圖形使用者介面</h3>
107
+
108
+ 1. 確保已安裝 Python 版本大於 3.10 且小於 3.12
109
+ 2. 安裝此程式:
110
+
111
+ ```bash
112
+ pip install pdf2zh
113
+ ```
114
+
115
+ 3. 在瀏覽器中啟動使用:
116
+
117
+ ```bash
118
+ pdf2zh -i
119
+ ```
120
+
121
+ 4. 如果您的瀏覽器沒有自動開啟並跳轉,請手動在瀏覽器開啟:
122
+
123
+ ```bash
124
+ http://localhost:7860/
125
+ ```
126
+
127
+ <img src="./images/gui.gif" width="500"/>
128
+
129
+ 查看 [documentation for GUI](/README_GUI.md) 以獲取詳細說明
130
+
131
+ <h3 id="docker">方法四、容器化部署</h3>
132
+
133
+ 1. 拉取 Docker 映像檔並執行:
134
+
135
+ ```bash
136
+ docker pull byaidu/pdf2zh
137
+ docker run -d -p 7860:7860 byaidu/pdf2zh
138
+ ```
139
+
140
+ 2. 透過瀏覽器開啟:
141
+
142
+ ```
143
+ http://localhost:7860/
144
+ ```
145
+
146
+ 用於在雲服務上部署容器映像檔:
147
+
148
+ <div>
149
+ <a href="https://www.heroku.com/deploy?template=https://github.com/Byaidu/PDFMathTranslate">
150
+ <img src="https://www.herokucdn.com/deploy/button.svg" alt="Deploy" height="26"></a>
151
+ <a href="https://render.com/deploy">
152
+ <img src="https://render.com/images/deploy-to-render-button.svg" alt="Deploy to Koyeb" height="26"></a>
153
+ <a href="https://zeabur.com/templates/5FQIGX?referralCode=reycn">
154
+ <img src="https://zeabur.com/button.svg" alt="Deploy on Zeabur" height="26"></a>
155
+ <a href="https://app.koyeb.com/deploy?type=git&builder=buildpack&repository=github.com/Byaidu/PDFMathTranslate&branch=main&name=pdf-math-translate">
156
+ <img src="https://www.koyeb.com/static/images/deploy/button.svg" alt="Deploy to Koyeb" height="26"></a>
157
+ </div>
158
+
159
+ <h2 id="usage">高級選項</h2>
160
+
161
+ 在命令列中執行翻譯指令,並在目前工作目錄下生成譯文檔案 `example-mono.pdf` 和雙語對照檔案 `example-dual.pdf`。預設使用 Google 翻譯服務。
162
+
163
+ <img src="./images/cmd.explained.png" width="580px" alt="cmd"/>
164
+
165
+ 以下表格列出了所有高級選項,供參考:
166
+
167
+ | Option | 功能 | 範例 |
168
+ | -------- | ------- |------- |
169
+ | files | 本機檔案 | `pdf2zh ~/local.pdf` |
170
+ | links | 線上檔案 | `pdf2zh http://arxiv.org/paper.pdf` |
171
+ | `-i` | [進入圖形介面](#gui) | `pdf2zh -i` |
172
+ | `-p` | [僅翻譯部分文件](#partial) | `pdf2zh example.pdf -p 1` |
173
+ | `-li` | [原文語言](#language) | `pdf2zh example.pdf -li en` |
174
+ | `-lo` | [目標語言](#language) | `pdf2zh example.pdf -lo zh` |
175
+ | `-s` | [指定翻譯服務](#services) | `pdf2zh example.pdf -s deepl` |
176
+ | `-t` | [多執行緒](#threads) | `pdf2zh example.pdf -t 1` |
177
+ | `-o` | 輸出目錄 | `pdf2zh example.pdf -o output` |
178
+ | `-f`, `-c` | [例外規則](#exceptions) | `pdf2zh example.pdf -f "(MS.*)"` |
179
+ | `--share` | [獲取 gradio 公開連結] | `pdf2zh -i --share` |
180
+ | `--authorized` | [[添加網頁認證及自訂認證頁面](https://github.com/Byaidu/PDFMathTranslate/blob/main/docs/ADVANCED.)] | `pdf2zh -i --authorized users.txt [auth.html]` |
181
+ | `--prompt` | [使用自訂的大模型 Prompt] | `pdf2zh --prompt [prompt.txt]` |
182
+ | `--onnx` | [使用自訂的 DocLayout-YOLO ONNX 模型] | `pdf2zh --onnx [onnx/model/path]` |
183
+ | `--serverport` | [自訂 WebUI 埠號] | `pdf2zh --serverport 7860` |
184
+ | `--dir` | [資料夾翻譯] | `pdf2zh --dir /path/to/translate/` |
185
+
186
+ <h3 id="partial">全文或部分文件翻譯</h3>
187
+
188
+ - **全文翻譯**
189
+
190
+ ```bash
191
+ pdf2zh example.pdf
192
+ ```
193
+
194
+ - **部分翻譯**
195
+
196
+ ```bash
197
+ pdf2zh example.pdf -p 1-3,5
198
+ ```
199
+
200
+ <h3 id="language">指定原文語言與目標語言</h3>
201
+
202
+ 可參考 [Google 語言代碼](https://developers.google.com/admin-sdk/directory/v1/languages)、[DeepL 語言代碼](https://developers.deepl.com/docs/resources/supported-languages)
203
+
204
+ ```bash
205
+ pdf2zh example.pdf -li en -lo ja
206
+ ```
207
+
208
+ <h3 id="services">使用不同的翻譯服務</h3>
209
+
210
+ 下表列出了每個翻譯服務所需的 [環境變數](https://chatgpt.com/share/6734a83d-9d48-800e-8a46-f57ca6e8bcb4)。在使用前,請先確保已設定好對應的變數。
211
+
212
+ |**Translator**|**Service**|**Environment Variables**|**Default Values**|**Notes**|
213
+ |-|-|-|-|-|
214
+ |**Google (Default)**|`google`|無|N/A|無|
215
+ |**Bing**|`bing`|無|N/A|無|
216
+ |**DeepL**|`deepl`|`DEEPL_AUTH_KEY`|`[Your Key]`|參閱 [DeepL](https://support.deepl.com/hc/en-us/articles/360020695820-API-Key-for-DeepL-s-API)|
217
+ |**DeepLX**|`deeplx`|`DEEPLX_ENDPOINT`|`https://api.deepl.com/translate`|參閱 [DeepLX](https://github.com/OwO-Network/DeepLX)|
218
+ |**Ollama**|`ollama`|`OLLAMA_HOST`, `OLLAMA_MODEL`|`http://127.0.0.1:11434`, `gemma2`|參閱 [Ollama](https://github.com/ollama/ollama)|
219
+ |**OpenAI**|`openai`|`OPENAI_BASE_URL`, `OPENAI_API_KEY`, `OPENAI_MODEL`|`https://api.openai.com/v1`, `[Your Key]`, `gpt-4o-mini`|參閱 [OpenAI](https://platform.openai.com/docs/overview)|
220
+ |**AzureOpenAI**|`azure-openai`|`AZURE_OPENAI_BASE_URL`, `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_MODEL`|`[Your Endpoint]`, `[Your Key]`, `gpt-4o-mini`|參閱 [Azure OpenAI](https://learn.microsoft.com/zh-cn/azure/ai-services/openai/chatgpt-quickstart?tabs=command-line%2Cjavascript-keyless%2Ctypescript-keyless%2Cpython&pivots=programming-language-python)|
221
+ |**Zhipu**|`zhipu`|`ZHIPU_API_KEY`, `ZHIPU_MODEL`|`[Your Key]`, `glm-4-flash`|參閱 [Zhipu](https://open.bigmodel.cn/dev/api/thirdparty-frame/openai-sdk)|
222
+ | **ModelScope** | `modelscope` |`MODELSCOPE_API_KEY`, `MODELSCOPE_MODEL`|`[Your Key]`, `Qwen/Qwen2.5-Coder-32B-Instruct`| 參閱 [ModelScope](https://www.modelscope.cn/docs/model-service/API-Inference/intro)|
223
+ |**Silicon**|`silicon`|`SILICON_API_KEY`, `SILICON_MODEL`|`[Your Key]`, `Qwen/Qwen2.5-7B-Instruct`|參閱 [SiliconCloud](https://docs.siliconflow.cn/quickstart)|
224
+ |**Gemini**|`gemini`|`GEMINI_API_KEY`, `GEMINI_MODEL`|`[Your Key]`, `gemini-1.5-flash`|參閱 [Gemini](https://ai.google.dev/gemini-api/docs/openai)|
225
+ |**Azure**|`azure`|`AZURE_ENDPOINT`, `AZURE_API_KEY`|`https://api.translator.azure.cn`, `[Your Key]`|參閱 [Azure](https://docs.azure.cn/en-us/ai-services/translator/text-translation-overview)|
226
+ |**Tencent**|`tencent`|`TENCENTCLOUD_SECRET_ID`, `TENCENTCLOUD_SECRET_KEY`|`[Your ID]`, `[Your Key]`|參閱 [Tencent](https://www.tencentcloud.com/products/tmt?from_qcintl=122110104)|
227
+ |**Dify**|`dify`|`DIFY_API_URL`, `DIFY_API_KEY`|`[Your DIFY URL]`, `[Your Key]`|參閱 [Dify](https://github.com/langgenius/dify),需要在 Dify 的工作流程輸入中定義三個變數:lang_out、lang_in、text。|
228
+ |**AnythingLLM**|`anythingllm`|`AnythingLLM_URL`, `AnythingLLM_APIKEY`|`[Your AnythingLLM URL]`, `[Your Key]`|參閱 [anything-llm](https://github.com/Mintplex-Labs/anything-llm)|
229
+ |**Argos Translate**|`argos`| | |參閱 [argos-translate](https://github.com/argosopentech/argos-translate)|
230
+ |**Grok**|`grok`| `GORK_API_KEY`, `GORK_MODEL` | `[Your GORK_API_KEY]`, `grok-2-1212` |參閱 [Grok](https://docs.x.ai/docs/overview)|
231
+ |**DeepSeek**|`deepseek`| `DEEPSEEK_API_KEY`, `DEEPSEEK_MODEL` | `[Your DEEPSEEK_API_KEY]`, `deepseek-chat` |參閱 [DeepSeek](https://www.deepseek.com/)|
232
+ |**OpenAI-Liked**|`openailiked`| `OPENAILIKED_BASE_URL`, `OPENAILIKED_API_KEY`, `OPENAILIKED_MODEL` | `url`, `[Your Key]`, `model name` | 無 |
233
+
234
+ 對於不在上述表格中,但兼容 OpenAI API 的大語言模型,可以使用與 OpenAI 相同的方式設定環境變數。
235
+
236
+ 使用 `-s service` 或 `-s service:model` 指定翻譯服務:
237
+
238
+ ```bash
239
+ pdf2zh example.pdf -s openai:gpt-4o-mini
240
+ ```
241
+
242
+ 或使用環境變數指定模型:
243
+
244
+ ```bash
245
+ set OPENAI_MODEL=gpt-4o-mini
246
+ pdf2zh example.pdf -s openai
247
+ ```
248
+
249
+ <h3 id="exceptions">指定例外規則</h3>
250
+
251
+ 使用正則表達式指定需要保留的公式字體與字元:
252
+
253
+ ```bash
254
+ pdf2zh example.pdf -f "(CM[^RT].*|MS.*|.*Ital)" -c "(\(|\||\)|\+|=|\d|[\u0080-\ufaff])"
255
+ ```
256
+
257
+ 預設保留 `Latex`, `Mono`, `Code`, `Italic`, `Symbol` 以及 `Math` 字體:
258
+
259
+ ```bash
260
+ pdf2zh example.pdf -f "(CM[^R]|MS.M|XY|MT|BL|RM|EU|LA|RS|LINE|LCIRCLE|TeX-|rsfs|txsy|wasy|stmary|.*Mono|.*Code|.*Ital|.*Sym|.*Math)"
261
+ ```
262
+
263
+ <h3 id="threads">指定執行緒數量</h3>
264
+
265
+ 使用 `-t` 參數指定翻譯使用的執行緒數量:
266
+
267
+ ```bash
268
+ pdf2zh example.pdf -t 1
269
+ ```
270
+
271
+ <h3 id="prompt">自訂大模型 Prompt</h3>
272
+
273
+ 使用 `--prompt` 指定在使用大模型翻譯時所採用的 Prompt 檔案。
274
+
275
+ ```bash
276
+ pdf2zh example.pdf -pr prompt.txt
277
+ ```
278
+
279
+ 範例 `prompt.txt` 檔案內容:
280
+
281
+ ```
282
+ [
283
+ {
284
+ "role": "system",
285
+ "content": "You are a professional,authentic machine translation engine.",
286
+ },
287
+ {
288
+ "role": "user",
289
+ "content": "Translate the following markdown source text to ${lang_out}. Keep the formula notation {{v*}} unchanged. Output translation directly without any additional text.\nSource Text: ${text}\nTranslated Text:",
290
+ },
291
+ ]
292
+ ```
293
+
294
+ 在自訂 Prompt 檔案中,可以使用以下三個內建變數來傳遞參數:
295
+ |**變數名稱**|**說明**|
296
+ |-|-|
297
+ |`lang_in`|輸入語言|
298
+ |`lang_out`|輸出語言|
299
+ |`text`|需要翻譯的文本|
300
+
301
+ <h2 id="todo">API</h2>
302
+
303
+ ### Python
304
+
305
+ ```python
306
+ from pdf2zh import translate, translate_stream
307
+
308
+ params = {"lang_in": "en", "lang_out": "zh", "service": "google", "thread": 4}
309
+ file_mono, file_dual = translate(files=["example.pdf"], **params)[0]
310
+ with open("example.pdf", "rb") as f:
311
+ stream_mono, stream_dual = translate_stream(stream=f.read(), **params)
312
+ ```
313
+
314
+ ### HTTP
315
+
316
+ ```bash
317
+ pip install pdf2zh[backend]
318
+ pdf2zh --flask
319
+ pdf2zh --celery worker
320
+ ```
321
+
322
+ ```bash
323
+ curl http://localhost:11008/v1/translate -F "[email protected]" -F "data={\"lang_in\":\"en\",\"lang_out\":\"zh\",\"service\":\"google\",\"thread\":4}"
324
+ {"id":"d9894125-2f4e-45ea-9d93-1a9068d2045a"}
325
+
326
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
327
+ {"info":{"n":13,"total":506},"state":"PROGRESS"}
328
+
329
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a
330
+ {"state":"SUCCESS"}
331
+
332
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/mono --output example-mono.pdf
333
+
334
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a/dual --output example-dual.pdf
335
+
336
+ curl http://localhost:11008/v1/translate/d9894125-2f4e-45ea-9d93-1a9068d2045a -X DELETE
337
+ ```
338
+
339
+ <h2 id="acknowledgement">致謝</h2>
340
+
341
+ - 文件合併:[PyMuPDF](https://github.com/pymupdf/PyMuPDF)
342
+ - 文件解析:[Pdfminer.six](https://github.com/pdfminer/pdfminer.six)
343
+ - 文件提取:[MinerU](https://github.com/opendatalab/MinerU)
344
+ - 文件預覽:[Gradio PDF](https://github.com/freddyaboulton/gradio-pdf)
345
+ - 多執行緒翻譯:[MathTranslate](https://github.com/SUSYUSTC/MathTranslate)
346
+ - 版面解析:[DocLayout-YOLO](https://github.com/opendatalab/DocLayout-YOLO)
347
+ - PDF 標準:[PDF Explained](https://zxyle.github.io/PDF-Explained/)、[PDF Cheat Sheets](https://pdfa.org/resource/pdf-cheat-sheets/)
348
+ - 多語言字型:[Go Noto Universal](https://github.com/satbyy/go-noto-universal)
349
+
350
+ <h2 id="contrib">貢獻者</h2>
351
+
352
+ <a href="https://github.com/Byaidu/PDFMathTranslate/graphs/contributors">
353
+ <img src="https://opencollective.com/PDFMathTranslate/contributors.svg?width=890&button=false" />
354
+ </a>
355
+
356
+ ![Alt](https://repobeats.axiom.co/api/embed/dfa7583da5332a11468d686fbd29b92320a6a869.svg "Repobeats analytics image")
357
+
358
+ <h2 id="star_hist">星標歷史</h2>
359
+
360
+ <a href="https://star-history.com/#Byaidu/PDFMathTranslate&Date">
361
+ <picture>
362
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date&theme=dark" />
363
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date" />
364
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Byaidu/PDFMathTranslate&type=Date"/>
365
+ </picture>
366
+ </a>
docs/images/after.png ADDED

Git LFS Details

  • SHA256: ea7983102723b661045985d7bd530e78008a72e6633e500752e9f534db3f31c5
  • Pointer size: 132 Bytes
  • Size of remote file: 1.3 MB
docs/images/banner.png ADDED

Git LFS Details

  • SHA256: 580a6334c36b9f1428a471f7597536eed69a21bf8872d756ff1af1c6edce265d
  • Pointer size: 131 Bytes
  • Size of remote file: 121 kB
docs/images/before.png ADDED

Git LFS Details

  • SHA256: 6333e4fdee8b372fe4f6969b9000d283d94cb9339b8ca650bc934b2c2db80f40
  • Pointer size: 132 Bytes
  • Size of remote file: 1.45 MB
docs/images/cmd.explained.png ADDED

Git LFS Details

  • SHA256: 40a6c40be8a41b353c29b85c1e5df3a624b80e453c7fa429c29719373b80d1e3
  • Pointer size: 130 Bytes
  • Size of remote file: 29.3 kB
docs/images/cmd.explained.zh.png ADDED

Git LFS Details

  • SHA256: 6e1f7308c27fa3f52031aa5e67e58af96a377019b271460f69ab07bcd00625a1
  • Pointer size: 130 Bytes
  • Size of remote file: 29.2 kB
docs/images/gui.gif ADDED
docs/images/preview.gif ADDED
entrypoint.sh ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ UPLOADED_FILES_RECORD="/app/uploaded_files.txt"
4
+ WATCH_DIR="pdf2zh_files"
5
+ cleanup() {
6
+ echo "正在退出..."
7
+ exit 0
8
+ }
9
+ trap cleanup SIGTERM SIGINT
10
+ echo "$APP_USERS" > /app/users.txt
11
+ chmod 600 /app/users.txt
12
+ cat > /app/config.json << CONFIG_EOF
13
+ {
14
+ "translators": [
15
+ {
16
+ "name": "openai",
17
+ "envs": {
18
+ "OPENAI_BASE_URL": "${OPENAI_BASE_URL}",
19
+ "OPENAI_API_KEY": "${OPENAI_API_KEY}",
20
+ "OPENAI_MODEL": "${OPENAI_MODEL}"
21
+ }
22
+ }
23
+ ],
24
+ "ENABLED_SERVICES": [
25
+ "OpenAI"
26
+ ],
27
+ "HIDDEN_GRADIO_DETAILS": true
28
+ }
29
+ CONFIG_EOF
30
+ pdf2zh -i --authorized /app/users.txt --config /app/config.json &
31
+ if [ ! -f "$UPLOADED_FILES_RECORD" ]; then
32
+ touch "$UPLOADED_FILES_RECORD"
33
+ fi
34
+ if [ ! -d "$WATCH_DIR" ]; then
35
+ mkdir "$WATCH_DIR"
36
+ fi
37
+ upload_file() {
38
+ local file="$1"
39
+ (
40
+ flock -n 9 || exit 1
41
+
42
+ if grep -Fxq "$file" "$UPLOADED_FILES_RECORD"; then
43
+ echo "文件 $file 已经上传过,跳过。"
44
+ exit 0
45
+ fi
46
+ echo "正在上传 $file..."
47
+ encoded_file=$(python3 -c "import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1]))" "$file")
48
+ if curl -T "$WATCH_DIR/$file" "$WEBDAV_URL/$encoded_file" --user "$WEBDAV_USER:$WEBDAV_PASS"; then
49
+ echo "成功上传 $file"
50
+ echo "$file" >> "$UPLOADED_FILES_RECORD"
51
+ else
52
+ echo "上传 $file 失败" >&2
53
+ fi
54
+
55
+ ) 9>>"$UPLOADED_FILES_RECORD.lock"
56
+ }
57
+ if command -v inotifywait >/dev/null 2>&1; then
58
+ echo "开始监控 $WATCH_DIR 文件夹..."
59
+ inotifywait -m -e create -e moved_to --format '%f' "$WATCH_DIR" |
60
+ while read -r filename; do
61
+ # 检查文件是否为 PDF,并且存在
62
+ if [[ "$filename" =~ \.pdf$ ]] && [ -f "$WATCH_DIR/$filename" ]; then
63
+ upload_file "$filename"
64
+ fi
65
+ done
66
+ else
67
+ echo "未安装 inotifywait,使用定期检查方式。您可以通过 'sudo apt-get install inotify-tools' 安装 inotifywait。"
68
+ while true; do
69
+ for local_file in "$WATCH_DIR"/*.pdf; do
70
+ if [ -f "$local_file" ]; then
71
+ filename=$(basename "$local_file")
72
+ # 检查文件是否已上传
73
+ if ! grep -Fxq "$filename" "$UPLOADED_FILES_RECORD"; then
74
+ upload_file "$filename"
75
+ fi
76
+ fi
77
+ done
78
+ sleep 60
79
+ done
80
+ fi
pdf2zh/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from pdf2zh.high_level import translate, translate_stream
3
+
4
+ log = logging.getLogger(__name__)
5
+
6
+ __version__ = "1.9.11"
7
+ __author__ = "Byaidu"
8
+ __all__ = ["translate", "translate_stream"]
pdf2zh/backend.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, send_file
2
+ from celery import Celery, Task
3
+ from celery.result import AsyncResult
4
+ from pdf2zh import translate_stream
5
+ import tqdm
6
+ import json
7
+ import io
8
+ from pdf2zh.doclayout import ModelInstance
9
+ from pdf2zh.config import ConfigManager
10
+
11
+ flask_app = Flask("pdf2zh")
12
+ flask_app.config.from_mapping(
13
+ CELERY=dict(
14
+ broker_url=ConfigManager.get("CELERY_BROKER", "redis://127.0.0.1:6379/0"),
15
+ result_backend=ConfigManager.get("CELERY_RESULT", "redis://127.0.0.1:6379/0"),
16
+ )
17
+ )
18
+
19
+
20
+ def celery_init_app(app: Flask) -> Celery:
21
+ class FlaskTask(Task):
22
+ def __call__(self, *args, **kwargs):
23
+ with app.app_context():
24
+ return self.run(*args, **kwargs)
25
+
26
+ celery_app = Celery(app.name)
27
+ celery_app.config_from_object(app.config["CELERY"])
28
+ celery_app.Task = FlaskTask
29
+ celery_app.set_default()
30
+ celery_app.autodiscover_tasks()
31
+ app.extensions["celery"] = celery_app
32
+ return celery_app
33
+
34
+
35
+ celery_app = celery_init_app(flask_app)
36
+
37
+
38
+ @celery_app.task(bind=True)
39
+ def translate_task(
40
+ self: Task,
41
+ stream: bytes,
42
+ args: dict,
43
+ ):
44
+ def progress_bar(t: tqdm.tqdm):
45
+ self.update_state(state="PROGRESS", meta={"n": t.n, "total": t.total}) # noqa
46
+ print(f"Translating {t.n} / {t.total} pages")
47
+
48
+ doc_mono, doc_dual = translate_stream(
49
+ stream,
50
+ callback=progress_bar,
51
+ model=ModelInstance.value,
52
+ **args,
53
+ )
54
+ return doc_mono, doc_dual
55
+
56
+
57
+ @flask_app.route("/v1/translate", methods=["POST"])
58
+ def create_translate_tasks():
59
+ file = request.files["file"]
60
+ stream = file.stream.read()
61
+ print(request.form.get("data"))
62
+ args = json.loads(request.form.get("data"))
63
+ task = translate_task.delay(stream, args)
64
+ return {"id": task.id}
65
+
66
+
67
+ @flask_app.route("/v1/translate/<id>", methods=["GET"])
68
+ def get_translate_task(id: str):
69
+ result: AsyncResult = celery_app.AsyncResult(id)
70
+ if str(result.state) == "PROGRESS":
71
+ return {"state": str(result.state), "info": result.info}
72
+ else:
73
+ return {"state": str(result.state)}
74
+
75
+
76
+ @flask_app.route("/v1/translate/<id>", methods=["DELETE"])
77
+ def delete_translate_task(id: str):
78
+ result: AsyncResult = celery_app.AsyncResult(id)
79
+ result.revoke(terminate=True)
80
+ return {"state": str(result.state)}
81
+
82
+
83
+ @flask_app.route("/v1/translate/<id>/<format>")
84
+ def get_translate_result(id: str, format: str):
85
+ result = celery_app.AsyncResult(id)
86
+ if not result.ready():
87
+ return {"error": "task not finished"}, 400
88
+ if not result.successful():
89
+ return {"error": "task failed"}, 400
90
+ doc_mono, doc_dual = result.get()
91
+ to_send = doc_mono if format == "mono" else doc_dual
92
+ return send_file(io.BytesIO(to_send), "application/pdf")
93
+
94
+
95
+ if __name__ == "__main__":
96
+ flask_app.run()
pdf2zh/cache.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import json
4
+ from peewee import Model, SqliteDatabase, AutoField, CharField, TextField, SQL
5
+ from typing import Optional
6
+
7
+
8
+ # we don't init the database here
9
+ db = SqliteDatabase(None)
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class _TranslationCache(Model):
14
+ id = AutoField()
15
+ translate_engine = CharField(max_length=20)
16
+ translate_engine_params = TextField()
17
+ original_text = TextField()
18
+ translation = TextField()
19
+
20
+ class Meta:
21
+ database = db
22
+ constraints = [
23
+ SQL(
24
+ """
25
+ UNIQUE (
26
+ translate_engine,
27
+ translate_engine_params,
28
+ original_text
29
+ )
30
+ ON CONFLICT REPLACE
31
+ """
32
+ )
33
+ ]
34
+
35
+
36
+ class TranslationCache:
37
+ @staticmethod
38
+ def _sort_dict_recursively(obj):
39
+ if isinstance(obj, dict):
40
+ return {
41
+ k: TranslationCache._sort_dict_recursively(v)
42
+ for k in sorted(obj.keys())
43
+ for v in [obj[k]]
44
+ }
45
+ elif isinstance(obj, list):
46
+ return [TranslationCache._sort_dict_recursively(item) for item in obj]
47
+ return obj
48
+
49
+ def __init__(self, translate_engine: str, translate_engine_params: dict = None):
50
+ assert (
51
+ len(translate_engine) < 20
52
+ ), "current cache require translate engine name less than 20 characters"
53
+ self.translate_engine = translate_engine
54
+ self.replace_params(translate_engine_params)
55
+
56
+ # The program typically starts multi-threaded translation
57
+ # only after cache parameters are fully configured,
58
+ # so thread safety doesn't need to be considered here.
59
+ def replace_params(self, params: dict = None):
60
+ if params is None:
61
+ params = {}
62
+ self.params = params
63
+ params = self._sort_dict_recursively(params)
64
+ self.translate_engine_params = json.dumps(params)
65
+
66
+ def update_params(self, params: dict = None):
67
+ if params is None:
68
+ params = {}
69
+ self.params.update(params)
70
+ self.replace_params(self.params)
71
+
72
+ def add_params(self, k: str, v):
73
+ self.params[k] = v
74
+ self.replace_params(self.params)
75
+
76
+ # Since peewee and the underlying sqlite are thread-safe,
77
+ # get and set operations don't need locks.
78
+ def get(self, original_text: str) -> Optional[str]:
79
+ result = _TranslationCache.get_or_none(
80
+ translate_engine=self.translate_engine,
81
+ translate_engine_params=self.translate_engine_params,
82
+ original_text=original_text,
83
+ )
84
+ return result.translation if result else None
85
+
86
+ def set(self, original_text: str, translation: str):
87
+ try:
88
+ _TranslationCache.create(
89
+ translate_engine=self.translate_engine,
90
+ translate_engine_params=self.translate_engine_params,
91
+ original_text=original_text,
92
+ translation=translation,
93
+ )
94
+ except Exception as e:
95
+ logger.debug(f"Error setting cache: {e}")
96
+
97
+
98
+ def init_db(remove_exists=False):
99
+ cache_folder = os.path.join(os.path.expanduser("~"), ".cache", "pdf2zh")
100
+ os.makedirs(cache_folder, exist_ok=True)
101
+ # The current version does not support database migration, so add the version number to the file name.
102
+ cache_db_path = os.path.join(cache_folder, "cache.v1.db")
103
+ if remove_exists and os.path.exists(cache_db_path):
104
+ os.remove(cache_db_path)
105
+ db.init(
106
+ cache_db_path,
107
+ pragmas={
108
+ "journal_mode": "wal",
109
+ "busy_timeout": 1000,
110
+ },
111
+ )
112
+ db.create_tables([_TranslationCache], safe=True)
113
+
114
+
115
+ def init_test_db():
116
+ import tempfile
117
+
118
+ cache_db_path = tempfile.mktemp(suffix=".db")
119
+ test_db = SqliteDatabase(
120
+ cache_db_path,
121
+ pragmas={
122
+ "journal_mode": "wal",
123
+ "busy_timeout": 1000,
124
+ },
125
+ )
126
+ test_db.bind([_TranslationCache], bind_refs=False, bind_backrefs=False)
127
+ test_db.connect()
128
+ test_db.create_tables([_TranslationCache], safe=True)
129
+ return test_db
130
+
131
+
132
+ def clean_test_db(test_db):
133
+ test_db.drop_tables([_TranslationCache])
134
+ test_db.close()
135
+ db_path = test_db.database
136
+ if os.path.exists(db_path):
137
+ os.remove(test_db.database)
138
+ wal_path = db_path + "-wal"
139
+ if os.path.exists(wal_path):
140
+ os.remove(wal_path)
141
+ shm_path = db_path + "-shm"
142
+ if os.path.exists(shm_path):
143
+ os.remove(shm_path)
144
+
145
+
146
+ init_db()
pdf2zh/config.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ from threading import RLock # 改成 RLock
4
+ import os
5
+ import copy
6
+
7
+
8
+ class ConfigManager:
9
+ _instance = None
10
+ _lock = RLock() # 用 RLock 替换 Lock,允许在同一个线程中重复获取锁
11
+
12
+ @classmethod
13
+ def get_instance(cls):
14
+ """获取单例实例"""
15
+ # 先判断是否存在实例,如果不存在再加锁进行初始化
16
+ if cls._instance is None:
17
+ with cls._lock:
18
+ if cls._instance is None:
19
+ cls._instance = cls()
20
+ return cls._instance
21
+
22
+ def __init__(self):
23
+ # 防止重复初始化
24
+ if hasattr(self, "_initialized") and self._initialized:
25
+ return
26
+ self._initialized = True
27
+
28
+ self._config_path = Path.home() / ".config" / "PDFMathTranslate" / "config.json"
29
+ self._config_data = {}
30
+
31
+ # 这里不要再加锁,因为外层可能已经加了锁 (get_instance), RLock也无妨
32
+ self._ensure_config_exists()
33
+
34
+ def _ensure_config_exists(self, isInit=True):
35
+ """确保配置文件存在,如果不存在则创建默认配置"""
36
+ # 这里也不需要显式再次加锁,原因同上,方法体中再调用 _load_config(),
37
+ # 而 _load_config() 内部会加锁。因为 RLock 是可重入的,不会阻塞。
38
+ if not self._config_path.exists():
39
+ if isInit:
40
+ self._config_path.parent.mkdir(parents=True, exist_ok=True)
41
+ self._config_data = {} # 默认配置内容
42
+ self._save_config()
43
+ else:
44
+ raise ValueError(f"config file {self._config_path} not found!")
45
+ else:
46
+ self._load_config()
47
+
48
+ def _load_config(self):
49
+ """从 config.json 中加载配置"""
50
+ with self._lock: # 加锁确保线程安全
51
+ with self._config_path.open("r", encoding="utf-8") as f:
52
+ self._config_data = json.load(f)
53
+
54
+ def _save_config(self):
55
+ """保存配置到 config.json"""
56
+ with self._lock: # 加锁确保线程安全
57
+ # 移除循环引用并写入
58
+ cleaned_data = self._remove_circular_references(self._config_data)
59
+ with self._config_path.open("w", encoding="utf-8") as f:
60
+ json.dump(cleaned_data, f, indent=4, ensure_ascii=False)
61
+
62
+ def _remove_circular_references(self, obj, seen=None):
63
+ """递归移除循环引用"""
64
+ if seen is None:
65
+ seen = set()
66
+ obj_id = id(obj)
67
+ if obj_id in seen:
68
+ return None # 遇到已处理过的对象,视为循环引用
69
+ seen.add(obj_id)
70
+
71
+ if isinstance(obj, dict):
72
+ return {
73
+ k: self._remove_circular_references(v, seen) for k, v in obj.items()
74
+ }
75
+ elif isinstance(obj, list):
76
+ return [self._remove_circular_references(i, seen) for i in obj]
77
+ return obj
78
+
79
+ @classmethod
80
+ def custome_config(cls, file_path):
81
+ """使用自定义路径加载配置文件"""
82
+ custom_path = Path(file_path)
83
+ if not custom_path.exists():
84
+ raise ValueError(f"Config file {custom_path} not found!")
85
+ # 加锁
86
+ with cls._lock:
87
+ instance = cls()
88
+ instance._config_path = custom_path
89
+ # 此处传 isInit=False,若不存在则报错;若存在则正常 _load_config()
90
+ instance._ensure_config_exists(isInit=False)
91
+ cls._instance = instance
92
+
93
+ @classmethod
94
+ def get(cls, key, default=None):
95
+ """获取配置值"""
96
+ instance = cls.get_instance()
97
+ # 读取时,加锁或不加锁都行。但为了统一,我们在修改配置前后都要加锁。
98
+ # get 只要最终需要保存,则会加锁 -> _save_config()
99
+ if key in instance._config_data:
100
+ return instance._config_data[key]
101
+
102
+ # 若环境变量中存在该 key,则使用环境变量并写回 config
103
+ if key in os.environ:
104
+ value = os.environ[key]
105
+ instance._config_data[key] = value
106
+ instance._save_config()
107
+ return value
108
+
109
+ # 若 default 不为 None,则设置并保存
110
+ if default is not None:
111
+ instance._config_data[key] = default
112
+ instance._save_config()
113
+ return default
114
+
115
+ # 找不到则抛出异常
116
+ # raise KeyError(f"{key} is not found in config file or environment variables.")
117
+ return default
118
+
119
+ @classmethod
120
+ def set(cls, key, value):
121
+ """设置配置值并保存"""
122
+ instance = cls.get_instance()
123
+ with instance._lock:
124
+ instance._config_data[key] = value
125
+ instance._save_config()
126
+
127
+ @classmethod
128
+ def get_translator_by_name(cls, name):
129
+ """根据 name 获取对应的 translator 配置"""
130
+ instance = cls.get_instance()
131
+ translators = instance._config_data.get("translators", [])
132
+ for translator in translators:
133
+ if translator.get("name") == name:
134
+ return translator["envs"]
135
+ return None
136
+
137
+ @classmethod
138
+ def set_translator_by_name(cls, name, new_translator_envs):
139
+ """根据 name 设置或更新 translator 配置"""
140
+ instance = cls.get_instance()
141
+ with instance._lock:
142
+ translators = instance._config_data.get("translators", [])
143
+ for translator in translators:
144
+ if translator.get("name") == name:
145
+ translator["envs"] = copy.deepcopy(new_translator_envs)
146
+ instance._save_config()
147
+ return
148
+ translators.append(
149
+ {"name": name, "envs": copy.deepcopy(new_translator_envs)}
150
+ )
151
+ instance._config_data["translators"] = translators
152
+ instance._save_config()
153
+
154
+ @classmethod
155
+ def get_env_by_translatername(cls, translater_name, name, default=None):
156
+ """根据 name 获取对应的 translator 配置"""
157
+ instance = cls.get_instance()
158
+ translators = instance._config_data.get("translators", [])
159
+ for translator in translators:
160
+ if translator.get("name") == translater_name.name:
161
+ if translator["envs"][name]:
162
+ return translator["envs"][name]
163
+ else:
164
+ with instance._lock:
165
+ translator["envs"][name] = default
166
+ instance._save_config()
167
+ return default
168
+
169
+ with instance._lock:
170
+ translators = instance._config_data.get("translators", [])
171
+ for translator in translators:
172
+ if translator.get("name") == translater_name.name:
173
+ translator["envs"][name] = default
174
+ instance._save_config()
175
+ return default
176
+ translators.append(
177
+ {
178
+ "name": translater_name.name,
179
+ "envs": copy.deepcopy(translater_name.envs),
180
+ }
181
+ )
182
+ instance._config_data["translators"] = translators
183
+ instance._save_config()
184
+ return default
185
+
186
+ @classmethod
187
+ def delete(cls, key):
188
+ """删除配置值并保存"""
189
+ instance = cls.get_instance()
190
+ with instance._lock:
191
+ if key in instance._config_data:
192
+ del instance._config_data[key]
193
+ instance._save_config()
194
+
195
+ @classmethod
196
+ def clear(cls):
197
+ """删除配置值并保存"""
198
+ instance = cls.get_instance()
199
+ with instance._lock:
200
+ instance._config_data = {}
201
+ instance._save_config()
202
+
203
+ @classmethod
204
+ def all(cls):
205
+ """返回所有配置项"""
206
+ instance = cls.get_instance()
207
+ # 这里只做读取操作,一般可不加锁。不过为了保险也可以加锁。
208
+ return instance._config_data
209
+
210
+ @classmethod
211
+ def remove(cls):
212
+ instance = cls.get_instance()
213
+ with instance._lock:
214
+ os.remove(instance._config_path)
pdf2zh/converter.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import concurrent.futures
2
+ import logging
3
+ import re
4
+ import unicodedata
5
+ from enum import Enum
6
+ from string import Template
7
+ from typing import Dict
8
+
9
+ import numpy as np
10
+ from pdfminer.converter import PDFConverter
11
+ from pdfminer.layout import LTChar, LTFigure, LTLine, LTPage
12
+ from pdfminer.pdffont import PDFCIDFont, PDFUnicodeNotDefined
13
+ from pdfminer.pdfinterp import PDFGraphicState, PDFResourceManager
14
+ from pdfminer.utils import apply_matrix_pt, mult_matrix
15
+ from pymupdf import Font
16
+ from tenacity import retry, wait_fixed
17
+
18
+ from pdf2zh.translator import (
19
+ AnythingLLMTranslator,
20
+ ArgosTranslator,
21
+ AzureOpenAITranslator,
22
+ AzureTranslator,
23
+ BaseTranslator,
24
+ BingTranslator,
25
+ DeepLTranslator,
26
+ DeepLXTranslator,
27
+ DeepseekTranslator,
28
+ DifyTranslator,
29
+ GeminiTranslator,
30
+ GoogleTranslator,
31
+ GrokTranslator,
32
+ GroqTranslator,
33
+ ModelScopeTranslator,
34
+ OllamaTranslator,
35
+ OpenAIlikedTranslator,
36
+ OpenAITranslator,
37
+ QwenMtTranslator,
38
+ SiliconTranslator,
39
+ TencentTranslator,
40
+ XinferenceTranslator,
41
+ ZhipuTranslator,
42
+ )
43
+
44
+ log = logging.getLogger(__name__)
45
+
46
+
47
+ class PDFConverterEx(PDFConverter):
48
+ def __init__(
49
+ self,
50
+ rsrcmgr: PDFResourceManager,
51
+ ) -> None:
52
+ PDFConverter.__init__(self, rsrcmgr, None, "utf-8", 1, None)
53
+
54
+ def begin_page(self, page, ctm) -> None:
55
+ # 重载替换 cropbox
56
+ (x0, y0, x1, y1) = page.cropbox
57
+ (x0, y0) = apply_matrix_pt(ctm, (x0, y0))
58
+ (x1, y1) = apply_matrix_pt(ctm, (x1, y1))
59
+ mediabox = (0, 0, abs(x0 - x1), abs(y0 - y1))
60
+ self.cur_item = LTPage(page.pageno, mediabox)
61
+
62
+ def end_page(self, page):
63
+ # 重载返回指令流
64
+ return self.receive_layout(self.cur_item)
65
+
66
+ def begin_figure(self, name, bbox, matrix) -> None:
67
+ # 重载设置 pageid
68
+ self._stack.append(self.cur_item)
69
+ self.cur_item = LTFigure(name, bbox, mult_matrix(matrix, self.ctm))
70
+ self.cur_item.pageid = self._stack[-1].pageid
71
+
72
+ def end_figure(self, _: str) -> None:
73
+ # 重载返回指令流
74
+ fig = self.cur_item
75
+ assert isinstance(self.cur_item, LTFigure), str(type(self.cur_item))
76
+ self.cur_item = self._stack.pop()
77
+ self.cur_item.add(fig)
78
+ return self.receive_layout(fig)
79
+
80
+ def render_char(
81
+ self,
82
+ matrix,
83
+ font,
84
+ fontsize: float,
85
+ scaling: float,
86
+ rise: float,
87
+ cid: int,
88
+ ncs,
89
+ graphicstate: PDFGraphicState,
90
+ ) -> float:
91
+ # 重载设置 cid 和 font
92
+ try:
93
+ text = font.to_unichr(cid)
94
+ assert isinstance(text, str), str(type(text))
95
+ except PDFUnicodeNotDefined:
96
+ text = self.handle_undefined_char(font, cid)
97
+ textwidth = font.char_width(cid)
98
+ textdisp = font.char_disp(cid)
99
+ item = LTChar(
100
+ matrix,
101
+ font,
102
+ fontsize,
103
+ scaling,
104
+ rise,
105
+ text,
106
+ textwidth,
107
+ textdisp,
108
+ ncs,
109
+ graphicstate,
110
+ )
111
+ self.cur_item.add(item)
112
+ item.cid = cid # hack 插入原字符编码
113
+ item.font = font # hack 插入原字符字体
114
+ return item.adv
115
+
116
+
117
+ class Paragraph:
118
+ def __init__(self, y, x, x0, x1, y0, y1, size, brk):
119
+ self.y: float = y # 初始纵坐标
120
+ self.x: float = x # 初始横坐标
121
+ self.x0: float = x0 # 左边界
122
+ self.x1: float = x1 # 右边界
123
+ self.y0: float = y0 # 上边界
124
+ self.y1: float = y1 # 下边界
125
+ self.size: float = size # 字体大小
126
+ self.brk: bool = brk # 换行标记
127
+
128
+
129
+ # fmt: off
130
+ class TranslateConverter(PDFConverterEx):
131
+ def __init__(
132
+ self,
133
+ rsrcmgr,
134
+ vfont: str = None,
135
+ vchar: str = None,
136
+ thread: int = 0,
137
+ layout={},
138
+ lang_in: str = "",
139
+ lang_out: str = "",
140
+ service: str = "",
141
+ noto_name: str = "",
142
+ noto: Font = None,
143
+ envs: Dict = None,
144
+ prompt: Template = None,
145
+ ignore_cache: bool = False,
146
+ ) -> None:
147
+ super().__init__(rsrcmgr)
148
+ self.vfont = vfont
149
+ self.vchar = vchar
150
+ self.thread = thread
151
+ self.layout = layout
152
+ self.noto_name = noto_name
153
+ self.noto = noto
154
+ self.translator: BaseTranslator = None
155
+ # e.g. "ollama:gemma2:9b" -> ["ollama", "gemma2:9b"]
156
+ param = service.split(":", 1)
157
+ service_name = param[0]
158
+ service_model = param[1] if len(param) > 1 else None
159
+ if not envs:
160
+ envs = {}
161
+ for translator in [GoogleTranslator, BingTranslator, DeepLTranslator, DeepLXTranslator, OllamaTranslator, XinferenceTranslator, AzureOpenAITranslator,
162
+ OpenAITranslator, ZhipuTranslator, ModelScopeTranslator, SiliconTranslator, GeminiTranslator, AzureTranslator, TencentTranslator, DifyTranslator, AnythingLLMTranslator, ArgosTranslator, GrokTranslator, GroqTranslator, DeepseekTranslator, OpenAIlikedTranslator, QwenMtTranslator,]:
163
+ if service_name == translator.name:
164
+ self.translator = translator(lang_in, lang_out, service_model, envs=envs, prompt=prompt, ignore_cache=ignore_cache)
165
+ if not self.translator:
166
+ raise ValueError("Unsupported translation service")
167
+
168
+ def receive_layout(self, ltpage: LTPage):
169
+ # 段落
170
+ sstk: list[str] = [] # 段落文字栈
171
+ pstk: list[Paragraph] = [] # 段落属性栈
172
+ vbkt: int = 0 # 段落公式括号计数
173
+ # 公式组
174
+ vstk: list[LTChar] = [] # 公式符号组
175
+ vlstk: list[LTLine] = [] # 公式线条组
176
+ vfix: float = 0 # 公式纵向偏移
177
+ # 公式组栈
178
+ var: list[list[LTChar]] = [] # 公式符号组栈
179
+ varl: list[list[LTLine]] = [] # 公式线条组栈
180
+ varf: list[float] = [] # 公式纵向偏移栈
181
+ vlen: list[float] = [] # 公式宽度栈
182
+ # 全局
183
+ lstk: list[LTLine] = [] # 全局线条栈
184
+ xt: LTChar = None # 上一个字符
185
+ xt_cls: int = -1 # 上一个字符所属段落,保证无论第一个字符属于哪个类别都可以触发新段落
186
+ vmax: float = ltpage.width / 4 # 行内公式最大宽度
187
+ ops: str = "" # 渲染结果
188
+
189
+ def vflag(font: str, char: str): # 匹配公式(和角标)字体
190
+ if isinstance(font, bytes): # 不一定能 decode,直接转 str
191
+ try:
192
+ font = font.decode('utf-8') # 尝试使用 UTF-8 解码
193
+ except UnicodeDecodeError:
194
+ font = ""
195
+ font = font.split("+")[-1] # 字体名截断
196
+ if re.match(r"\(cid:", char):
197
+ return True
198
+ # 基于字体名规则的判定
199
+ if self.vfont:
200
+ if re.match(self.vfont, font):
201
+ return True
202
+ else:
203
+ if re.match( # latex 字体
204
+ r"(CM[^R]|MS.M|XY|MT|BL|RM|EU|LA|RS|LINE|LCIRCLE|TeX-|rsfs|txsy|wasy|stmary|.*Mono|.*Code|.*Ital|.*Sym|.*Math)",
205
+ font,
206
+ ):
207
+ return True
208
+ # 基于字符集规则的判定
209
+ if self.vchar:
210
+ if re.match(self.vchar, char):
211
+ return True
212
+ else:
213
+ if (
214
+ char
215
+ and char != " " # 非空格
216
+ and (
217
+ unicodedata.category(char[0])
218
+ in ["Lm", "Mn", "Sk", "Sm", "Zl", "Zp", "Zs"] # 文字修饰符、数学符号、分隔符号
219
+ or ord(char[0]) in range(0x370, 0x400) # 希腊字母
220
+ )
221
+ ):
222
+ return True
223
+ return False
224
+
225
+ ############################################################
226
+ # A. 原文档解析
227
+ for child in ltpage:
228
+ if isinstance(child, LTChar):
229
+ cur_v = False
230
+ layout = self.layout[ltpage.pageid]
231
+ # ltpage.height 可能是 fig 里面的高度,这里统一用 layout.shape
232
+ h, w = layout.shape
233
+ # 读取当前字符在 layout 中的类别
234
+ cx, cy = np.clip(int(child.x0), 0, w - 1), np.clip(int(child.y0), 0, h - 1)
235
+ cls = layout[cy, cx]
236
+ # 锚定文档中 bullet 的位置
237
+ if child.get_text() == "•":
238
+ cls = 0
239
+ # 判定当前字符是否属于公式
240
+ if ( # 判定当前字符是否属于公式
241
+ cls == 0 # 1. 类别为保留区域
242
+ or (cls == xt_cls and len(sstk[-1].strip()) > 1 and child.size < pstk[-1].size * 0.79) # 2. 角标字体,有 0.76 的角标和 0.799 的大写,这里用 0.79 取中,同时考虑首字母放大的情况
243
+ or vflag(child.fontname, child.get_text()) # 3. 公式字体
244
+ or (child.matrix[0] == 0 and child.matrix[3] == 0) # 4. 垂直字体
245
+ ):
246
+ cur_v = True
247
+ # 判定括号组是否属于公式
248
+ if not cur_v:
249
+ if vstk and child.get_text() == "(":
250
+ cur_v = True
251
+ vbkt += 1
252
+ if vbkt and child.get_text() == ")":
253
+ cur_v = True
254
+ vbkt -= 1
255
+ if ( # 判定当前公式是否结束
256
+ not cur_v # 1. 当前字符不属于公式
257
+ or cls != xt_cls # 2. 当前字符与前一个字符不属于同一段落
258
+ # or (abs(child.x0 - xt.x0) > vmax and cls != 0) # 3. 段落内换行,可能是一长串斜体的段落,也可能是段内分式换行,这里设个阈值进行区分
259
+ # 禁止纯公式(代码)段落换行,直到文字开始再重开文字段落,保证只存在两种情况
260
+ # A. 纯公式(代码)段落(锚定绝对位置)sstk[-1]=="" -> sstk[-1]=="{v*}"
261
+ # B. 文字开头段落(排版相对位置)sstk[-1]!=""
262
+ or (sstk[-1] != "" and abs(child.x0 - xt.x0) > vmax) # 因为 cls==xt_cls==0 一定有 sstk[-1]=="",所以这里不需要再判定 cls!=0
263
+ ):
264
+ if vstk:
265
+ if ( # 根据公式右侧的文字修正公式的纵向偏移
266
+ not cur_v # 1. 当前字符不属于公式
267
+ and cls == xt_cls # 2. 当前字符与前一个字符属于同一段落
268
+ and child.x0 > max([vch.x0 for vch in vstk]) # 3. 当前字符在公式右侧
269
+ ):
270
+ vfix = vstk[0].y0 - child.y0
271
+ if sstk[-1] == "":
272
+ xt_cls = -1 # 禁止纯公式段落(sstk[-1]=="{v*}")的后续连接,但是要考虑新字符和后续字符的连接,所以这里修改的是上个字符的类别
273
+ sstk[-1] += f"{{v{len(var)}}}"
274
+ var.append(vstk)
275
+ varl.append(vlstk)
276
+ varf.append(vfix)
277
+ vstk = []
278
+ vlstk = []
279
+ vfix = 0
280
+ # 当前字符不属于公式或当前字符是公式的第一个字符
281
+ if not vstk:
282
+ if cls == xt_cls: # 当前字符与前一个字符属于同一段落
283
+ if child.x0 > xt.x1 + 1: # 添加行内空格
284
+ sstk[-1] += " "
285
+ elif child.x1 < xt.x0: # 添加换行空格并标记原文段落存在换行
286
+ sstk[-1] += " "
287
+ pstk[-1].brk = True
288
+ else: # 根据当前字符构建一个新的段落
289
+ sstk.append("")
290
+ pstk.append(Paragraph(child.y0, child.x0, child.x0, child.x0, child.y0, child.y1, child.size, False))
291
+ if not cur_v: # 文字入栈
292
+ if ( # 根据当前字符修正段落属性
293
+ child.size > pstk[-1].size # 1. 当前字符比段落字体大
294
+ or len(sstk[-1].strip()) == 1 # 2. 当前字符为段落第二个文字(考虑首字母放大的情况)
295
+ ) and child.get_text() != " ": # 3. 当前字符不是空格
296
+ pstk[-1].y -= child.size - pstk[-1].size # 修正段落初始纵坐标,假设两个不同大小字符的上边界对齐
297
+ pstk[-1].size = child.size
298
+ sstk[-1] += child.get_text()
299
+ else: # 公式入栈
300
+ if ( # 根据公式左侧的文字修正公式的纵向偏移
301
+ not vstk # 1. 当前字符是公式的第一个字符
302
+ and cls == xt_cls # 2. 当前字符与前一个字符属于同一段落
303
+ and child.x0 > xt.x0 # 3. 前一个字符在公式左侧
304
+ ):
305
+ vfix = child.y0 - xt.y0
306
+ vstk.append(child)
307
+ # 更新段落边界,因为段落内换行之后可能是公式开头,所以要在外边处理
308
+ pstk[-1].x0 = min(pstk[-1].x0, child.x0)
309
+ pstk[-1].x1 = max(pstk[-1].x1, child.x1)
310
+ pstk[-1].y0 = min(pstk[-1].y0, child.y0)
311
+ pstk[-1].y1 = max(pstk[-1].y1, child.y1)
312
+ # 更新上一个字符
313
+ xt = child
314
+ xt_cls = cls
315
+ elif isinstance(child, LTFigure): # 图表
316
+ pass
317
+ elif isinstance(child, LTLine): # 线条
318
+ layout = self.layout[ltpage.pageid]
319
+ # ltpage.height 可能是 fig 里面的高度,这里统一用 layout.shape
320
+ h, w = layout.shape
321
+ # 读取当前线条在 layout 中的类别
322
+ cx, cy = np.clip(int(child.x0), 0, w - 1), np.clip(int(child.y0), 0, h - 1)
323
+ cls = layout[cy, cx]
324
+ if vstk and cls == xt_cls: # 公式线条
325
+ vlstk.append(child)
326
+ else: # 全局线条
327
+ lstk.append(child)
328
+ else:
329
+ pass
330
+ # 处理结尾
331
+ if vstk: # 公式出栈
332
+ sstk[-1] += f"{{v{len(var)}}}"
333
+ var.append(vstk)
334
+ varl.append(vlstk)
335
+ varf.append(vfix)
336
+ log.debug("\n==========[VSTACK]==========\n")
337
+ for id, v in enumerate(var): # 计算公式宽度
338
+ l = max([vch.x1 for vch in v]) - v[0].x0
339
+ log.debug(f'< {l:.1f} {v[0].x0:.1f} {v[0].y0:.1f} {v[0].cid} {v[0].fontname} {len(varl[id])} > v{id} = {"".join([ch.get_text() for ch in v])}')
340
+ vlen.append(l)
341
+
342
+ ############################################################
343
+ # B. 段落翻译
344
+ log.debug("\n==========[SSTACK]==========\n")
345
+
346
+ @retry(wait=wait_fixed(1))
347
+ def worker(s: str): # 多线程翻译
348
+ if not s.strip() or re.match(r"^\{v\d+\}$", s): # 空白和公式不翻译
349
+ return s
350
+ try:
351
+ new = self.translator.translate(s)
352
+ return new
353
+ except BaseException as e:
354
+ if log.isEnabledFor(logging.DEBUG):
355
+ log.exception(e)
356
+ else:
357
+ log.exception(e, exc_info=False)
358
+ raise e
359
+ with concurrent.futures.ThreadPoolExecutor(
360
+ max_workers=self.thread
361
+ ) as executor:
362
+ news = list(executor.map(worker, sstk))
363
+
364
+ ############################################################
365
+ # C. 新文档排版
366
+ def raw_string(fcur: str, cstk: str): # 编码字符串
367
+ if fcur == self.noto_name:
368
+ return "".join(["%04x" % self.noto.has_glyph(ord(c)) for c in cstk])
369
+ elif isinstance(self.fontmap[fcur], PDFCIDFont): # 判断编码长度
370
+ return "".join(["%04x" % ord(c) for c in cstk])
371
+ else:
372
+ return "".join(["%02x" % ord(c) for c in cstk])
373
+
374
+ # 根据目标语言获取默认行距
375
+ LANG_LINEHEIGHT_MAP = {
376
+ "zh-cn": 1.4, "zh-tw": 1.4, "zh-hans": 1.4, "zh-hant": 1.4, "zh": 1.4,
377
+ "ja": 1.1, "ko": 1.2, "en": 1.2, "ar": 1.0, "ru": 0.8, "uk": 0.8, "ta": 0.8
378
+ }
379
+ default_line_height = LANG_LINEHEIGHT_MAP.get(self.translator.lang_out.lower(), 1.1) # 小语种默认1.1
380
+ _x, _y = 0, 0
381
+ ops_list = []
382
+
383
+ def gen_op_txt(font, size, x, y, rtxt):
384
+ return f"/{font} {size:f} Tf 1 0 0 1 {x:f} {y:f} Tm [<{rtxt}>] TJ "
385
+
386
+ def gen_op_line(x, y, xlen, ylen, linewidth):
387
+ return f"ET q 1 0 0 1 {x:f} {y:f} cm [] 0 d 0 J {linewidth:f} w 0 0 m {xlen:f} {ylen:f} l S Q BT "
388
+
389
+ for id, new in enumerate(news):
390
+ x: float = pstk[id].x # 段落初始横坐标
391
+ y: float = pstk[id].y # 段落初始纵坐标
392
+ x0: float = pstk[id].x0 # 段落左边界
393
+ x1: float = pstk[id].x1 # 段落右边界
394
+ height: float = pstk[id].y1 - pstk[id].y0 # 段落高度
395
+ size: float = pstk[id].size # 段落字体大小
396
+ brk: bool = pstk[id].brk # 段落换行标记
397
+ cstk: str = "" # 当前文字栈
398
+ fcur: str = None # 当前字体 ID
399
+ lidx = 0 # 记录换行次数
400
+ tx = x
401
+ fcur_ = fcur
402
+ ptr = 0
403
+ log.debug(f"< {y} {x} {x0} {x1} {size} {brk} > {sstk[id]} | {new}")
404
+
405
+ ops_vals: list[dict] = []
406
+
407
+ while ptr < len(new):
408
+ vy_regex = re.match(
409
+ r"\{\s*v([\d\s]+)\}", new[ptr:], re.IGNORECASE
410
+ ) # 匹配 {vn} 公式标记
411
+ mod = 0 # 文字修饰符
412
+ if vy_regex: # 加载公式
413
+ ptr += len(vy_regex.group(0))
414
+ try:
415
+ vid = int(vy_regex.group(1).replace(" ", ""))
416
+ adv = vlen[vid]
417
+ except Exception:
418
+ continue # 翻译器可能会自动补个越界的公式标记
419
+ if var[vid][-1].get_text() and unicodedata.category(var[vid][-1].get_text()[0]) in ["Lm", "Mn", "Sk"]: # 文字修饰符
420
+ mod = var[vid][-1].width
421
+ else: # 加载文字
422
+ ch = new[ptr]
423
+ fcur_ = None
424
+ try:
425
+ if fcur_ is None and self.fontmap["tiro"].to_unichr(ord(ch)) == ch:
426
+ fcur_ = "tiro" # 默认拉丁字体
427
+ except Exception:
428
+ pass
429
+ if fcur_ is None:
430
+ fcur_ = self.noto_name # 默认非拉丁字体
431
+ if fcur_ == self.noto_name: # FIXME: change to CONST
432
+ adv = self.noto.char_lengths(ch, size)[0]
433
+ else:
434
+ adv = self.fontmap[fcur_].char_width(ord(ch)) * size
435
+ ptr += 1
436
+ if ( # 输出文字缓冲区
437
+ fcur_ != fcur # 1. 字体更新
438
+ or vy_regex # 2. 插入公式
439
+ or x + adv > x1 + 0.1 * size # 3. 到达右边界(可能一整行都被符号化,这里需要考虑浮点误差)
440
+ ):
441
+ if cstk:
442
+ ops_vals.append({
443
+ "type": OpType.TEXT,
444
+ "font": fcur,
445
+ "size": size,
446
+ "x": tx,
447
+ "dy": 0,
448
+ "rtxt": raw_string(fcur, cstk),
449
+ "lidx": lidx
450
+ })
451
+ cstk = ""
452
+ if brk and x + adv > x1 + 0.1 * size: # 到达右边界且原文段落存在换行
453
+ x = x0
454
+ lidx += 1
455
+ if vy_regex: # 插入公式
456
+ fix = 0
457
+ if fcur is not None: # 段落内公式修正纵向偏移
458
+ fix = varf[vid]
459
+ for vch in var[vid]: # 排版公式字符
460
+ vc = chr(vch.cid)
461
+ ops_vals.append({
462
+ "type": OpType.TEXT,
463
+ "font": self.fontid[vch.font],
464
+ "size": vch.size,
465
+ "x": x + vch.x0 - var[vid][0].x0,
466
+ "dy": fix + vch.y0 - var[vid][0].y0,
467
+ "rtxt": raw_string(self.fontid[vch.font], vc),
468
+ "lidx": lidx
469
+ })
470
+ if log.isEnabledFor(logging.DEBUG):
471
+ lstk.append(LTLine(0.1, (_x, _y), (x + vch.x0 - var[vid][0].x0, fix + y + vch.y0 - var[vid][0].y0)))
472
+ _x, _y = x + vch.x0 - var[vid][0].x0, fix + y + vch.y0 - var[vid][0].y0
473
+ for l in varl[vid]: # 排版公式线条
474
+ if l.linewidth < 5: # hack 有的文档会用粗线条当图片背景
475
+ ops_vals.append({
476
+ "type": OpType.LINE,
477
+ "x": l.pts[0][0] + x - var[vid][0].x0,
478
+ "dy": l.pts[0][1] + fix - var[vid][0].y0,
479
+ "linewidth": l.linewidth,
480
+ "xlen": l.pts[1][0] - l.pts[0][0],
481
+ "ylen": l.pts[1][1] - l.pts[0][1],
482
+ "lidx": lidx
483
+ })
484
+ else: # 插入文字缓冲区
485
+ if not cstk: # 单行开头
486
+ tx = x
487
+ if x == x0 and ch == " ": # 消除段落换行空格
488
+ adv = 0
489
+ else:
490
+ cstk += ch
491
+ else:
492
+ cstk += ch
493
+ adv -= mod # 文字修饰符
494
+ fcur = fcur_
495
+ x += adv
496
+ if log.isEnabledFor(logging.DEBUG):
497
+ lstk.append(LTLine(0.1, (_x, _y), (x, y)))
498
+ _x, _y = x, y
499
+ # 处理结尾
500
+ if cstk:
501
+ ops_vals.append({
502
+ "type": OpType.TEXT,
503
+ "font": fcur,
504
+ "size": size,
505
+ "x": tx,
506
+ "dy": 0,
507
+ "rtxt": raw_string(fcur, cstk),
508
+ "lidx": lidx
509
+ })
510
+
511
+ line_height = default_line_height
512
+
513
+ while (lidx + 1) * size * line_height > height and line_height >= 1:
514
+ line_height -= 0.05
515
+
516
+ for vals in ops_vals:
517
+ if vals["type"] == OpType.TEXT:
518
+ ops_list.append(gen_op_txt(vals["font"], vals["size"], vals["x"], vals["dy"] + y - vals["lidx"] * size * line_height, vals["rtxt"]))
519
+ elif vals["type"] == OpType.LINE:
520
+ ops_list.append(gen_op_line(vals["x"], vals["dy"] + y - vals["lidx"] * size * line_height, vals["xlen"], vals["ylen"], vals["linewidth"]))
521
+
522
+ for l in lstk: # 排版全局线条
523
+ if l.linewidth < 5: # hack 有的文档会用粗线条当图片背景
524
+ ops_list.append(gen_op_line(l.pts[0][0], l.pts[0][1], l.pts[1][0] - l.pts[0][0], l.pts[1][1] - l.pts[0][1], l.linewidth))
525
+
526
+ ops = f"BT {''.join(ops_list)}ET "
527
+ return ops
528
+
529
+
530
+ class OpType(Enum):
531
+ TEXT = "text"
532
+ LINE = "line"
pdf2zh/doclayout.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import os.path
3
+
4
+ import cv2
5
+ import numpy as np
6
+ import ast
7
+ from babeldoc.assets.assets import get_doclayout_onnx_model_path
8
+
9
+ try:
10
+ import onnx
11
+ import onnxruntime
12
+ except ImportError as e:
13
+ if "DLL load failed" in str(e):
14
+ raise OSError(
15
+ "Microsoft Visual C++ Redistributable is not installed. "
16
+ "Download it at https://aka.ms/vs/17/release/vc_redist.x64.exe"
17
+ ) from e
18
+ raise
19
+
20
+ from huggingface_hub import hf_hub_download
21
+
22
+ from pdf2zh.config import ConfigManager
23
+
24
+
25
+ class DocLayoutModel(abc.ABC):
26
+ @staticmethod
27
+ def load_onnx():
28
+ model = OnnxModel.from_pretrained()
29
+ return model
30
+
31
+ @staticmethod
32
+ def load_available():
33
+ return DocLayoutModel.load_onnx()
34
+
35
+ @property
36
+ @abc.abstractmethod
37
+ def stride(self) -> int:
38
+ """Stride of the model input."""
39
+ pass
40
+
41
+ @abc.abstractmethod
42
+ def predict(self, image, imgsz=1024, **kwargs) -> list:
43
+ """
44
+ Predict the layout of a document page.
45
+
46
+ Args:
47
+ image: The image of the document page.
48
+ imgsz: Resize the image to this size. Must be a multiple of the stride.
49
+ **kwargs: Additional arguments.
50
+ """
51
+ pass
52
+
53
+
54
+ class YoloResult:
55
+ """Helper class to store detection results from ONNX model."""
56
+
57
+ def __init__(self, boxes, names):
58
+ self.boxes = [YoloBox(data=d) for d in boxes]
59
+ self.boxes.sort(key=lambda x: x.conf, reverse=True)
60
+ self.names = names
61
+
62
+
63
+ class YoloBox:
64
+ """Helper class to store detection results from ONNX model."""
65
+
66
+ def __init__(self, data):
67
+ self.xyxy = data[:4]
68
+ self.conf = data[-2]
69
+ self.cls = data[-1]
70
+
71
+
72
+ class OnnxModel(DocLayoutModel):
73
+ def __init__(self, model_path: str):
74
+ self.model_path = model_path
75
+
76
+ model = onnx.load(model_path)
77
+ metadata = {d.key: d.value for d in model.metadata_props}
78
+ self._stride = ast.literal_eval(metadata["stride"])
79
+ self._names = ast.literal_eval(metadata["names"])
80
+
81
+ self.model = onnxruntime.InferenceSession(model.SerializeToString())
82
+
83
+ @staticmethod
84
+ def from_pretrained():
85
+ pth = get_doclayout_onnx_model_path()
86
+ return OnnxModel(pth)
87
+
88
+ @property
89
+ def stride(self):
90
+ return self._stride
91
+
92
+ def resize_and_pad_image(self, image, new_shape):
93
+ """
94
+ Resize and pad the image to the specified size, ensuring dimensions are multiples of stride.
95
+
96
+ Parameters:
97
+ - image: Input image
98
+ - new_shape: Target size (integer or (height, width) tuple)
99
+ - stride: Padding alignment stride, default 32
100
+
101
+ Returns:
102
+ - Processed image
103
+ """
104
+ if isinstance(new_shape, int):
105
+ new_shape = (new_shape, new_shape)
106
+
107
+ h, w = image.shape[:2]
108
+ new_h, new_w = new_shape
109
+
110
+ # Calculate scaling ratio
111
+ r = min(new_h / h, new_w / w)
112
+ resized_h, resized_w = int(round(h * r)), int(round(w * r))
113
+
114
+ # Resize image
115
+ image = cv2.resize(
116
+ image, (resized_w, resized_h), interpolation=cv2.INTER_LINEAR
117
+ )
118
+
119
+ # Calculate padding size and align to stride multiple
120
+ pad_w = (new_w - resized_w) % self.stride
121
+ pad_h = (new_h - resized_h) % self.stride
122
+ top, bottom = pad_h // 2, pad_h - pad_h // 2
123
+ left, right = pad_w // 2, pad_w - pad_w // 2
124
+
125
+ # Add padding
126
+ image = cv2.copyMakeBorder(
127
+ image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114)
128
+ )
129
+
130
+ return image
131
+
132
+ def scale_boxes(self, img1_shape, boxes, img0_shape):
133
+ """
134
+ Rescales bounding boxes (in the format of xyxy by default) from the shape of the image they were originally
135
+ specified in (img1_shape) to the shape of a different image (img0_shape).
136
+
137
+ Args:
138
+ img1_shape (tuple): The shape of the image that the bounding boxes are for,
139
+ in the format of (height, width).
140
+ boxes (torch.Tensor): the bounding boxes of the objects in the image, in the format of (x1, y1, x2, y2)
141
+ img0_shape (tuple): the shape of the target image, in the format of (height, width).
142
+
143
+ Returns:
144
+ boxes (torch.Tensor): The scaled bounding boxes, in the format of (x1, y1, x2, y2)
145
+ """
146
+
147
+ # Calculate scaling ratio
148
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1])
149
+
150
+ # Calculate padding size
151
+ pad_x = round((img1_shape[1] - img0_shape[1] * gain) / 2 - 0.1)
152
+ pad_y = round((img1_shape[0] - img0_shape[0] * gain) / 2 - 0.1)
153
+
154
+ # Remove padding and scale boxes
155
+ boxes[..., :4] = (boxes[..., :4] - [pad_x, pad_y, pad_x, pad_y]) / gain
156
+ return boxes
157
+
158
+ def predict(self, image, imgsz=1024, **kwargs):
159
+ # Preprocess input image
160
+ orig_h, orig_w = image.shape[:2]
161
+ pix = self.resize_and_pad_image(image, new_shape=imgsz)
162
+ pix = np.transpose(pix, (2, 0, 1)) # CHW
163
+ pix = np.expand_dims(pix, axis=0) # BCHW
164
+ pix = pix.astype(np.float32) / 255.0 # Normalize to [0, 1]
165
+ new_h, new_w = pix.shape[2:]
166
+
167
+ # Run inference
168
+ preds = self.model.run(None, {"images": pix})[0]
169
+
170
+ # Postprocess predictions
171
+ preds = preds[preds[..., 4] > 0.25]
172
+ preds[..., :4] = self.scale_boxes(
173
+ (new_h, new_w), preds[..., :4], (orig_h, orig_w)
174
+ )
175
+ return [YoloResult(boxes=preds, names=self._names)]
176
+
177
+
178
+ class ModelInstance:
179
+ value: OnnxModel = None
pdf2zh/gui.py ADDED
@@ -0,0 +1,888 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import cgi
3
+ import os
4
+ import shutil
5
+ import uuid
6
+ from asyncio import CancelledError
7
+ from pathlib import Path
8
+ import typing as T
9
+
10
+ import gradio as gr
11
+ import requests
12
+ import tqdm
13
+ from gradio_pdf import PDF
14
+ from string import Template
15
+ import logging
16
+
17
+ from pdf2zh import __version__
18
+ from pdf2zh.high_level import translate
19
+ from pdf2zh.doclayout import ModelInstance
20
+ from pdf2zh.config import ConfigManager
21
+ from pdf2zh.translator import (
22
+ AnythingLLMTranslator,
23
+ AzureOpenAITranslator,
24
+ AzureTranslator,
25
+ BaseTranslator,
26
+ BingTranslator,
27
+ DeepLTranslator,
28
+ DeepLXTranslator,
29
+ DifyTranslator,
30
+ ArgosTranslator,
31
+ GeminiTranslator,
32
+ GoogleTranslator,
33
+ ModelScopeTranslator,
34
+ OllamaTranslator,
35
+ OpenAITranslator,
36
+ SiliconTranslator,
37
+ TencentTranslator,
38
+ XinferenceTranslator,
39
+ ZhipuTranslator,
40
+ GrokTranslator,
41
+ GroqTranslator,
42
+ DeepseekTranslator,
43
+ OpenAIlikedTranslator,
44
+ QwenMtTranslator,
45
+ )
46
+ from babeldoc.docvision.doclayout import OnnxModel
47
+ from babeldoc import __version__ as babeldoc_version
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+ BABELDOC_MODEL = OnnxModel.load_available()
52
+ # The following variables associate strings with translators
53
+ service_map: dict[str, BaseTranslator] = {
54
+ "Google": GoogleTranslator,
55
+ "Bing": BingTranslator,
56
+ "DeepL": DeepLTranslator,
57
+ "DeepLX": DeepLXTranslator,
58
+ "Ollama": OllamaTranslator,
59
+ "Xinference": XinferenceTranslator,
60
+ "AzureOpenAI": AzureOpenAITranslator,
61
+ "OpenAI": OpenAITranslator,
62
+ "Zhipu": ZhipuTranslator,
63
+ "ModelScope": ModelScopeTranslator,
64
+ "Silicon": SiliconTranslator,
65
+ "Gemini": GeminiTranslator,
66
+ "Azure": AzureTranslator,
67
+ "Tencent": TencentTranslator,
68
+ "Dify": DifyTranslator,
69
+ "AnythingLLM": AnythingLLMTranslator,
70
+ "Argos Translate": ArgosTranslator,
71
+ "Grok": GrokTranslator,
72
+ "Groq": GroqTranslator,
73
+ "DeepSeek": DeepseekTranslator,
74
+ "OpenAI-liked": OpenAIlikedTranslator,
75
+ "Ali Qwen-Translation": QwenMtTranslator,
76
+ }
77
+
78
+ # The following variables associate strings with specific languages
79
+ lang_map = {
80
+ "Simplified Chinese": "zh",
81
+ "Traditional Chinese": "zh-TW",
82
+ "English": "en",
83
+ "French": "fr",
84
+ "German": "de",
85
+ "Japanese": "ja",
86
+ "Korean": "ko",
87
+ "Russian": "ru",
88
+ "Spanish": "es",
89
+ "Italian": "it",
90
+ }
91
+
92
+ # The following variable associate strings with page ranges
93
+ page_map = {
94
+ "All": None,
95
+ "First": [0],
96
+ "First 5 pages": list(range(0, 5)),
97
+ "Others": None,
98
+ }
99
+
100
+ # Check if this is a public demo, which has resource limits
101
+ flag_demo = False
102
+
103
+ # Limit resources
104
+ if ConfigManager.get("PDF2ZH_DEMO"):
105
+ flag_demo = True
106
+ service_map = {
107
+ "Google": GoogleTranslator,
108
+ }
109
+ page_map = {
110
+ "First": [0],
111
+ "First 20 pages": list(range(0, 20)),
112
+ }
113
+ client_key = ConfigManager.get("PDF2ZH_CLIENT_KEY")
114
+ server_key = ConfigManager.get("PDF2ZH_SERVER_KEY")
115
+
116
+
117
+ # Limit Enabled Services
118
+ enabled_services: T.Optional[T.List[str]] = ConfigManager.get("ENABLED_SERVICES")
119
+ if isinstance(enabled_services, list):
120
+ default_services = ["Google", "Bing"]
121
+ enabled_services_names = [str(_).lower().strip() for _ in enabled_services]
122
+ enabled_services = [
123
+ k
124
+ for k in service_map.keys()
125
+ if str(k).lower().strip() in enabled_services_names
126
+ ]
127
+ if len(enabled_services) == 0:
128
+ raise RuntimeError("No services available.")
129
+ enabled_services = default_services + enabled_services
130
+ else:
131
+ enabled_services = list(service_map.keys())
132
+
133
+
134
+ # Configure about Gradio show keys
135
+ hidden_gradio_details: bool = bool(ConfigManager.get("HIDDEN_GRADIO_DETAILS"))
136
+
137
+
138
+ # Public demo control
139
+ def verify_recaptcha(response):
140
+ """
141
+ This function verifies the reCAPTCHA response.
142
+ """
143
+ recaptcha_url = "https://www.google.com/recaptcha/api/siteverify"
144
+ data = {"secret": server_key, "response": response}
145
+ result = requests.post(recaptcha_url, data=data).json()
146
+ return result.get("success")
147
+
148
+
149
+ def download_with_limit(url: str, save_path: str, size_limit: int) -> str:
150
+ """
151
+ This function downloads a file from a URL and saves it to a specified path.
152
+
153
+ Inputs:
154
+ - url: The URL to download the file from
155
+ - save_path: The path to save the file to
156
+ - size_limit: The maximum size of the file to download
157
+
158
+ Returns:
159
+ - The path of the downloaded file
160
+ """
161
+ chunk_size = 1024
162
+ total_size = 0
163
+ with requests.get(url, stream=True, timeout=10) as response:
164
+ response.raise_for_status()
165
+ content = response.headers.get("Content-Disposition")
166
+ try: # filename from header
167
+ _, params = cgi.parse_header(content)
168
+ filename = params["filename"]
169
+ except Exception: # filename from url
170
+ filename = os.path.basename(url)
171
+ filename = os.path.splitext(os.path.basename(filename))[0] + ".pdf"
172
+ with open(save_path / filename, "wb") as file:
173
+ for chunk in response.iter_content(chunk_size=chunk_size):
174
+ total_size += len(chunk)
175
+ if size_limit and total_size > size_limit:
176
+ raise gr.Error("Exceeds file size limit")
177
+ file.write(chunk)
178
+ return save_path / filename
179
+
180
+
181
+ def stop_translate_file(state: dict) -> None:
182
+ """
183
+ This function stops the translation process.
184
+
185
+ Inputs:
186
+ - state: The state of the translation process
187
+
188
+ Returns:- None
189
+ """
190
+ session_id = state["session_id"]
191
+ if session_id is None:
192
+ return
193
+ if session_id in cancellation_event_map:
194
+ logger.info(f"Stopping translation for session {session_id}")
195
+ cancellation_event_map[session_id].set()
196
+
197
+
198
+ def translate_file(
199
+ file_type,
200
+ file_input,
201
+ link_input,
202
+ service,
203
+ lang_from,
204
+ lang_to,
205
+ page_range,
206
+ page_input,
207
+ prompt,
208
+ threads,
209
+ skip_subset_fonts,
210
+ ignore_cache,
211
+ vfont,
212
+ use_babeldoc,
213
+ recaptcha_response,
214
+ state,
215
+ progress=gr.Progress(),
216
+ *envs,
217
+ ):
218
+ """
219
+ This function translates a PDF file from one language to another.
220
+
221
+ Inputs:
222
+ - file_type: The type of file to translate
223
+ - file_input: The file to translate
224
+ - link_input: The link to the file to translate
225
+ - service: The translation service to use
226
+ - lang_from: The language to translate from
227
+ - lang_to: The language to translate to
228
+ - page_range: The range of pages to translate
229
+ - page_input: The input for the page range
230
+ - prompt: The custom prompt for the llm
231
+ - threads: The number of threads to use
232
+ - recaptcha_response: The reCAPTCHA response
233
+ - state: The state of the translation process
234
+ - progress: The progress bar
235
+ - envs: The environment variables
236
+
237
+ Returns:
238
+ - The translated file
239
+ - The translated file
240
+ - The translated file
241
+ - The progress bar
242
+ - The progress bar
243
+ - The progress bar
244
+ """
245
+ session_id = uuid.uuid4()
246
+ state["session_id"] = session_id
247
+ cancellation_event_map[session_id] = asyncio.Event()
248
+ # Translate PDF content using selected service.
249
+ if flag_demo and not verify_recaptcha(recaptcha_response):
250
+ raise gr.Error("reCAPTCHA fail")
251
+
252
+ progress(0, desc="Starting translation...")
253
+
254
+ output = Path("pdf2zh_files")
255
+ output.mkdir(parents=True, exist_ok=True)
256
+
257
+ if file_type == "File":
258
+ if not file_input:
259
+ raise gr.Error("No input")
260
+ file_path = shutil.copy(file_input, output)
261
+ else:
262
+ if not link_input:
263
+ raise gr.Error("No input")
264
+ file_path = download_with_limit(
265
+ link_input,
266
+ output,
267
+ 5 * 1024 * 1024 if flag_demo else None,
268
+ )
269
+
270
+ filename = os.path.splitext(os.path.basename(file_path))[0]
271
+ file_raw = output / f"{filename}.pdf"
272
+ file_mono = output / f"{filename}-mono.pdf"
273
+ file_dual = output / f"{filename}-dual.pdf"
274
+
275
+ translator = service_map[service]
276
+ if page_range != "Others":
277
+ selected_page = page_map[page_range]
278
+ else:
279
+ selected_page = []
280
+ for p in page_input.split(","):
281
+ if "-" in p:
282
+ start, end = p.split("-")
283
+ selected_page.extend(range(int(start) - 1, int(end)))
284
+ else:
285
+ selected_page.append(int(p) - 1)
286
+ lang_from = lang_map[lang_from]
287
+ lang_to = lang_map[lang_to]
288
+
289
+ _envs = {}
290
+ for i, env in enumerate(translator.envs.items()):
291
+ _envs[env[0]] = envs[i]
292
+ for k, v in _envs.items():
293
+ if str(k).upper().endswith("API_KEY") and str(v) == "***":
294
+ # Load Real API_KEYs from local configure file
295
+ real_keys: str = ConfigManager.get_env_by_translatername(
296
+ translator, k, None
297
+ )
298
+ _envs[k] = real_keys
299
+
300
+ print(f"Files before translation: {os.listdir(output)}")
301
+
302
+ def progress_bar(t: tqdm.tqdm):
303
+ desc = getattr(t, "desc", "Translating...")
304
+ if desc == "":
305
+ desc = "Translating..."
306
+ progress(t.n / t.total, desc=desc)
307
+
308
+ try:
309
+ threads = int(threads)
310
+ except ValueError:
311
+ threads = 1
312
+
313
+ param = {
314
+ "files": [str(file_raw)],
315
+ "pages": selected_page,
316
+ "lang_in": lang_from,
317
+ "lang_out": lang_to,
318
+ "service": f"{translator.name}",
319
+ "output": output,
320
+ "thread": int(threads),
321
+ "callback": progress_bar,
322
+ "cancellation_event": cancellation_event_map[session_id],
323
+ "envs": _envs,
324
+ "prompt": Template(prompt) if prompt else None,
325
+ "skip_subset_fonts": skip_subset_fonts,
326
+ "ignore_cache": ignore_cache,
327
+ "vfont": vfont, # 添加自定义公式字体正则表达式
328
+ "model": ModelInstance.value,
329
+ }
330
+
331
+ try:
332
+ if use_babeldoc:
333
+ return babeldoc_translate_file(**param)
334
+ translate(**param)
335
+ except CancelledError:
336
+ del cancellation_event_map[session_id]
337
+ raise gr.Error("Translation cancelled")
338
+ print(f"Files after translation: {os.listdir(output)}")
339
+
340
+ if not file_mono.exists() or not file_dual.exists():
341
+ raise gr.Error("No output")
342
+
343
+ progress(1.0, desc="Translation complete!")
344
+
345
+ return (
346
+ str(file_mono),
347
+ str(file_mono),
348
+ str(file_dual),
349
+ gr.update(visible=True),
350
+ gr.update(visible=True),
351
+ gr.update(visible=True),
352
+ )
353
+
354
+
355
+ def babeldoc_translate_file(**kwargs):
356
+ from babeldoc.high_level import init as babeldoc_init
357
+
358
+ babeldoc_init()
359
+ from babeldoc.high_level import async_translate as babeldoc_translate
360
+ from babeldoc.translation_config import TranslationConfig as YadtConfig
361
+
362
+ for translator in [
363
+ GoogleTranslator,
364
+ BingTranslator,
365
+ DeepLTranslator,
366
+ DeepLXTranslator,
367
+ OllamaTranslator,
368
+ XinferenceTranslator,
369
+ AzureOpenAITranslator,
370
+ OpenAITranslator,
371
+ ZhipuTranslator,
372
+ ModelScopeTranslator,
373
+ SiliconTranslator,
374
+ GeminiTranslator,
375
+ AzureTranslator,
376
+ TencentTranslator,
377
+ DifyTranslator,
378
+ AnythingLLMTranslator,
379
+ ArgosTranslator,
380
+ GrokTranslator,
381
+ GroqTranslator,
382
+ DeepseekTranslator,
383
+ OpenAIlikedTranslator,
384
+ QwenMtTranslator,
385
+ ]:
386
+ if kwargs["service"] == translator.name:
387
+ translator = translator(
388
+ kwargs["lang_in"],
389
+ kwargs["lang_out"],
390
+ "",
391
+ envs=kwargs["envs"],
392
+ prompt=kwargs["prompt"],
393
+ ignore_cache=kwargs["ignore_cache"],
394
+ )
395
+ break
396
+ else:
397
+ raise ValueError("Unsupported translation service")
398
+ import asyncio
399
+ from babeldoc.main import create_progress_handler
400
+
401
+ for file in kwargs["files"]:
402
+ file = file.strip("\"'")
403
+ yadt_config = YadtConfig(
404
+ input_file=file,
405
+ font=None,
406
+ pages=",".join((str(x) for x in getattr(kwargs, "raw_pages", []))),
407
+ output_dir=kwargs["output"],
408
+ doc_layout_model=BABELDOC_MODEL,
409
+ translator=translator,
410
+ debug=False,
411
+ lang_in=kwargs["lang_in"],
412
+ lang_out=kwargs["lang_out"],
413
+ no_dual=False,
414
+ no_mono=False,
415
+ qps=kwargs["thread"],
416
+ use_rich_pbar=False,
417
+ disable_rich_text_translate=not isinstance(translator, OpenAITranslator),
418
+ skip_clean=kwargs["skip_subset_fonts"],
419
+ report_interval=0.5,
420
+ )
421
+
422
+ async def yadt_translate_coro(yadt_config):
423
+ progress_context, progress_handler = create_progress_handler(yadt_config)
424
+
425
+ # 开始翻译
426
+ with progress_context:
427
+ async for event in babeldoc_translate(yadt_config):
428
+ progress_handler(event)
429
+ if yadt_config.debug:
430
+ logger.debug(event)
431
+ kwargs["callback"](progress_context)
432
+ if kwargs["cancellation_event"].is_set():
433
+ yadt_config.cancel_translation()
434
+ raise CancelledError
435
+ if event["type"] == "finish":
436
+ result = event["translate_result"]
437
+ logger.info("Translation Result:")
438
+ logger.info(f" Original PDF: {result.original_pdf_path}")
439
+ logger.info(f" Time Cost: {result.total_seconds:.2f}s")
440
+ logger.info(f" Mono PDF: {result.mono_pdf_path or 'None'}")
441
+ logger.info(f" Dual PDF: {result.dual_pdf_path or 'None'}")
442
+ file_mono = result.mono_pdf_path
443
+ file_dual = result.dual_pdf_path
444
+ break
445
+ import gc
446
+
447
+ gc.collect()
448
+ return (
449
+ str(file_mono),
450
+ str(file_mono),
451
+ str(file_dual),
452
+ gr.update(visible=True),
453
+ gr.update(visible=True),
454
+ gr.update(visible=True),
455
+ )
456
+
457
+ return asyncio.run(yadt_translate_coro(yadt_config))
458
+
459
+
460
+ # Global setup
461
+ custom_blue = gr.themes.Color(
462
+ c50="#E8F3FF",
463
+ c100="#BEDAFF",
464
+ c200="#94BFFF",
465
+ c300="#6AA1FF",
466
+ c400="#4080FF",
467
+ c500="#165DFF", # Primary color
468
+ c600="#0E42D2",
469
+ c700="#0A2BA6",
470
+ c800="#061D79",
471
+ c900="#03114D",
472
+ c950="#020B33",
473
+ )
474
+
475
+ custom_css = """
476
+ .secondary-text {color: #999 !important;}
477
+ footer {visibility: hidden}
478
+ .env-warning {color: #dd5500 !important;}
479
+ .env-success {color: #559900 !important;}
480
+
481
+ /* Add dashed border to input-file class */
482
+ .input-file {
483
+ border: 1.2px dashed #165DFF !important;
484
+ border-radius: 6px !important;
485
+ }
486
+
487
+ .progress-bar-wrap {
488
+ border-radius: 8px !important;
489
+ }
490
+
491
+ .progress-bar {
492
+ border-radius: 8px !important;
493
+ }
494
+
495
+ .pdf-canvas canvas {
496
+ width: 100%;
497
+ }
498
+ """
499
+
500
+ demo_recaptcha = """
501
+ <script src="https://www.google.com/recaptcha/api.js?render=explicit" async defer></script>
502
+ <script type="text/javascript">
503
+ var onVerify = function(token) {
504
+ el=document.getElementById('verify').getElementsByTagName('textarea')[0];
505
+ el.value=token;
506
+ el.dispatchEvent(new Event('input'));
507
+ };
508
+ </script>
509
+ """
510
+
511
+ tech_details_string = f"""
512
+ <summary>Technical details</summary>
513
+ - GitHub: <a href="https://github.com/Byaidu/PDFMathTranslate">Byaidu/PDFMathTranslate</a><br>
514
+ - BabelDOC: <a href="https://github.com/funstory-ai/BabelDOC">funstory-ai/BabelDOC</a><br>
515
+ - GUI by: <a href="https://github.com/reycn">Rongxin</a><br>
516
+ - pdf2zh Version: {__version__} <br>
517
+ - BabelDOC Version: {babeldoc_version}
518
+ """
519
+ cancellation_event_map = {}
520
+
521
+
522
+ # The following code creates the GUI
523
+ with gr.Blocks(
524
+ title="PDFMathTranslate - PDF Translation with preserved formats",
525
+ theme=gr.themes.Default(
526
+ primary_hue=custom_blue, spacing_size="md", radius_size="lg"
527
+ ),
528
+ css=custom_css,
529
+ head=demo_recaptcha if flag_demo else "",
530
+ ) as demo:
531
+ gr.Markdown(
532
+ "# [PDFMathTranslate @ GitHub](https://github.com/Byaidu/PDFMathTranslate)"
533
+ )
534
+
535
+ with gr.Row():
536
+ with gr.Column(scale=1):
537
+ gr.Markdown("## File | < 5 MB" if flag_demo else "## File")
538
+ file_type = gr.Radio(
539
+ choices=["File", "Link"],
540
+ label="Type",
541
+ value="File",
542
+ )
543
+ file_input = gr.File(
544
+ label="File",
545
+ file_count="single",
546
+ file_types=[".pdf"],
547
+ type="filepath",
548
+ elem_classes=["input-file"],
549
+ )
550
+ link_input = gr.Textbox(
551
+ label="Link",
552
+ visible=False,
553
+ interactive=True,
554
+ )
555
+ gr.Markdown("## Option")
556
+ service = gr.Dropdown(
557
+ label="Service",
558
+ choices=enabled_services,
559
+ value=enabled_services[0],
560
+ )
561
+ envs = []
562
+ for i in range(3):
563
+ envs.append(
564
+ gr.Textbox(
565
+ visible=False,
566
+ interactive=True,
567
+ )
568
+ )
569
+ with gr.Row():
570
+ lang_from = gr.Dropdown(
571
+ label="Translate from",
572
+ choices=lang_map.keys(),
573
+ value=ConfigManager.get("PDF2ZH_LANG_FROM", "English"),
574
+ )
575
+ lang_to = gr.Dropdown(
576
+ label="Translate to",
577
+ choices=lang_map.keys(),
578
+ value=ConfigManager.get("PDF2ZH_LANG_TO", "Simplified Chinese"),
579
+ )
580
+ page_range = gr.Radio(
581
+ choices=page_map.keys(),
582
+ label="Pages",
583
+ value=list(page_map.keys())[0],
584
+ )
585
+
586
+ page_input = gr.Textbox(
587
+ label="Page range",
588
+ visible=False,
589
+ interactive=True,
590
+ )
591
+
592
+ with gr.Accordion("Open for More Experimental Options!", open=False):
593
+ gr.Markdown("#### Experimental")
594
+ threads = gr.Textbox(
595
+ label="number of threads", interactive=True, value="4"
596
+ )
597
+ skip_subset_fonts = gr.Checkbox(
598
+ label="Skip font subsetting", interactive=True, value=False
599
+ )
600
+ ignore_cache = gr.Checkbox(
601
+ label="Ignore cache", interactive=True, value=False
602
+ )
603
+ vfont = gr.Textbox(
604
+ label="Custom formula font regex (vfont)",
605
+ interactive=True,
606
+ value=ConfigManager.get("PDF2ZH_VFONT", ""),
607
+ )
608
+ prompt = gr.Textbox(
609
+ label="Custom Prompt for llm", interactive=True, visible=False
610
+ )
611
+ use_babeldoc = gr.Checkbox(
612
+ label="Use BabelDOC", interactive=True, value=False
613
+ )
614
+ envs.append(prompt)
615
+
616
+ def on_select_service(service, evt: gr.EventData):
617
+ translator = service_map[service]
618
+ _envs = []
619
+ for i in range(4):
620
+ _envs.append(gr.update(visible=False, value=""))
621
+ for i, env in enumerate(translator.envs.items()):
622
+ label = env[0]
623
+ value = ConfigManager.get_env_by_translatername(
624
+ translator, env[0], env[1]
625
+ )
626
+ visible = True
627
+ if hidden_gradio_details:
628
+ if (
629
+ "MODEL" not in str(label).upper()
630
+ and value
631
+ and hidden_gradio_details
632
+ ):
633
+ visible = False
634
+ # Hidden Keys From Gradio
635
+ if "API_KEY" in label.upper():
636
+ value = "***" # We use "***" Present Real API_KEY
637
+ _envs[i] = gr.update(
638
+ visible=visible,
639
+ label=label,
640
+ value=value,
641
+ )
642
+ _envs[-1] = gr.update(visible=translator.CustomPrompt)
643
+ return _envs
644
+
645
+ def on_select_filetype(file_type):
646
+ return (
647
+ gr.update(visible=file_type == "File"),
648
+ gr.update(visible=file_type == "Link"),
649
+ )
650
+
651
+ def on_select_page(choice):
652
+ if choice == "Others":
653
+ return gr.update(visible=True)
654
+ else:
655
+ return gr.update(visible=False)
656
+
657
+ def on_vfont_change(value):
658
+ ConfigManager.set("PDF2ZH_VFONT", value)
659
+ return value
660
+
661
+ output_title = gr.Markdown("## Translated", visible=False)
662
+ output_file_mono = gr.File(
663
+ label="Download Translation (Mono)", visible=False
664
+ )
665
+ output_file_dual = gr.File(
666
+ label="Download Translation (Dual)", visible=False
667
+ )
668
+ recaptcha_response = gr.Textbox(
669
+ label="reCAPTCHA Response", elem_id="verify", visible=False
670
+ )
671
+ recaptcha_box = gr.HTML('<div id="recaptcha-box"></div>')
672
+ translate_btn = gr.Button("Translate", variant="primary")
673
+ cancellation_btn = gr.Button("Cancel", variant="secondary")
674
+ tech_details_tog = gr.Markdown(
675
+ tech_details_string,
676
+ elem_classes=["secondary-text"],
677
+ )
678
+ page_range.select(on_select_page, page_range, page_input)
679
+ service.select(
680
+ on_select_service,
681
+ service,
682
+ envs,
683
+ )
684
+ vfont.change(on_vfont_change, inputs=vfont, outputs=None)
685
+ file_type.select(
686
+ on_select_filetype,
687
+ file_type,
688
+ [file_input, link_input],
689
+ js=(
690
+ f"""
691
+ (a,b)=>{{
692
+ try{{
693
+ grecaptcha.render('recaptcha-box',{{
694
+ 'sitekey':'{client_key}',
695
+ 'callback':'onVerify'
696
+ }});
697
+ }}catch(error){{}}
698
+ return [a];
699
+ }}
700
+ """
701
+ if flag_demo
702
+ else ""
703
+ ),
704
+ )
705
+
706
+ with gr.Column(scale=2):
707
+ gr.Markdown("## Preview")
708
+ preview = PDF(label="Document Preview", visible=True, height=2000)
709
+
710
+ # Event handlers
711
+ file_input.upload(
712
+ lambda x: x,
713
+ inputs=file_input,
714
+ outputs=preview,
715
+ js=(
716
+ f"""
717
+ (a,b)=>{{
718
+ try{{
719
+ grecaptcha.render('recaptcha-box',{{
720
+ 'sitekey':'{client_key}',
721
+ 'callback':'onVerify'
722
+ }});
723
+ }}catch(error){{}}
724
+ return [a];
725
+ }}
726
+ """
727
+ if flag_demo
728
+ else ""
729
+ ),
730
+ )
731
+
732
+ state = gr.State({"session_id": None})
733
+
734
+ translate_btn.click(
735
+ translate_file,
736
+ inputs=[
737
+ file_type,
738
+ file_input,
739
+ link_input,
740
+ service,
741
+ lang_from,
742
+ lang_to,
743
+ page_range,
744
+ page_input,
745
+ prompt,
746
+ threads,
747
+ skip_subset_fonts,
748
+ ignore_cache,
749
+ vfont,
750
+ use_babeldoc,
751
+ recaptcha_response,
752
+ state,
753
+ *envs,
754
+ ],
755
+ outputs=[
756
+ output_file_mono,
757
+ preview,
758
+ output_file_dual,
759
+ output_file_mono,
760
+ output_file_dual,
761
+ output_title,
762
+ ],
763
+ ).then(lambda: None, js="()=>{grecaptcha.reset()}" if flag_demo else "")
764
+
765
+ cancellation_btn.click(
766
+ stop_translate_file,
767
+ inputs=[state],
768
+ )
769
+
770
+
771
+ def parse_user_passwd(file_path: str) -> tuple:
772
+ """
773
+ Parse the user name and password from the file.
774
+
775
+ Inputs:
776
+ - file_path: The file path to read.
777
+ Outputs:
778
+ - tuple_list: The list of tuples of user name and password.
779
+ - content: The content of the file
780
+ """
781
+ tuple_list = []
782
+ content = ""
783
+ if not file_path:
784
+ return tuple_list, content
785
+ if len(file_path) == 2:
786
+ try:
787
+ with open(file_path[1], "r", encoding="utf-8") as file:
788
+ content = file.read()
789
+ except FileNotFoundError:
790
+ print(f"Error: File '{file_path[1]}' not found.")
791
+ try:
792
+ with open(file_path[0], "r", encoding="utf-8") as file:
793
+ tuple_list = [
794
+ tuple(line.strip().split(",")) for line in file if line.strip()
795
+ ]
796
+ except FileNotFoundError:
797
+ print(f"Error: File '{file_path[0]}' not found.")
798
+ return tuple_list, content
799
+
800
+
801
+ def setup_gui(
802
+ share: bool = False, auth_file: list = ["", ""], server_port=7860
803
+ ) -> None:
804
+ """
805
+ Setup the GUI with the given parameters.
806
+
807
+ Inputs:
808
+ - share: Whether to share the GUI.
809
+ - auth_file: The file path to read the user name and password.
810
+
811
+ Outputs:
812
+ - None
813
+ """
814
+ user_list, html = parse_user_passwd(auth_file)
815
+ if flag_demo:
816
+ demo.launch(server_name="0.0.0.0", max_file_size="5mb", inbrowser=True)
817
+ else:
818
+ if len(user_list) == 0:
819
+ try:
820
+ demo.launch(
821
+ server_name="0.0.0.0",
822
+ debug=True,
823
+ inbrowser=True,
824
+ share=share,
825
+ server_port=server_port,
826
+ )
827
+ except Exception:
828
+ print(
829
+ "Error launching GUI using 0.0.0.0.\nThis may be caused by global mode of proxy software."
830
+ )
831
+ try:
832
+ demo.launch(
833
+ server_name="127.0.0.1",
834
+ debug=True,
835
+ inbrowser=True,
836
+ share=share,
837
+ server_port=server_port,
838
+ )
839
+ except Exception:
840
+ print(
841
+ "Error launching GUI using 127.0.0.1.\nThis may be caused by global mode of proxy software."
842
+ )
843
+ demo.launch(
844
+ debug=True, inbrowser=True, share=True, server_port=server_port
845
+ )
846
+ else:
847
+ try:
848
+ demo.launch(
849
+ server_name="0.0.0.0",
850
+ debug=True,
851
+ inbrowser=True,
852
+ share=share,
853
+ auth=user_list,
854
+ auth_message=html,
855
+ server_port=server_port,
856
+ )
857
+ except Exception:
858
+ print(
859
+ "Error launching GUI using 0.0.0.0.\nThis may be caused by global mode of proxy software."
860
+ )
861
+ try:
862
+ demo.launch(
863
+ server_name="127.0.0.1",
864
+ debug=True,
865
+ inbrowser=True,
866
+ share=share,
867
+ auth=user_list,
868
+ auth_message=html,
869
+ server_port=server_port,
870
+ )
871
+ except Exception:
872
+ print(
873
+ "Error launching GUI using 127.0.0.1.\nThis may be caused by global mode of proxy software."
874
+ )
875
+ demo.launch(
876
+ debug=True,
877
+ inbrowser=True,
878
+ share=True,
879
+ auth=user_list,
880
+ auth_message=html,
881
+ server_port=server_port,
882
+ )
883
+
884
+
885
+ # For auto-reloading while developing
886
+ if __name__ == "__main__":
887
+ logging.basicConfig(level=logging.DEBUG)
888
+ setup_gui()
pdf2zh/high_level.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions that can be used for the most common use-cases for pdf2zh.six"""
2
+
3
+ import asyncio
4
+ import io
5
+ import os
6
+ import re
7
+ import sys
8
+ import tempfile
9
+ import logging
10
+ from asyncio import CancelledError
11
+ from pathlib import Path
12
+ from string import Template
13
+ from typing import Any, BinaryIO, List, Optional, Dict
14
+
15
+ import numpy as np
16
+ import requests
17
+ import tqdm
18
+ from pdfminer.pdfdocument import PDFDocument
19
+ from pdfminer.pdfexceptions import PDFValueError
20
+ from pdfminer.pdfinterp import PDFResourceManager
21
+ from pdfminer.pdfpage import PDFPage
22
+ from pdfminer.pdfparser import PDFParser
23
+ from pymupdf import Document, Font
24
+
25
+ from pdf2zh.converter import TranslateConverter
26
+ from pdf2zh.doclayout import OnnxModel
27
+ from pdf2zh.pdfinterp import PDFPageInterpreterEx
28
+
29
+ from pdf2zh.config import ConfigManager
30
+ from babeldoc.assets.assets import get_font_and_metadata
31
+
32
+ NOTO_NAME = "noto"
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ noto_list = [
37
+ "am", # Amharic
38
+ "ar", # Arabic
39
+ "bn", # Bengali
40
+ "bg", # Bulgarian
41
+ "chr", # Cherokee
42
+ "el", # Greek
43
+ "gu", # Gujarati
44
+ "iw", # Hebrew
45
+ "hi", # Hindi
46
+ "kn", # Kannada
47
+ "ml", # Malayalam
48
+ "mr", # Marathi
49
+ "ru", # Russian
50
+ "sr", # Serbian
51
+ "ta", # Tamil
52
+ "te", # Telugu
53
+ "th", # Thai
54
+ "ur", # Urdu
55
+ "uk", # Ukrainian
56
+ ]
57
+
58
+
59
+ def check_files(files: List[str]) -> List[str]:
60
+ files = [
61
+ f for f in files if not f.startswith("http://")
62
+ ] # exclude online files, http
63
+ files = [
64
+ f for f in files if not f.startswith("https://")
65
+ ] # exclude online files, https
66
+ missing_files = [file for file in files if not os.path.exists(file)]
67
+ return missing_files
68
+
69
+
70
+ def translate_patch(
71
+ inf: BinaryIO,
72
+ pages: Optional[list[int]] = None,
73
+ vfont: str = "",
74
+ vchar: str = "",
75
+ thread: int = 0,
76
+ doc_zh: Document = None,
77
+ lang_in: str = "",
78
+ lang_out: str = "",
79
+ service: str = "",
80
+ noto_name: str = "",
81
+ noto: Font = None,
82
+ callback: object = None,
83
+ cancellation_event: asyncio.Event = None,
84
+ model: OnnxModel = None,
85
+ envs: Dict = None,
86
+ prompt: Template = None,
87
+ ignore_cache: bool = False,
88
+ **kwarg: Any,
89
+ ) -> None:
90
+ rsrcmgr = PDFResourceManager()
91
+ layout = {}
92
+ device = TranslateConverter(
93
+ rsrcmgr,
94
+ vfont,
95
+ vchar,
96
+ thread,
97
+ layout,
98
+ lang_in,
99
+ lang_out,
100
+ service,
101
+ noto_name,
102
+ noto,
103
+ envs,
104
+ prompt,
105
+ ignore_cache,
106
+ )
107
+
108
+ assert device is not None
109
+ obj_patch = {}
110
+ interpreter = PDFPageInterpreterEx(rsrcmgr, device, obj_patch)
111
+ if pages:
112
+ total_pages = len(pages)
113
+ else:
114
+ total_pages = doc_zh.page_count
115
+
116
+ parser = PDFParser(inf)
117
+ doc = PDFDocument(parser)
118
+ with tqdm.tqdm(total=total_pages) as progress:
119
+ for pageno, page in enumerate(PDFPage.create_pages(doc)):
120
+ if cancellation_event and cancellation_event.is_set():
121
+ raise CancelledError("task cancelled")
122
+ if pages and (pageno not in pages):
123
+ continue
124
+ progress.update()
125
+ if callback:
126
+ callback(progress)
127
+ page.pageno = pageno
128
+ pix = doc_zh[page.pageno].get_pixmap()
129
+ image = np.frombuffer(pix.samples, np.uint8).reshape(
130
+ pix.height, pix.width, 3
131
+ )[:, :, ::-1]
132
+ page_layout = model.predict(image, imgsz=int(pix.height / 32) * 32)[0]
133
+ # kdtree 是不可能 kdtree 的,不如直接渲染成图片,用空间换时间
134
+ box = np.ones((pix.height, pix.width))
135
+ h, w = box.shape
136
+ vcls = ["abandon", "figure", "table", "isolate_formula", "formula_caption"]
137
+ for i, d in enumerate(page_layout.boxes):
138
+ if page_layout.names[int(d.cls)] not in vcls:
139
+ x0, y0, x1, y1 = d.xyxy.squeeze()
140
+ x0, y0, x1, y1 = (
141
+ np.clip(int(x0 - 1), 0, w - 1),
142
+ np.clip(int(h - y1 - 1), 0, h - 1),
143
+ np.clip(int(x1 + 1), 0, w - 1),
144
+ np.clip(int(h - y0 + 1), 0, h - 1),
145
+ )
146
+ box[y0:y1, x0:x1] = i + 2
147
+ for i, d in enumerate(page_layout.boxes):
148
+ if page_layout.names[int(d.cls)] in vcls:
149
+ x0, y0, x1, y1 = d.xyxy.squeeze()
150
+ x0, y0, x1, y1 = (
151
+ np.clip(int(x0 - 1), 0, w - 1),
152
+ np.clip(int(h - y1 - 1), 0, h - 1),
153
+ np.clip(int(x1 + 1), 0, w - 1),
154
+ np.clip(int(h - y0 + 1), 0, h - 1),
155
+ )
156
+ box[y0:y1, x0:x1] = 0
157
+ layout[page.pageno] = box
158
+ # 新建一个 xref 存放新指令流
159
+ page.page_xref = doc_zh.get_new_xref() # hack 插入页面的新 xref
160
+ doc_zh.update_object(page.page_xref, "<<>>")
161
+ doc_zh.update_stream(page.page_xref, b"")
162
+ doc_zh[page.pageno].set_contents(page.page_xref)
163
+ interpreter.process_page(page)
164
+
165
+ device.close()
166
+ return obj_patch
167
+
168
+
169
+ def translate_stream(
170
+ stream: bytes,
171
+ pages: Optional[list[int]] = None,
172
+ lang_in: str = "",
173
+ lang_out: str = "",
174
+ service: str = "",
175
+ thread: int = 0,
176
+ vfont: str = "",
177
+ vchar: str = "",
178
+ callback: object = None,
179
+ cancellation_event: asyncio.Event = None,
180
+ model: OnnxModel = None,
181
+ envs: Dict = None,
182
+ prompt: Template = None,
183
+ skip_subset_fonts: bool = False,
184
+ ignore_cache: bool = False,
185
+ **kwarg: Any,
186
+ ):
187
+ font_list = [("tiro", None)]
188
+
189
+ font_path = download_remote_fonts(lang_out.lower())
190
+ noto_name = NOTO_NAME
191
+ noto = Font(noto_name, font_path)
192
+ font_list.append((noto_name, font_path))
193
+
194
+ doc_en = Document(stream=stream)
195
+ stream = io.BytesIO()
196
+ doc_en.save(stream)
197
+ doc_zh = Document(stream=stream)
198
+ page_count = doc_zh.page_count
199
+ # font_list = [("GoNotoKurrent-Regular.ttf", font_path), ("tiro", None)]
200
+ font_id = {}
201
+ for page in doc_zh:
202
+ for font in font_list:
203
+ font_id[font[0]] = page.insert_font(font[0], font[1])
204
+ xreflen = doc_zh.xref_length()
205
+ for xref in range(1, xreflen):
206
+ for label in ["Resources/", ""]: # 可能是基于 xobj 的 res
207
+ try: # xref 读写可能出错
208
+ font_res = doc_zh.xref_get_key(xref, f"{label}Font")
209
+ target_key_prefix = f"{label}Font/"
210
+ if font_res[0] == "xref":
211
+ resource_xref_id = re.search("(\\d+) 0 R", font_res[1]).group(1)
212
+ xref = int(resource_xref_id)
213
+ font_res = ("dict", doc_zh.xref_object(xref))
214
+ target_key_prefix = ""
215
+
216
+ if font_res[0] == "dict":
217
+ for font in font_list:
218
+ target_key = f"{target_key_prefix}{font[0]}"
219
+ font_exist = doc_zh.xref_get_key(xref, target_key)
220
+ if font_exist[0] == "null":
221
+ doc_zh.xref_set_key(
222
+ xref,
223
+ target_key,
224
+ f"{font_id[font[0]]} 0 R",
225
+ )
226
+ except Exception:
227
+ pass
228
+
229
+ fp = io.BytesIO()
230
+
231
+ doc_zh.save(fp)
232
+ obj_patch: dict = translate_patch(fp, **locals())
233
+
234
+ for obj_id, ops_new in obj_patch.items():
235
+ # ops_old=doc_en.xref_stream(obj_id)
236
+ # print(obj_id)
237
+ # print(ops_old)
238
+ # print(ops_new.encode())
239
+ doc_zh.update_stream(obj_id, ops_new.encode())
240
+
241
+ doc_en.insert_file(doc_zh)
242
+ for id in range(page_count):
243
+ doc_en.move_page(page_count + id, id * 2 + 1)
244
+ if not skip_subset_fonts:
245
+ doc_zh.subset_fonts(fallback=True)
246
+ doc_en.subset_fonts(fallback=True)
247
+ return (
248
+ doc_zh.write(deflate=True, garbage=3, use_objstms=1),
249
+ doc_en.write(deflate=True, garbage=3, use_objstms=1),
250
+ )
251
+
252
+
253
+ def convert_to_pdfa(input_path, output_path):
254
+ """
255
+ Convert PDF to PDF/A format
256
+
257
+ Args:
258
+ input_path: Path to source PDF file
259
+ output_path: Path to save PDF/A file
260
+ """
261
+ from pikepdf import Dictionary, Name, Pdf
262
+
263
+ # Open the PDF file
264
+ pdf = Pdf.open(input_path)
265
+
266
+ # Add PDF/A conformance metadata
267
+ metadata = {
268
+ "pdfa_part": "2",
269
+ "pdfa_conformance": "B",
270
+ "title": pdf.docinfo.get("/Title", ""),
271
+ "author": pdf.docinfo.get("/Author", ""),
272
+ "creator": "PDF Math Translate",
273
+ }
274
+
275
+ with pdf.open_metadata() as meta:
276
+ meta.load_from_docinfo(pdf.docinfo)
277
+ meta["pdfaid:part"] = metadata["pdfa_part"]
278
+ meta["pdfaid:conformance"] = metadata["pdfa_conformance"]
279
+
280
+ # Create OutputIntent dictionary
281
+ output_intent = Dictionary(
282
+ {
283
+ "/Type": Name("/OutputIntent"),
284
+ "/S": Name("/GTS_PDFA1"),
285
+ "/OutputConditionIdentifier": "sRGB IEC61966-2.1",
286
+ "/RegistryName": "http://www.color.org",
287
+ "/Info": "sRGB IEC61966-2.1",
288
+ }
289
+ )
290
+
291
+ # Add output intent to PDF root
292
+ if "/OutputIntents" not in pdf.Root:
293
+ pdf.Root.OutputIntents = [output_intent]
294
+ else:
295
+ pdf.Root.OutputIntents.append(output_intent)
296
+
297
+ # Save as PDF/A
298
+ pdf.save(output_path, linearize=True)
299
+ pdf.close()
300
+
301
+
302
+ def translate(
303
+ files: list[str],
304
+ output: str = "",
305
+ pages: Optional[list[int]] = None,
306
+ lang_in: str = "",
307
+ lang_out: str = "",
308
+ service: str = "",
309
+ thread: int = 0,
310
+ vfont: str = "",
311
+ vchar: str = "",
312
+ callback: object = None,
313
+ compatible: bool = False,
314
+ cancellation_event: asyncio.Event = None,
315
+ model: OnnxModel = None,
316
+ envs: Dict = None,
317
+ prompt: Template = None,
318
+ skip_subset_fonts: bool = False,
319
+ ignore_cache: bool = False,
320
+ **kwarg: Any,
321
+ ):
322
+ if not files:
323
+ raise PDFValueError("No files to process.")
324
+
325
+ missing_files = check_files(files)
326
+
327
+ if missing_files:
328
+ print("The following files do not exist:", file=sys.stderr)
329
+ for file in missing_files:
330
+ print(f" {file}", file=sys.stderr)
331
+ raise PDFValueError("Some files do not exist.")
332
+
333
+ result_files = []
334
+
335
+ for file in files:
336
+ if type(file) is str and (
337
+ file.startswith("http://") or file.startswith("https://")
338
+ ):
339
+ print("Online files detected, downloading...")
340
+ try:
341
+ r = requests.get(file, allow_redirects=True)
342
+ if r.status_code == 200:
343
+ with tempfile.NamedTemporaryFile(
344
+ suffix=".pdf", delete=False
345
+ ) as tmp_file:
346
+ print(f"Writing the file: {file}...")
347
+ tmp_file.write(r.content)
348
+ file = tmp_file.name
349
+ else:
350
+ r.raise_for_status()
351
+ except Exception as e:
352
+ raise PDFValueError(
353
+ f"Errors occur in downloading the PDF file. Please check the link(s).\nError:\n{e}"
354
+ )
355
+ filename = os.path.splitext(os.path.basename(file))[0]
356
+
357
+ # If the commandline has specified converting to PDF/A format
358
+ # --compatible / -cp
359
+ if compatible:
360
+ with tempfile.NamedTemporaryFile(
361
+ suffix="-pdfa.pdf", delete=False
362
+ ) as tmp_pdfa:
363
+ print(f"Converting {file} to PDF/A format...")
364
+ convert_to_pdfa(file, tmp_pdfa.name)
365
+ doc_raw = open(tmp_pdfa.name, "rb")
366
+ os.unlink(tmp_pdfa.name)
367
+ else:
368
+ doc_raw = open(file, "rb")
369
+ s_raw = doc_raw.read()
370
+ doc_raw.close()
371
+
372
+ temp_dir = Path(tempfile.gettempdir())
373
+ file_path = Path(file)
374
+ try:
375
+ if file_path.exists() and file_path.resolve().is_relative_to(
376
+ temp_dir.resolve()
377
+ ):
378
+ file_path.unlink(missing_ok=True)
379
+ logger.debug(f"Cleaned temp file: {file_path}")
380
+ except Exception as e:
381
+ logger.warning(f"Failed to clean temp file {file_path}", exc_info=True)
382
+
383
+ s_mono, s_dual = translate_stream(
384
+ s_raw,
385
+ **locals(),
386
+ )
387
+ file_mono = Path(output) / f"{filename}-mono.pdf"
388
+ file_dual = Path(output) / f"{filename}-dual.pdf"
389
+ doc_mono = open(file_mono, "wb")
390
+ doc_dual = open(file_dual, "wb")
391
+ doc_mono.write(s_mono)
392
+ doc_dual.write(s_dual)
393
+ doc_mono.close()
394
+ doc_dual.close()
395
+ result_files.append((str(file_mono), str(file_dual)))
396
+
397
+ return result_files
398
+
399
+
400
+ def download_remote_fonts(lang: str):
401
+ lang = lang.lower()
402
+ LANG_NAME_MAP = {
403
+ **{la: "GoNotoKurrent-Regular.ttf" for la in noto_list},
404
+ **{
405
+ la: f"SourceHanSerif{region}-Regular.ttf"
406
+ for region, langs in {
407
+ "CN": ["zh-cn", "zh-hans", "zh"],
408
+ "TW": ["zh-tw", "zh-hant"],
409
+ "JP": ["ja"],
410
+ "KR": ["ko"],
411
+ }.items()
412
+ for la in langs
413
+ },
414
+ }
415
+ font_name = LANG_NAME_MAP.get(lang, "GoNotoKurrent-Regular.ttf")
416
+
417
+ # docker
418
+ font_path = ConfigManager.get("NOTO_FONT_PATH", Path("/app", font_name).as_posix())
419
+ if not Path(font_path).exists():
420
+ font_path, _ = get_font_and_metadata(font_name)
421
+ font_path = font_path.as_posix()
422
+
423
+ logger.info(f"use font: {font_path}")
424
+
425
+ return font_path
pdf2zh/mcp_server.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mcp.server import Server
2
+ from mcp.server.fastmcp import FastMCP, Context
3
+ from mcp.server.sse import SseServerTransport
4
+ from starlette.applications import Starlette
5
+ from starlette.requests import Request
6
+ from starlette.routing import Mount, Route
7
+ from pdf2zh import translate_stream
8
+ from pdf2zh.doclayout import ModelInstance
9
+ from pathlib import Path
10
+
11
+ import contextlib
12
+ import io
13
+ import os
14
+
15
+
16
+ def create_mcp_app() -> FastMCP:
17
+ mcp = FastMCP("pdf2zh")
18
+
19
+ @mcp.tool()
20
+ async def translate_pdf(
21
+ file: str, lang_in: str, lang_out: str, ctx: Context
22
+ ) -> str:
23
+ """
24
+ translate given pdf. Argument `file` is absolute path of input pdf,
25
+ `lang_in` and `lang_out` is translate from and to language, and
26
+ should be like google translate lang_code. `lang_in` can be `auto`
27
+ if you can't determine input language.
28
+ """
29
+
30
+ with open(file, "rb") as f:
31
+ file_bytes = f.read()
32
+ await ctx.log(level="info", message=f"start translate {file}")
33
+ with contextlib.redirect_stdout(io.StringIO()):
34
+ doc_mono_bytes, doc_dual_bytes = translate_stream(
35
+ file_bytes,
36
+ lang_in=lang_in,
37
+ lang_out=lang_out,
38
+ service="google",
39
+ model=ModelInstance.value,
40
+ thread=4,
41
+ )
42
+ await ctx.log(level="info", message="translate complete")
43
+ output_path = Path(os.path.dirname(file))
44
+ filename = os.path.splitext(os.path.basename(file))[0]
45
+ doc_mono = output_path / f"{filename}-mono.pdf"
46
+ doc_dual = output_path / f"{filename}-dual.pdf"
47
+ with open(doc_mono, "wb") as f:
48
+ f.write(doc_mono_bytes)
49
+ with open(doc_dual, "wb") as f:
50
+ f.write(doc_dual_bytes)
51
+ return f"""------------
52
+ translate complete
53
+ mono pdf file: {doc_mono.absolute()}
54
+ dual pdf file: {doc_dual.absolute()}
55
+ """
56
+
57
+ return mcp
58
+
59
+
60
+ def create_starlette_app(mcp_server: Server, *, debug: bool = False) -> Starlette:
61
+ sse = SseServerTransport("/messages/")
62
+
63
+ async def handle_sse(request: Request) -> None:
64
+ async with sse.connect_sse(request.scope, request.receive, request._send) as (
65
+ read_stream,
66
+ write_stream,
67
+ ):
68
+ await mcp_server.run(
69
+ read_stream, write_stream, mcp_server.create_initialization_options()
70
+ )
71
+
72
+ return Starlette(
73
+ debug=debug,
74
+ routes=[
75
+ Route("/sse", endpoint=handle_sse),
76
+ Mount("/messages/", app=sse.handle_post_message),
77
+ ],
78
+ )
79
+
80
+
81
+ if __name__ == "__main__":
82
+ import argparse
83
+
84
+ mcp = create_mcp_app()
85
+ mcp_server = mcp._mcp_server
86
+ parser = argparse.ArgumentParser(description="Run MCP SSE-based PDF2ZH server")
87
+
88
+ parser.add_argument(
89
+ "--sse",
90
+ default=False,
91
+ action="store_true",
92
+ help="Run the server with SSE transport or STDIO",
93
+ )
94
+ parser.add_argument(
95
+ "--host", type=str, default="127.0.0.1", required=False, help="Host to bind"
96
+ )
97
+ parser.add_argument(
98
+ "--port", type=int, default=3001, required=False, help="Port to bind"
99
+ )
100
+
101
+ args = parser.parse_args()
102
+ if args.sse and args.host and args.port:
103
+ import uvicorn
104
+
105
+ starlette_app = create_starlette_app(mcp_server, debug=True)
106
+ uvicorn.run(starlette_app, host=args.host, port=args.port)
107
+ else:
108
+ mcp.run()