wolfdocx-docx 0.1.0__py3-none-any.whl
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.
- wolfdocx_docx/THIRD_PARTY_NOTICES.txt +26 -0
- wolfdocx_docx/__init__.py +25 -0
- wolfdocx_docx/agent.py +292 -0
- wolfdocx_docx/document.py +223 -0
- wolfdocx_docx/shared.py +143 -0
- wolfdocx_docx/table.py +274 -0
- wolfdocx_docx/text.py +388 -0
- wolfdocx_docx-0.1.0.dist-info/METADATA +295 -0
- wolfdocx_docx-0.1.0.dist-info/RECORD +12 -0
- wolfdocx_docx-0.1.0.dist-info/WHEEL +4 -0
- wolfdocx_docx-0.1.0.dist-info/licenses/LICENSE +21 -0
- wolfdocx_docx-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.txt +26 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
python-docx v1.2.0
|
|
2
|
+
Source: https://github.com/python-openxml/python-docx
|
|
3
|
+
Commit: e45454602b53e8e572b179ccf1c91093ec9f4ed7
|
|
4
|
+
|
|
5
|
+
Portions of wolfdocx_docx/shared.py are derived from docx/shared.py.
|
|
6
|
+
|
|
7
|
+
The MIT License (MIT)
|
|
8
|
+
Copyright (c) 2013 Steve Canny, https://github.com/scanny
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in
|
|
18
|
+
all copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
26
|
+
THE SOFTWARE.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Opt-in python-docx compatible import alias over the native WolfDocx engine.
|
|
2
|
+
|
|
3
|
+
Use ``import wolfdocx_docx as docx``. Documents are edited through
|
|
4
|
+
``wolfdocx.builder.DocumentBuilder`` and saved through the engine's verified session
|
|
5
|
+
publication; python-docx is never imported. Names python-docx offers that are absent
|
|
6
|
+
here are not implemented.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
from typing import IO
|
|
13
|
+
|
|
14
|
+
from wolfdocx_docx.document import Document as _Document
|
|
15
|
+
from wolfdocx_docx.text import WD_ALIGN_PARAGRAPH
|
|
16
|
+
|
|
17
|
+
__all__ = ["WD_ALIGN_PARAGRAPH", "Document"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def Document(docx: str | os.PathLike[str] | IO[bytes] | None = None) -> _Document:
|
|
21
|
+
"""Return a document opened from a path or seekable binary stream.
|
|
22
|
+
|
|
23
|
+
Without an argument the document is new and holds no paragraphs.
|
|
24
|
+
"""
|
|
25
|
+
return _Document._open(docx)
|
wolfdocx_docx/agent.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""WolfDocx extensions, deliberately separate from the python-docx API subset."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import tempfile
|
|
7
|
+
from contextlib import contextmanager
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING, Any
|
|
10
|
+
from uuid import uuid4
|
|
11
|
+
|
|
12
|
+
from wolfdocx.builder import DocumentParagraph, DocumentRun, DocumentTable
|
|
13
|
+
from wolfdocx.comments import (
|
|
14
|
+
CommentInsert,
|
|
15
|
+
CommentReply,
|
|
16
|
+
CommentRequest,
|
|
17
|
+
CommentResolve,
|
|
18
|
+
author_comment,
|
|
19
|
+
discover_comment_targets,
|
|
20
|
+
)
|
|
21
|
+
from wolfdocx.inspect import Q, W
|
|
22
|
+
from wolfdocx.model import NodeEditError
|
|
23
|
+
from wolfdocx.review import (
|
|
24
|
+
ReviewChange,
|
|
25
|
+
ReviewDecisionRequest,
|
|
26
|
+
ReviewRequest,
|
|
27
|
+
ReviewRevisionRef,
|
|
28
|
+
author_review,
|
|
29
|
+
decide_review,
|
|
30
|
+
discover_review_revisions,
|
|
31
|
+
discover_review_targets,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
from .table import Table
|
|
35
|
+
from .text import Paragraph, Run
|
|
36
|
+
|
|
37
|
+
if TYPE_CHECKING:
|
|
38
|
+
from .document import Document
|
|
39
|
+
|
|
40
|
+
_MAIN = "word/document.xml"
|
|
41
|
+
_ID_NS = "urn:wolfdocx:object-identity:1"
|
|
42
|
+
_ID = Q(_ID_NS, "id")
|
|
43
|
+
_MC = "http://schemas.openxmlformats.org/markup-compatibility/2006"
|
|
44
|
+
_KINDS = {Q(W, "p"): "paragraph", Q(W, "r"): "run", Q(W, "tbl"): "table"}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class AgentEdits:
|
|
48
|
+
"""Use ``document.wolf`` for persistent addresses and source-bound review.
|
|
49
|
+
|
|
50
|
+
Mutating review/comment operations replace the document's in-memory snapshot.
|
|
51
|
+
Re-resolve saved identifiers afterwards instead of retaining old proxy objects.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(self, document: Document) -> None:
|
|
55
|
+
self._document = document
|
|
56
|
+
|
|
57
|
+
def identify(self, obj: Paragraph | Run | Table | dict[str, Any]) -> str:
|
|
58
|
+
"""Persist an identity on a current object; leave unaddressed objects alone."""
|
|
59
|
+
if isinstance(obj, dict):
|
|
60
|
+
identifier = obj.get("identifier")
|
|
61
|
+
if not isinstance(identifier, str) or not identifier.startswith("comment:"):
|
|
62
|
+
raise ValueError("expected a comment returned by wolf.comments()")
|
|
63
|
+
self.resolve(identifier)
|
|
64
|
+
return identifier
|
|
65
|
+
if not isinstance(obj, (Paragraph, Run, Table)):
|
|
66
|
+
raise TypeError("expected an alias paragraph, run, table, or comment")
|
|
67
|
+
element = obj._native.element
|
|
68
|
+
root = self._document._builder.document
|
|
69
|
+
if not any(node is element for node in root.iter()):
|
|
70
|
+
raise ValueError("object is detached, stale, or belongs to another document")
|
|
71
|
+
identifier = element.get(_ID)
|
|
72
|
+
if identifier is None:
|
|
73
|
+
occupied = {node.get(_ID) for node in root.iter()}
|
|
74
|
+
identifier = f"{_KINDS[element.tag]}:{uuid4().hex}"
|
|
75
|
+
while identifier in occupied:
|
|
76
|
+
identifier = f"{_KINDS[element.tag]}:{uuid4().hex}"
|
|
77
|
+
# Bind a fresh prefix without changing the meaning of existing prefixes.
|
|
78
|
+
prefix = "wolfid"
|
|
79
|
+
while root.get(f"xmlns:{prefix}") not in (None, _ID_NS):
|
|
80
|
+
prefix += "_"
|
|
81
|
+
scope = dict(getattr(root, "_namespace_scope", ()))
|
|
82
|
+
while prefix in scope and scope[prefix] != _ID_NS:
|
|
83
|
+
prefix += "_"
|
|
84
|
+
root.set(f"xmlns:{prefix}", _ID_NS)
|
|
85
|
+
ignorable = root.get(Q(_MC, "Ignorable"), "").split()
|
|
86
|
+
if prefix not in ignorable:
|
|
87
|
+
root.set(Q(_MC, "Ignorable"), " ".join([*ignorable, prefix]))
|
|
88
|
+
element.set(_ID, identifier)
|
|
89
|
+
self.resolve(identifier) # Refuse ambiguous imported identities.
|
|
90
|
+
return identifier
|
|
91
|
+
|
|
92
|
+
def resolve(self, identifier: str) -> Paragraph | Run | Table | dict[str, Any]:
|
|
93
|
+
"""Resolve a saved identity; positions and text are never used as identity."""
|
|
94
|
+
if not isinstance(identifier, str):
|
|
95
|
+
raise TypeError("identifier must be a string")
|
|
96
|
+
if identifier.startswith("comment:"):
|
|
97
|
+
for comment in self.comments():
|
|
98
|
+
if comment["identifier"] == identifier:
|
|
99
|
+
return comment
|
|
100
|
+
raise KeyError(identifier)
|
|
101
|
+
matches = [
|
|
102
|
+
node for node in self._document._builder.document.iter() if node.get(_ID) == identifier
|
|
103
|
+
]
|
|
104
|
+
if not matches:
|
|
105
|
+
raise KeyError(identifier)
|
|
106
|
+
if len(matches) != 1:
|
|
107
|
+
raise ValueError("ambiguous object identifier")
|
|
108
|
+
element = matches[0]
|
|
109
|
+
kind = _KINDS.get(element.tag)
|
|
110
|
+
if kind is None or not identifier.startswith(kind + ":"):
|
|
111
|
+
raise ValueError("object identifier kind mismatch")
|
|
112
|
+
builder, story = self._document._builder, self._document._story
|
|
113
|
+
if kind == "paragraph":
|
|
114
|
+
return Paragraph(DocumentParagraph(element, builder), story)
|
|
115
|
+
if kind == "run":
|
|
116
|
+
parents = {child: parent for parent in builder.document.iter() for child in parent}
|
|
117
|
+
parent = parents[element]
|
|
118
|
+
while parent.tag != Q(W, "p"):
|
|
119
|
+
parent = parents[parent]
|
|
120
|
+
return Run(DocumentRun(element, DocumentParagraph(parent, builder)))
|
|
121
|
+
return Table(DocumentTable(element, builder), story)
|
|
122
|
+
|
|
123
|
+
@contextmanager
|
|
124
|
+
def _snapshot(self):
|
|
125
|
+
with tempfile.TemporaryDirectory(prefix="wolfdocx-agent-") as directory:
|
|
126
|
+
source = Path(directory) / "source.docx"
|
|
127
|
+
output = Path(directory) / "output.docx"
|
|
128
|
+
self._document._save_stage(source)
|
|
129
|
+
yield source, output
|
|
130
|
+
|
|
131
|
+
@staticmethod
|
|
132
|
+
def _discovered(result: dict[str, Any]) -> dict[str, Any]:
|
|
133
|
+
if not result.get("passed"):
|
|
134
|
+
raise NodeEditError(result.get("code") or "agent_discovery_refused")
|
|
135
|
+
return result
|
|
136
|
+
|
|
137
|
+
def _adopt(self, report: Any, output: Path) -> None:
|
|
138
|
+
if report.status != "published":
|
|
139
|
+
raise NodeEditError(report.code or "agent_edit_refused")
|
|
140
|
+
current = self._document
|
|
141
|
+
replacement = type(current)._open(io.BytesIO(output.read_bytes()))
|
|
142
|
+
# Native range edits may split a run. Retain its identity on the first
|
|
143
|
+
# surviving fragment; later fragments are new objects, not aliases of it.
|
|
144
|
+
seen: set[str] = set()
|
|
145
|
+
for node in replacement._builder.document.iter():
|
|
146
|
+
identifier = node.get(_ID)
|
|
147
|
+
if identifier is not None:
|
|
148
|
+
if identifier in seen:
|
|
149
|
+
del node.attrib[_ID]
|
|
150
|
+
else:
|
|
151
|
+
seen.add(identifier)
|
|
152
|
+
old_session = current._builder._session
|
|
153
|
+
current._builder, current._story = replacement._builder, replacement._story
|
|
154
|
+
if old_session is not None:
|
|
155
|
+
old_session.close()
|
|
156
|
+
|
|
157
|
+
def _paragraph_number(self, identifier: str) -> int:
|
|
158
|
+
paragraph = self.resolve(identifier)
|
|
159
|
+
if not isinstance(paragraph, Paragraph):
|
|
160
|
+
raise TypeError("expected a paragraph identifier")
|
|
161
|
+
return next(
|
|
162
|
+
index
|
|
163
|
+
for index, node in enumerate(self._document._builder.document.iter(Q(W, "p")), 1)
|
|
164
|
+
if node is paragraph._p
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
def track(
|
|
168
|
+
self, paragraph: str, start: int, end: int, text: str, *, author: str, date: str
|
|
169
|
+
) -> list[dict[str, Any]]:
|
|
170
|
+
"""Track replacement of ``[start, end)``; empty ranges insert, empty text deletes."""
|
|
171
|
+
number = self._paragraph_number(paragraph)
|
|
172
|
+
with self._snapshot() as (source, output):
|
|
173
|
+
discovered = self._discovered(discover_review_targets(source))
|
|
174
|
+
target = next(row for row in discovered["targets"] if row["paragraph"] == number)
|
|
175
|
+
report = author_review(
|
|
176
|
+
ReviewRequest(
|
|
177
|
+
source=source,
|
|
178
|
+
source_sha256=discovered["source_sha256"],
|
|
179
|
+
output=output,
|
|
180
|
+
author=author,
|
|
181
|
+
date=date,
|
|
182
|
+
changes=(
|
|
183
|
+
ReviewChange(
|
|
184
|
+
_MAIN, number, start, end, text, target["structure_fingerprint_sha256"]
|
|
185
|
+
),
|
|
186
|
+
),
|
|
187
|
+
)
|
|
188
|
+
)
|
|
189
|
+
self._adopt(report, output)
|
|
190
|
+
return self.revisions()
|
|
191
|
+
|
|
192
|
+
def revisions(self) -> list[dict[str, Any]]:
|
|
193
|
+
"""List main-story native revisions, including their decision eligibility."""
|
|
194
|
+
with self._snapshot() as (source, _):
|
|
195
|
+
return self._discovered(discover_review_revisions(source))["revisions"]
|
|
196
|
+
|
|
197
|
+
def _decide(self, revision: dict[str, Any], action: str) -> None:
|
|
198
|
+
reference = ReviewRevisionRef.from_discovery(revision)
|
|
199
|
+
with self._snapshot() as (source, output):
|
|
200
|
+
discovered = self._discovered(discover_review_revisions(source))
|
|
201
|
+
report = decide_review(
|
|
202
|
+
ReviewDecisionRequest(
|
|
203
|
+
source, discovered["source_sha256"], output, action, revisions=(reference,)
|
|
204
|
+
)
|
|
205
|
+
)
|
|
206
|
+
self._adopt(report, output)
|
|
207
|
+
|
|
208
|
+
def accept(self, revision: dict[str, Any]) -> None:
|
|
209
|
+
"""Accept precisely the discovered revision; stale references are refused."""
|
|
210
|
+
self._decide(revision, "accept")
|
|
211
|
+
|
|
212
|
+
def reject(self, revision: dict[str, Any]) -> None:
|
|
213
|
+
"""Reject precisely the discovered revision; stale references are refused."""
|
|
214
|
+
self._decide(revision, "reject")
|
|
215
|
+
|
|
216
|
+
def comments(self) -> list[dict[str, Any]]:
|
|
217
|
+
"""List anchored comments, reply relationships and resolution metadata."""
|
|
218
|
+
with self._snapshot() as (source, _):
|
|
219
|
+
rows = self._discovered(discover_comment_targets(source))["comments"]
|
|
220
|
+
return [dict(row, identifier=f"comment:{row['comment_id']}") for row in rows]
|
|
221
|
+
|
|
222
|
+
def add_comment(
|
|
223
|
+
self,
|
|
224
|
+
paragraph: str,
|
|
225
|
+
start: int,
|
|
226
|
+
end: int,
|
|
227
|
+
text: str,
|
|
228
|
+
*,
|
|
229
|
+
author: str,
|
|
230
|
+
date: str,
|
|
231
|
+
initials: str | None = None,
|
|
232
|
+
) -> str:
|
|
233
|
+
"""Anchor a comment to a character range in an identified paragraph."""
|
|
234
|
+
number = self._paragraph_number(paragraph)
|
|
235
|
+
with self._snapshot() as (source, output):
|
|
236
|
+
found = self._discovered(discover_comment_targets(source))
|
|
237
|
+
target = next(row for row in found["targets"] if row["paragraph"] == number)
|
|
238
|
+
edit = CommentInsert(
|
|
239
|
+
part=_MAIN,
|
|
240
|
+
paragraph=number,
|
|
241
|
+
start=start,
|
|
242
|
+
end=end,
|
|
243
|
+
expected_old_text=target["text"][start:end],
|
|
244
|
+
structure_fingerprint_sha256=target["structure_fingerprint_sha256"],
|
|
245
|
+
author=author,
|
|
246
|
+
initials=initials,
|
|
247
|
+
date=date,
|
|
248
|
+
text=text,
|
|
249
|
+
)
|
|
250
|
+
before = {row["comment_id"] for row in found["comments"]}
|
|
251
|
+
report = author_comment(CommentRequest(source, found["source_sha256"], output, (edit,)))
|
|
252
|
+
self._adopt(report, output)
|
|
253
|
+
added = [row for row in report.comments if row["comment_id"] not in before]
|
|
254
|
+
return f"comment:{added[0]['comment_id']}"
|
|
255
|
+
|
|
256
|
+
def reply(
|
|
257
|
+
self,
|
|
258
|
+
comment: str,
|
|
259
|
+
text: str,
|
|
260
|
+
*,
|
|
261
|
+
author: str,
|
|
262
|
+
date: str,
|
|
263
|
+
initials: str | None = None,
|
|
264
|
+
) -> str:
|
|
265
|
+
"""Append a reply to an existing comment and return its persistent address."""
|
|
266
|
+
with self._snapshot() as (source, output):
|
|
267
|
+
found = self._discovered(discover_comment_targets(source))
|
|
268
|
+
parent = self._comment(found, comment)
|
|
269
|
+
before = {row["comment_id"] for row in found["comments"]}
|
|
270
|
+
edit = CommentReply(
|
|
271
|
+
parent["comment_id"], parent["comment_sha256"], author, initials, date, text
|
|
272
|
+
)
|
|
273
|
+
report = author_comment(CommentRequest(source, found["source_sha256"], output, (edit,)))
|
|
274
|
+
self._adopt(report, output)
|
|
275
|
+
added = [row for row in report.comments if row["comment_id"] not in before]
|
|
276
|
+
return f"comment:{added[0]['comment_id']}"
|
|
277
|
+
|
|
278
|
+
def resolve_comment(self, comment: str, resolved: bool = True) -> None:
|
|
279
|
+
"""Set the thread's resolved state; use False to reopen it."""
|
|
280
|
+
with self._snapshot() as (source, output):
|
|
281
|
+
found = self._discovered(discover_comment_targets(source))
|
|
282
|
+
parent = self._comment(found, comment)
|
|
283
|
+
edit = CommentResolve(parent["comment_id"], parent["comment_sha256"], resolved)
|
|
284
|
+
report = author_comment(CommentRequest(source, found["source_sha256"], output, (edit,)))
|
|
285
|
+
self._adopt(report, output)
|
|
286
|
+
|
|
287
|
+
@staticmethod
|
|
288
|
+
def _comment(found: dict[str, Any], identifier: str) -> dict[str, Any]:
|
|
289
|
+
for row in found["comments"]:
|
|
290
|
+
if f"comment:{row['comment_id']}" == identifier:
|
|
291
|
+
return row
|
|
292
|
+
raise KeyError(identifier)
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""The ``Document`` proxy: open, edit and save over the native WolfDocx builder."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import posixpath
|
|
7
|
+
import shutil
|
|
8
|
+
import stat
|
|
9
|
+
import tempfile
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import IO
|
|
12
|
+
from xml.etree import ElementTree as ET
|
|
13
|
+
|
|
14
|
+
from wolfdocx.builder import DocumentBuilder, DocumentParagraph, DocumentSection, DocumentTable
|
|
15
|
+
from wolfdocx.document import Document as NativeDocument
|
|
16
|
+
from wolfdocx.inspect import Q, W, parse_xml_with_preserved_qnames
|
|
17
|
+
from wolfdocx.model import NodeEditError
|
|
18
|
+
|
|
19
|
+
from wolfdocx_docx.table import Table, _add_table
|
|
20
|
+
from wolfdocx_docx.text import Paragraph, _check_text, _Story
|
|
21
|
+
|
|
22
|
+
__all__ = ["Document"]
|
|
23
|
+
|
|
24
|
+
_DOCUMENT_RELATIONSHIPS = "word/_rels/document.xml.rels"
|
|
25
|
+
_STYLES_RELATIONSHIP = "/styles"
|
|
26
|
+
# The builder publishes only ``.docx`` names; staging uses a private fixed one.
|
|
27
|
+
_STAGED_NAME = "document.docx"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _styles_part(session: NativeDocument) -> bytes | None:
|
|
31
|
+
"""The bytes of the package's main-story styles part, when it has one."""
|
|
32
|
+
if _DOCUMENT_RELATIONSHIPS not in session.part_names:
|
|
33
|
+
return None
|
|
34
|
+
relationships = parse_xml_with_preserved_qnames(session.part_bytes(_DOCUMENT_RELATIONSHIPS))
|
|
35
|
+
for relation in relationships:
|
|
36
|
+
if (
|
|
37
|
+
relation.get("Type", "").endswith(_STYLES_RELATIONSHIP)
|
|
38
|
+
and relation.get("TargetMode") != "External"
|
|
39
|
+
):
|
|
40
|
+
target = relation.get("Target", "")
|
|
41
|
+
name = (
|
|
42
|
+
target.lstrip("/")
|
|
43
|
+
if target.startswith("/")
|
|
44
|
+
else posixpath.normpath(posixpath.join("word", target))
|
|
45
|
+
)
|
|
46
|
+
return session.part_bytes(name) if name in session.part_names else None
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class _Body:
|
|
51
|
+
"""Main-story content over one native builder, without an upstream part graph."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, builder: DocumentBuilder, story: _Story) -> None:
|
|
54
|
+
self._builder = builder
|
|
55
|
+
self._story = story
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def _element(self) -> ET.Element:
|
|
59
|
+
body = self._builder.document.find(Q(W, "body"))
|
|
60
|
+
assert body is not None
|
|
61
|
+
return body
|
|
62
|
+
|
|
63
|
+
def add_paragraph(self, text: str = "", style: str | None = None) -> Paragraph:
|
|
64
|
+
if text:
|
|
65
|
+
_check_text(text)
|
|
66
|
+
resolved = self._story.style_id(style, "paragraph")
|
|
67
|
+
paragraph = Paragraph(self._builder.write_paragraph("", style=resolved), self._story)
|
|
68
|
+
if text:
|
|
69
|
+
paragraph.add_run(text)
|
|
70
|
+
return paragraph
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def paragraphs(self) -> list[Paragraph]:
|
|
74
|
+
return [
|
|
75
|
+
Paragraph(DocumentParagraph(p, self._builder), self._story)
|
|
76
|
+
for p in self._element.findall(Q(W, "p"))
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def tables(self) -> list[Table]:
|
|
81
|
+
return [
|
|
82
|
+
Table(DocumentTable(t, self._builder), self._story)
|
|
83
|
+
for t in self._element.findall(Q(W, "tbl"))
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class Document:
|
|
88
|
+
"""A WordprocessingML document edited through the native WolfDocx builder.
|
|
89
|
+
|
|
90
|
+
Create packages with :func:`wolfdocx_docx.Document`. The lower-level XML
|
|
91
|
+
constructor imports a main-story tree into a fresh native builder. Its parent
|
|
92
|
+
is retained as context only, never used to open, edit or save a package.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
def __init__(self, element: ET.Element, part: object | None = None) -> None:
|
|
96
|
+
root = parse_xml_with_preserved_qnames(ET.tostring(element, encoding="utf-8"))
|
|
97
|
+
if root.tag != Q(W, "document"):
|
|
98
|
+
raise ValueError("expected a w:document element")
|
|
99
|
+
builder = DocumentBuilder()
|
|
100
|
+
body = root.find(Q(W, "body"))
|
|
101
|
+
if body is None:
|
|
102
|
+
body = ET.SubElement(root, Q(W, "body"))
|
|
103
|
+
if body.find(Q(W, "sectPr")) is None:
|
|
104
|
+
body.append(builder._section_properties)
|
|
105
|
+
builder._document = root
|
|
106
|
+
builder._body = body
|
|
107
|
+
builder._block_container = body
|
|
108
|
+
sections = list(body.iter(Q(W, "sectPr")))
|
|
109
|
+
builder._section_properties = sections[-1]
|
|
110
|
+
builder._sections = [DocumentSection(section, builder) for section in sections]
|
|
111
|
+
builder._paragraphs = [DocumentParagraph(p, builder) for p in body.findall(Q(W, "p"))]
|
|
112
|
+
builder._tables = [DocumentTable(t, builder) for t in body.findall(Q(W, "tbl"))]
|
|
113
|
+
self._builder = builder
|
|
114
|
+
self._story = _Story(builder, None)
|
|
115
|
+
self._part = part
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def wolf(self):
|
|
119
|
+
"""WolfDocx-only review, comments and persistent object addresses."""
|
|
120
|
+
from .agent import AgentEdits
|
|
121
|
+
|
|
122
|
+
return AgentEdits(self)
|
|
123
|
+
|
|
124
|
+
@classmethod
|
|
125
|
+
def _open(cls, docx: str | os.PathLike[str] | IO[bytes] | None) -> Document:
|
|
126
|
+
session = None if docx is None else NativeDocument(docx)
|
|
127
|
+
try:
|
|
128
|
+
builder = DocumentBuilder() if session is None else DocumentBuilder.open(session)
|
|
129
|
+
document = cls.__new__(cls)
|
|
130
|
+
document._builder = builder
|
|
131
|
+
document._story = _Story(builder, None if session is None else _styles_part(session))
|
|
132
|
+
document._part = None
|
|
133
|
+
return document
|
|
134
|
+
except BaseException:
|
|
135
|
+
if session is not None:
|
|
136
|
+
session.close()
|
|
137
|
+
raise
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def _body(self) -> _Body:
|
|
141
|
+
return _Body(self._builder, self._story)
|
|
142
|
+
|
|
143
|
+
def add_heading(self, text: str = "", level: int = 1) -> Paragraph:
|
|
144
|
+
"""Append a paragraph styled ``Title`` for level 0, else ``Heading <level>``."""
|
|
145
|
+
if not 0 <= level <= 9:
|
|
146
|
+
raise ValueError(f"level must be in range 0-9, got {level}")
|
|
147
|
+
return self.add_paragraph(text, "Title" if level == 0 else f"Heading {level}")
|
|
148
|
+
|
|
149
|
+
def add_paragraph(self, text: str = "", style: str | None = None) -> Paragraph:
|
|
150
|
+
"""Append a paragraph holding ``text`` in one run, with paragraph style ``style``."""
|
|
151
|
+
return self._body.add_paragraph(text, style)
|
|
152
|
+
|
|
153
|
+
def add_table(self, rows: int, cols: int, style: str | None = None) -> Table:
|
|
154
|
+
"""Append an empty ``rows`` by ``cols`` table with table style ``style``."""
|
|
155
|
+
resolved = self._story.style_id(style, "table")
|
|
156
|
+
return Table(_add_table(self._builder, rows, cols, resolved), self._story)
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def paragraphs(self) -> list[Paragraph]:
|
|
160
|
+
"""The paragraphs directly in the document body, in document order."""
|
|
161
|
+
return self._body.paragraphs
|
|
162
|
+
|
|
163
|
+
@property
|
|
164
|
+
def tables(self) -> list[Table]:
|
|
165
|
+
"""The tables directly in the document body, in document order."""
|
|
166
|
+
return self._body.tables
|
|
167
|
+
|
|
168
|
+
def save(self, path_or_stream: str | os.PathLike[str] | IO[bytes]) -> None:
|
|
169
|
+
"""Write the document to a path or a binary stream.
|
|
170
|
+
|
|
171
|
+
The package is composed and verified by the native engine in a private stage
|
|
172
|
+
first. An existing file at a path is replaced atomically, only once the stage
|
|
173
|
+
is complete; a stream receives the finished package. Parts the document does
|
|
174
|
+
not change keep their original bytes. A native refusal raises
|
|
175
|
+
``wolfdocx.model.NodeEditError`` carrying the engine's code and nothing is
|
|
176
|
+
published.
|
|
177
|
+
"""
|
|
178
|
+
if hasattr(path_or_stream, "write"):
|
|
179
|
+
if not path_or_stream.seekable():
|
|
180
|
+
raise ValueError("save requires a seekable binary stream")
|
|
181
|
+
with tempfile.TemporaryDirectory(prefix="wolfdocx-docx-save-") as directory:
|
|
182
|
+
staged = Path(directory) / _STAGED_NAME
|
|
183
|
+
self._save_stage(staged)
|
|
184
|
+
with staged.open("rb") as package:
|
|
185
|
+
while chunk := package.read(64 * 1024):
|
|
186
|
+
if path_or_stream.write(chunk) != len(chunk):
|
|
187
|
+
raise OSError("short stream write")
|
|
188
|
+
return
|
|
189
|
+
# Resolve links so an existing target is replaced where it lives, as an
|
|
190
|
+
# in-place write would; the stage shares its directory, keeping the swap atomic.
|
|
191
|
+
target = Path(os.path.realpath(os.fspath(path_or_stream)))
|
|
192
|
+
directory_path = Path(tempfile.mkdtemp(prefix=".wolfdocx-docx-save-", dir=target.parent))
|
|
193
|
+
try:
|
|
194
|
+
staged = directory_path / _STAGED_NAME
|
|
195
|
+
self._save_stage(staged)
|
|
196
|
+
os.chmod(staged, _published_mode(target, directory_path))
|
|
197
|
+
os.replace(staged, target)
|
|
198
|
+
finally:
|
|
199
|
+
shutil.rmtree(directory_path, ignore_errors=True)
|
|
200
|
+
|
|
201
|
+
def _save_stage(self, destination: Path) -> None:
|
|
202
|
+
if self._builder._session is not None:
|
|
203
|
+
# Opened packages use the builder's sync and verified session publication.
|
|
204
|
+
self._builder.save(destination)
|
|
205
|
+
return
|
|
206
|
+
# The fresh builder's ZIP writer is not a verification gate. Admit its package
|
|
207
|
+
# into a native session before publication, rather than bypassing that gate.
|
|
208
|
+
source = destination.with_name("new-document.docx")
|
|
209
|
+
self._builder.save(source)
|
|
210
|
+
with NativeDocument(source) as session:
|
|
211
|
+
report = session.save(destination)
|
|
212
|
+
if report.status != "published":
|
|
213
|
+
raise NodeEditError(report.code or "document_save_refused")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _published_mode(target: Path, scratch: Path) -> int:
|
|
217
|
+
"""The permissions an in-place write would give ``target``: its own, else the umask's."""
|
|
218
|
+
try:
|
|
219
|
+
return stat.S_IMODE(target.stat().st_mode)
|
|
220
|
+
except FileNotFoundError:
|
|
221
|
+
probe = scratch / "mode-probe"
|
|
222
|
+
os.close(os.open(probe, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o666))
|
|
223
|
+
return stat.S_IMODE(probe.stat().st_mode)
|