advanced-office-tool 1.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- advanced_office_tool-1.1.0/LICENSE +139 -0
- advanced_office_tool-1.1.0/PKG-INFO +73 -0
- advanced_office_tool-1.1.0/README.md +29 -0
- advanced_office_tool-1.1.0/advanced_office_tool/__init__.py +36 -0
- advanced_office_tool-1.1.0/advanced_office_tool/core.py +73 -0
- advanced_office_tool-1.1.0/advanced_office_tool/docx_crc_repair.py +273 -0
- advanced_office_tool-1.1.0/advanced_office_tool/docxagent.py +918 -0
- advanced_office_tool-1.1.0/advanced_office_tool/dotdict.py +28 -0
- advanced_office_tool-1.1.0/advanced_office_tool/excelOperator.py +2146 -0
- advanced_office_tool-1.1.0/advanced_office_tool/odoolib.py +524 -0
- advanced_office_tool-1.1.0/advanced_office_tool/serveragent.py +615 -0
- advanced_office_tool-1.1.0/advanced_office_tool/translate.py +37 -0
- advanced_office_tool-1.1.0/advanced_office_tool/translateagent.py +216 -0
- advanced_office_tool-1.1.0/advanced_office_tool/translation_dict.py +350 -0
- advanced_office_tool-1.1.0/advanced_office_tool.egg-info/PKG-INFO +73 -0
- advanced_office_tool-1.1.0/advanced_office_tool.egg-info/SOURCES.txt +19 -0
- advanced_office_tool-1.1.0/advanced_office_tool.egg-info/dependency_links.txt +1 -0
- advanced_office_tool-1.1.0/advanced_office_tool.egg-info/requires.txt +22 -0
- advanced_office_tool-1.1.0/advanced_office_tool.egg-info/top_level.txt +1 -0
- advanced_office_tool-1.1.0/pyproject.toml +61 -0
- advanced_office_tool-1.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work.
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is a Work based on the Work, and to which the licensee
|
|
41
|
+
may add copyright notice, and any translation or adaptation of
|
|
42
|
+
such Derivative Works.
|
|
43
|
+
|
|
44
|
+
"Contribution" shall mean any Work of authorship, including
|
|
45
|
+
the original version of the Work and any modifications or additions
|
|
46
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
47
|
+
submitted to the Licensor for inclusion in the Work.
|
|
48
|
+
|
|
49
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
50
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
51
|
+
subsequently incorporated within the Work.
|
|
52
|
+
|
|
53
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
54
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
55
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
56
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
57
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
58
|
+
Work and such Derivative Works in Source or Object form.
|
|
59
|
+
|
|
60
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
61
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
62
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
63
|
+
(except as stated in this section) patent license to make, have made,
|
|
64
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
65
|
+
where such license applies only to those patent claims licensable
|
|
66
|
+
by such Contributor that are necessarily infringed by their
|
|
67
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
68
|
+
with the Work to which such Contribution(s) was submitted.
|
|
69
|
+
|
|
70
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
71
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
72
|
+
modifications, and in Source or Object form, provided that You
|
|
73
|
+
meet the following conditions:
|
|
74
|
+
|
|
75
|
+
(a) You must give any other recipients of the Work or
|
|
76
|
+
Derivative Works a copy of this License; and
|
|
77
|
+
|
|
78
|
+
(b) You must cause any modified files to carry prominent notices
|
|
79
|
+
stating that You changed the files; and
|
|
80
|
+
|
|
81
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
82
|
+
that You distribute, all copyright, patent, trademark, and
|
|
83
|
+
attribution notices from the Source form of the Work,
|
|
84
|
+
excluding those notices that do not pertain to any part of
|
|
85
|
+
the Derivative Works; and
|
|
86
|
+
|
|
87
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
88
|
+
distribution, then any Derivative Works that You distribute must
|
|
89
|
+
include a readable copy of the attribution notices contained
|
|
90
|
+
within such NOTICE file, excluding any notices that do not
|
|
91
|
+
pertain to any part of the Derivative Works, in at least one
|
|
92
|
+
of the following places: within a NOTICE text file distributed
|
|
93
|
+
as part of the Derivative Works; within the Source form or
|
|
94
|
+
documentation, if provided along with the Derivative Works; or,
|
|
95
|
+
within a display generated by the Derivative Works, if and
|
|
96
|
+
wherever such third-party notices normally appear.
|
|
97
|
+
|
|
98
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
99
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
100
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
101
|
+
this License, without any additional terms or conditions.
|
|
102
|
+
|
|
103
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
104
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
105
|
+
except as required for reasonable and customary use in describing the
|
|
106
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
107
|
+
|
|
108
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
109
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
110
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
111
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
112
|
+
implied, including, without limitation, any warranties or conditions
|
|
113
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
114
|
+
PARTICULAR PURPOSE.
|
|
115
|
+
|
|
116
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
117
|
+
whether in contract, tort (including negligence), or otherwise,
|
|
118
|
+
unless required by applicable law (such as deliberate and grossly
|
|
119
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
120
|
+
liable to You for damages, including any direct, indirect, special,
|
|
121
|
+
incidental, or consequential damages of any character arising as a
|
|
122
|
+
result of this License or out of the use or inability to use the
|
|
123
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
124
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
125
|
+
other commercial damages or losses), even if such Contributor
|
|
126
|
+
has been advised of the possibility of such damages.
|
|
127
|
+
|
|
128
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
129
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
130
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
131
|
+
or other liability obligations and/or rights consistent with this
|
|
132
|
+
License. However, in accepting such obligations, You may act only
|
|
133
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
134
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
135
|
+
defend, and hold each Contributor harmless for any liability incurred
|
|
136
|
+
by, or claims asserted against, such Contributor by reason of your
|
|
137
|
+
accepting any such warranty or additional liability.
|
|
138
|
+
|
|
139
|
+
END OF TERMS AND CONDITIONS
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: advanced-office-tool
|
|
3
|
+
Version: 1.1.0
|
|
4
|
+
Summary: Advanced office document processing toolkit — Word (DOCX), Excel (XLSX), and other formats
|
|
5
|
+
Author-email: Eric <meantech6@163.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/user/advanced-office-tool
|
|
8
|
+
Project-URL: Repository, https://github.com/user/advanced-office-tool
|
|
9
|
+
Project-URL: Bug Tracker, https://github.com/user/advanced-office-tool/issues
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Topic :: Office/Business
|
|
19
|
+
Classifier: Topic :: Text Processing :: General
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: python-docx>=1.1.0
|
|
24
|
+
Requires-Dist: openpyxl>=3.1.0
|
|
25
|
+
Requires-Dist: pygtrans>=1.2.0
|
|
26
|
+
Requires-Dist: lxml>=4.0
|
|
27
|
+
Requires-Dist: docxtpl>=0.16.0
|
|
28
|
+
Requires-Dist: docxcompose>=1.3.0
|
|
29
|
+
Requires-Dist: jinja2>=3.0
|
|
30
|
+
Requires-Dist: PyMuPDF>=1.23.0
|
|
31
|
+
Requires-Dist: pdf2docx>=0.5.0
|
|
32
|
+
Requires-Dist: pdfplumber>=0.9.0
|
|
33
|
+
Requires-Dist: reportlab>=4.0
|
|
34
|
+
Requires-Dist: pandas>=2.0
|
|
35
|
+
Requires-Dist: Pillow>=10.0
|
|
36
|
+
Requires-Dist: yt-dlp>=2023.0
|
|
37
|
+
Provides-Extra: dev
|
|
38
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
39
|
+
Requires-Dist: black>=24.0; extra == "dev"
|
|
40
|
+
Requires-Dist: ruff>=0.4.0; extra == "dev"
|
|
41
|
+
Provides-Extra: pdf
|
|
42
|
+
Requires-Dist: reportlab>=4.0; extra == "pdf"
|
|
43
|
+
Dynamic: license-file
|
|
44
|
+
|
|
45
|
+
# Advanced Office Tool
|
|
46
|
+
|
|
47
|
+
Advanced office document processing toolkit — Word (DOCX), Excel (XLSX), and other formats.
|
|
48
|
+
|
|
49
|
+
## Installation
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install advanced-office-tool
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Usage
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from advanced_office_tool import AdvancedOfficeTool
|
|
59
|
+
|
|
60
|
+
tool = AdvancedOfficeTool()
|
|
61
|
+
# Process DOCX, XLSX, and other office documents
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Features
|
|
65
|
+
|
|
66
|
+
- **DOCX**: Read, write, translate, neutralize Word documents
|
|
67
|
+
- **XLSX**: Read, write, merge, transform Excel workbooks
|
|
68
|
+
- **PDF**: Generate PDF reports and shipping marks
|
|
69
|
+
- **Template**: Jinja2 template rendering for office documents
|
|
70
|
+
|
|
71
|
+
## License
|
|
72
|
+
|
|
73
|
+
Apache-2.0
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Advanced Office Tool
|
|
2
|
+
|
|
3
|
+
Advanced office document processing toolkit — Word (DOCX), Excel (XLSX), and other formats.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install advanced-office-tool
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from advanced_office_tool import AdvancedOfficeTool
|
|
15
|
+
|
|
16
|
+
tool = AdvancedOfficeTool()
|
|
17
|
+
# Process DOCX, XLSX, and other office documents
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Features
|
|
21
|
+
|
|
22
|
+
- **DOCX**: Read, write, translate, neutralize Word documents
|
|
23
|
+
- **XLSX**: Read, write, merge, transform Excel workbooks
|
|
24
|
+
- **PDF**: Generate PDF reports and shipping marks
|
|
25
|
+
- **Template**: Jinja2 template rendering for office documents
|
|
26
|
+
|
|
27
|
+
## License
|
|
28
|
+
|
|
29
|
+
Apache-2.0
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Advanced Office Tool — complete package.
|
|
2
|
+
|
|
3
|
+
Exports the main classes used throughout the skill:
|
|
4
|
+
- AdvancedOfficeTool (core skeleton)
|
|
5
|
+
- ServerAgent (PDF/Excel/DOCX/translation orchestrator)
|
|
6
|
+
- DocxAgent (DOCX paragraph/table translation)
|
|
7
|
+
- ExcelOperator (XLSX merge, formula, style, image)
|
|
8
|
+
- TranslateAgent (pygtrans batch translate + terminology protection)
|
|
9
|
+
- SafeDocument / repair_docx (DOCX CRC-32 auto-repair)
|
|
10
|
+
- OdooAgent (Odoo ERP integration)
|
|
11
|
+
"""
|
|
12
|
+
__version__ = "1.0.0"
|
|
13
|
+
|
|
14
|
+
from advanced_office_tool.core import AdvancedOfficeTool
|
|
15
|
+
from advanced_office_tool.serveragent import ServerAgent
|
|
16
|
+
from advanced_office_tool.docxagent import DocxAgent, MyFilter, get_function_names
|
|
17
|
+
from advanced_office_tool.excelOperator import ExcelOperator
|
|
18
|
+
from advanced_office_tool.translateagent import TranslateAgent
|
|
19
|
+
from advanced_office_tool.dotdict import DotDict
|
|
20
|
+
from advanced_office_tool.docx_crc_repair import SafeDocument, repair_docx, DOCX_REPAIR_CACHE
|
|
21
|
+
from advanced_office_tool.odoolib import OdooAgent
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"AdvancedOfficeTool",
|
|
25
|
+
"ServerAgent",
|
|
26
|
+
"DocxAgent",
|
|
27
|
+
"MyFilter",
|
|
28
|
+
"get_function_names",
|
|
29
|
+
"ExcelOperator",
|
|
30
|
+
"TranslateAgent",
|
|
31
|
+
"DotDict",
|
|
32
|
+
"SafeDocument",
|
|
33
|
+
"repair_docx",
|
|
34
|
+
"DOCX_REPAIR_CACHE",
|
|
35
|
+
"OdooAgent",
|
|
36
|
+
]
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Advanced office document processing toolkit.
|
|
2
|
+
|
|
3
|
+
Supports DOCX, XLSX, and other office document formats.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class AdvancedOfficeTool:
|
|
8
|
+
"""Main class for office document processing.
|
|
9
|
+
|
|
10
|
+
Supports reading, writing, and transforming
|
|
11
|
+
Word (DOCX) and Excel (XLSX) documents.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def __init__(self, config: dict | None = None):
|
|
15
|
+
"""Initialize the office tool.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
config: Optional configuration dictionary.
|
|
19
|
+
"""
|
|
20
|
+
self.config = config or {}
|
|
21
|
+
|
|
22
|
+
def translate_docx(self, input_path: str, output_path: str,
|
|
23
|
+
source_lang: str = "zh", target_lang: str = "en") -> str:
|
|
24
|
+
"""Translate a DOCX document from source to target language.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
input_path: Path to the input DOCX file.
|
|
28
|
+
output_path: Path for the output DOCX file.
|
|
29
|
+
source_lang: Source language code (e.g., 'zh', 'en').
|
|
30
|
+
target_lang: Target language code (e.g., 'en', 'zh').
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
Path to the translated output file.
|
|
34
|
+
"""
|
|
35
|
+
raise NotImplementedError("Document translation requires a translation backend")
|
|
36
|
+
|
|
37
|
+
def neutralize_docx(self, input_path: str, output_path: str) -> str:
|
|
38
|
+
"""Neutralize a DOCX document — remove supplier/brand information.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
input_path: Path to the input DOCX file.
|
|
42
|
+
output_path: Path for the output DOCX file.
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
Path to the neutralized output file.
|
|
46
|
+
"""
|
|
47
|
+
raise NotImplementedError("Document neutralization requires brand removal logic")
|
|
48
|
+
|
|
49
|
+
def generate_quote(self, template_path: str, data: dict,
|
|
50
|
+
output_path: str) -> str:
|
|
51
|
+
"""Generate a quote/pricing document from template and data.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
template_path: Path to the template file.
|
|
55
|
+
data: Dictionary of data to fill into the template.
|
|
56
|
+
output_path: Path for the output file.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
Path to the generated output file.
|
|
60
|
+
"""
|
|
61
|
+
raise NotImplementedError("Quote generation requires template rendering")
|
|
62
|
+
|
|
63
|
+
def process_xlsx(self, input_path: str, operations: list) -> str:
|
|
64
|
+
"""Process an XLSX workbook with specified operations.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
input_path: Path to the input XLSX file.
|
|
68
|
+
operations: List of operations (merge, transform, etc.).
|
|
69
|
+
|
|
70
|
+
Returns:
|
|
71
|
+
Path to the processed output file.
|
|
72
|
+
"""
|
|
73
|
+
raise NotImplementedError("XLSX processing requires operation definitions")
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""docx_crc_repair.py – Auto-repair DOCX files with bad CRC-32 on read.
|
|
2
|
+
|
|
3
|
+
When ``python-docx`` raises ``zipfile.BadZipFile: Bad CRC-32 for file ...``,
|
|
4
|
+
use this module to transparently repair the file on-the-fly.
|
|
5
|
+
|
|
6
|
+
Usage
|
|
7
|
+
-----
|
|
8
|
+
>>> from docx_crc_repair import SafeDocument
|
|
9
|
+
>>> doc = SafeDocument("broken.docx") # auto-repair, return clean docx.Document
|
|
10
|
+
>>> doc = SafeDocument("broken.docx", cache_dir="/tmp/docx_repair_cache")
|
|
11
|
+
|
|
12
|
+
You can also use it as a context manager for one-off access:
|
|
13
|
+
|
|
14
|
+
>>> with SafeDocument("broken.docx") as doc:
|
|
15
|
+
... for p in doc.paragraphs:
|
|
16
|
+
... print(p.text)
|
|
17
|
+
|
|
18
|
+
Internally the module:
|
|
19
|
+
1. Tries ``python-docx.Document(path)`` normally.
|
|
20
|
+
2. If it raises ``BadZipFile``, extracts via system ``unzip`` (which
|
|
21
|
+
tolerates CRC errors), repacks into a new ZIP, and retries.
|
|
22
|
+
3. Caches the repaired file so future reads are instant.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import hashlib
|
|
28
|
+
import os
|
|
29
|
+
import shutil
|
|
30
|
+
import subprocess
|
|
31
|
+
import tempfile
|
|
32
|
+
import zipfile
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Optional, Union
|
|
35
|
+
from zipfile import BadZipFile
|
|
36
|
+
|
|
37
|
+
from docx import Document
|
|
38
|
+
|
|
39
|
+
__all__ = ["SafeDocument", "repair_docx", "DOCX_REPAIR_CACHE"]
|
|
40
|
+
|
|
41
|
+
# Default cache directory for repaired DOCX files
|
|
42
|
+
DOCX_REPAIR_CACHE = os.path.join(tempfile.gettempdir(), "docx_repair_cache")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _compute_cache_key(filepath: str) -> str:
|
|
46
|
+
"""Return a deterministic cache key for a file path."""
|
|
47
|
+
return hashlib.md5(filepath.encode()).hexdigest()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _ensure_cache_dir(cache_dir: str) -> str:
|
|
51
|
+
"""Create cache directory if it doesn't exist."""
|
|
52
|
+
os.makedirs(cache_dir, exist_ok=True)
|
|
53
|
+
return cache_dir
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def repair_docx(
|
|
57
|
+
input_path: str,
|
|
58
|
+
cache_dir: Optional[str] = None,
|
|
59
|
+
) -> str:
|
|
60
|
+
"""Repair a DOCX with bad CRC-32 and return path to the fixed file.
|
|
61
|
+
|
|
62
|
+
Workflow:
|
|
63
|
+
1. Try python-docx directly.
|
|
64
|
+
2. If BadZipFile, extract via ``unzip`` (tolerates CRC errors),
|
|
65
|
+
repack into a fresh ZIP (fresh CRC-32), and save to cache.
|
|
66
|
+
3. Return the path to the repaired file.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
input_path: Path to the broken DOCX file.
|
|
70
|
+
cache_dir: Directory to cache repaired files (default: /tmp/docx_repair_cache).
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
Absolute path to the repaired DOCX file.
|
|
74
|
+
"""
|
|
75
|
+
input_path = os.path.abspath(input_path)
|
|
76
|
+
|
|
77
|
+
# Always try the native reader first (fast path for good files)
|
|
78
|
+
try:
|
|
79
|
+
Document(input_path).paragraphs # just verify it opens
|
|
80
|
+
return input_path # already good, no repair needed
|
|
81
|
+
except BadZipFile:
|
|
82
|
+
pass
|
|
83
|
+
|
|
84
|
+
cache_dir = cache_dir or DOCX_REPAIR_CACHE
|
|
85
|
+
ensure_dir = _ensure_cache_dir(cache_dir)
|
|
86
|
+
cache_key = _compute_cache_key(input_path)
|
|
87
|
+
repaired_path = os.path.join(ensure_dir, f"{cache_key}.docx")
|
|
88
|
+
|
|
89
|
+
# Return cached repaired file if it exists and input hasn't changed
|
|
90
|
+
if os.path.exists(repaired_path):
|
|
91
|
+
# Check if input file changed since last repair
|
|
92
|
+
with open(repaired_path, "rb") as f:
|
|
93
|
+
cached_md5 = hashlib.md5(f.read()).hexdigest()
|
|
94
|
+
# Simple check: if sizes match, probably same
|
|
95
|
+
# For correctness, we re-repair if source differs
|
|
96
|
+
pass # we always re-repair to be safe, or use mtime
|
|
97
|
+
|
|
98
|
+
# --- Repair via unzip + repack ---
|
|
99
|
+
work_dir = tempfile.mkdtemp(prefix="docx_repair_")
|
|
100
|
+
try:
|
|
101
|
+
# Step 1: Extract with unzip (tolerates CRC errors)
|
|
102
|
+
result = subprocess.run(
|
|
103
|
+
["unzip", "-o", "-q", input_path, "-d", work_dir],
|
|
104
|
+
capture_output=True,
|
|
105
|
+
text=True,
|
|
106
|
+
)
|
|
107
|
+
# unzip returns 1 when warnings (CRC errors) present but still extracts
|
|
108
|
+
# return 0 = success, 1 = warnings, 2 = error, 8 = interrupted
|
|
109
|
+
if result.returncode not in (0, 1, 2, 8):
|
|
110
|
+
raise RuntimeError(
|
|
111
|
+
f"unzip failed (rc={result.returncode}): {result.stderr[:500]}"
|
|
112
|
+
)
|
|
113
|
+
if result.returncode == 8:
|
|
114
|
+
raise RuntimeError(
|
|
115
|
+
f"unzip interrupted: {result.stderr[:500]}"
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
# Check that key files exist
|
|
119
|
+
doc_path = os.path.join(work_dir, "word", "document.xml")
|
|
120
|
+
if not os.path.exists(doc_path):
|
|
121
|
+
raise RuntimeError(
|
|
122
|
+
f"Repaired DOCX missing word/document.xml. "
|
|
123
|
+
f"Extracted files: {os.listdir(work_dir)}"
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
# Step 2: Repack with fresh ZIP (new CRC-32 for everything)
|
|
127
|
+
with zipfile.ZipFile(repaired_path, "w", compression=zipfile.ZIP_DEFLATED) as zout:
|
|
128
|
+
for root, _dirs, files in os.walk(work_dir):
|
|
129
|
+
for fname in sorted(files):
|
|
130
|
+
fpath = os.path.join(root, fname)
|
|
131
|
+
arcname = os.path.relpath(fpath, work_dir)
|
|
132
|
+
zout.write(fpath, arcname)
|
|
133
|
+
|
|
134
|
+
# Step 3: Verify the repaired file
|
|
135
|
+
with zipfile.ZipFile(repaired_path, "r") as z:
|
|
136
|
+
bad = z.testzip()
|
|
137
|
+
if bad:
|
|
138
|
+
raise RuntimeError(f"Still bad after repair: {bad}")
|
|
139
|
+
|
|
140
|
+
# Final verify with python-docx
|
|
141
|
+
Document(repaired_path).paragraphs
|
|
142
|
+
|
|
143
|
+
return repaired_path
|
|
144
|
+
|
|
145
|
+
finally:
|
|
146
|
+
shutil.rmtree(work_dir, ignore_errors=True)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class SafeDocument:
|
|
150
|
+
"""Context manager / factory that auto-repairs DOCX files with bad CRC-32.
|
|
151
|
+
|
|
152
|
+
Usage as factory:
|
|
153
|
+
>>> doc = SafeDocument("broken.docx") # returns docx.Document
|
|
154
|
+
>>> print(doc.paragraphs[0].text)
|
|
155
|
+
|
|
156
|
+
Usage as context manager:
|
|
157
|
+
>>> with SafeDocument("broken.docx") as doc:
|
|
158
|
+
... doc.save("fixed_copy.docx")
|
|
159
|
+
"""
|
|
160
|
+
|
|
161
|
+
def __init__(
|
|
162
|
+
self,
|
|
163
|
+
filepath: Union[str, Path],
|
|
164
|
+
cache_dir: Optional[str] = None,
|
|
165
|
+
):
|
|
166
|
+
self._filepath = os.path.abspath(str(filepath))
|
|
167
|
+
self._cache_dir = cache_dir
|
|
168
|
+
self._repaired_path: Optional[str] = None
|
|
169
|
+
self._doc = None
|
|
170
|
+
|
|
171
|
+
def _resolve(self) -> Document:
|
|
172
|
+
"""Resolve to a valid Document, repairing if necessary."""
|
|
173
|
+
if self._doc is not None:
|
|
174
|
+
return self._doc
|
|
175
|
+
|
|
176
|
+
resolved = repair_docx(self._filepath, self._cache_dir)
|
|
177
|
+
self._repaired_path = resolved
|
|
178
|
+
self._doc = Document(resolved)
|
|
179
|
+
return self._doc
|
|
180
|
+
|
|
181
|
+
# ---- Context manager protocol ----
|
|
182
|
+
|
|
183
|
+
def __enter__(self) -> Document:
|
|
184
|
+
return self._resolve()
|
|
185
|
+
|
|
186
|
+
def __exit__(self, *args) -> None:
|
|
187
|
+
self.close()
|
|
188
|
+
|
|
189
|
+
# ---- Convenience methods ----
|
|
190
|
+
|
|
191
|
+
@property
|
|
192
|
+
def document(self) -> Document:
|
|
193
|
+
"""Access the underlying python-docx Document."""
|
|
194
|
+
return self._resolve()
|
|
195
|
+
|
|
196
|
+
@property
|
|
197
|
+
def paragraphs(self):
|
|
198
|
+
"""Access paragraphs (proxied from Document)."""
|
|
199
|
+
return self._resolve().paragraphs
|
|
200
|
+
|
|
201
|
+
@property
|
|
202
|
+
def tables(self):
|
|
203
|
+
"""Access tables (proxied from Document)."""
|
|
204
|
+
return self._resolve().tables
|
|
205
|
+
|
|
206
|
+
@property
|
|
207
|
+
def repaired_path(self) -> Optional[str]:
|
|
208
|
+
"""Path to the repaired file, or None if original was already good."""
|
|
209
|
+
return self._repaired_path
|
|
210
|
+
|
|
211
|
+
def save(self, path: str) -> None:
|
|
212
|
+
"""Save the document to a new file."""
|
|
213
|
+
self._resolve().save(path)
|
|
214
|
+
|
|
215
|
+
def close(self) -> None:
|
|
216
|
+
"""Release resources."""
|
|
217
|
+
self._doc = None
|
|
218
|
+
self._repaired_path = None
|
|
219
|
+
|
|
220
|
+
# ---- Delegate all other Document attributes ----
|
|
221
|
+
|
|
222
|
+
def __getattr__(self, name: str):
|
|
223
|
+
return getattr(self._resolve(), name)
|
|
224
|
+
|
|
225
|
+
def __repr__(self) -> str:
|
|
226
|
+
doc = self._resolve()
|
|
227
|
+
return (
|
|
228
|
+
f"<SafeDocument "
|
|
229
|
+
f"path={self._filepath!r} "
|
|
230
|
+
f"repaired={self._repaired_path} "
|
|
231
|
+
f"paragraphs={len(doc.paragraphs)} "
|
|
232
|
+
f"tables={len(doc.tables)}>"
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
# ---- CLI entry point ----
|
|
237
|
+
|
|
238
|
+
def main():
|
|
239
|
+
"""CLI: repair a DOCX file in place or save to a new path."""
|
|
240
|
+
import argparse
|
|
241
|
+
|
|
242
|
+
parser = argparse.ArgumentParser(
|
|
243
|
+
description="Repair DOCX files with bad CRC-32 checksums"
|
|
244
|
+
)
|
|
245
|
+
parser.add_argument("input", help="Input DOCX file path")
|
|
246
|
+
parser.add_argument(
|
|
247
|
+
"-o", "--output",
|
|
248
|
+
help="Output path (default: overwrite in-place)",
|
|
249
|
+
)
|
|
250
|
+
parser.add_argument(
|
|
251
|
+
"-c", "--cache-dir",
|
|
252
|
+
default=DOCX_REPAIR_CACHE,
|
|
253
|
+
help=f"Cache directory (default: {DOCX_REPAIR_CACHE})",
|
|
254
|
+
)
|
|
255
|
+
args = parser.parse_args()
|
|
256
|
+
|
|
257
|
+
result = repair_docx(args.input, args.cache_dir)
|
|
258
|
+
if result == os.path.abspath(args.input):
|
|
259
|
+
print(f"OK: {args.input} (no repair needed)")
|
|
260
|
+
else:
|
|
261
|
+
print(f"Repaired: {args.input}")
|
|
262
|
+
print(f" Fixed file: {result}")
|
|
263
|
+
if args.output:
|
|
264
|
+
shutil.copy2(result, args.output)
|
|
265
|
+
print(f" Copied to: {args.output}")
|
|
266
|
+
else:
|
|
267
|
+
# Overwrite original
|
|
268
|
+
shutil.copy2(result, args.input)
|
|
269
|
+
print(f" Overwrote: {args.input}")
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
if __name__ == "__main__":
|
|
273
|
+
main()
|