parse-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.
parse_docx/__init__.py ADDED
@@ -0,0 +1,33 @@
1
+ """A bounded, dependency-free DOCX parser."""
2
+
3
+ from .parser import (
4
+ Document,
5
+ HeaderFooter,
6
+ Limits,
7
+ Note,
8
+ Paragraph,
9
+ ParseError,
10
+ Run,
11
+ Table,
12
+ TableCell,
13
+ TableRow,
14
+ load,
15
+ loads,
16
+ parse,
17
+ )
18
+
19
+ __all__ = [
20
+ "Document",
21
+ "HeaderFooter",
22
+ "Limits",
23
+ "Note",
24
+ "Paragraph",
25
+ "ParseError",
26
+ "Run",
27
+ "Table",
28
+ "TableCell",
29
+ "TableRow",
30
+ "load",
31
+ "loads",
32
+ "parse",
33
+ ]
parse_docx/parser.py ADDED
@@ -0,0 +1,868 @@
1
+ """Bounded parsing of the WordprocessingML subset used by common DOCX files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import lzma
7
+ import posixpath
8
+ import re
9
+ import stat
10
+ import zipfile
11
+ import zlib
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from urllib.parse import unquote
15
+ from xml.etree import ElementTree as ET
16
+ from xml.parsers import expat
17
+
18
+ _W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
19
+ _R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
20
+ _PKG_REL = "http://schemas.openxmlformats.org/package/2006/relationships"
21
+ _OFFICE_DOCUMENT_REL = f"{_R}/officeDocument"
22
+ _NS = {"w": _W, "r": _R}
23
+ _QNAME = re.compile(r"^\{[^}]+\}(.+)$")
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class Limits:
28
+ """Resource bounds applied while reading an OPC ZIP package."""
29
+
30
+ max_archive_bytes: int = 128 * 1024 * 1024
31
+ max_uncompressed_bytes: int = 256 * 1024 * 1024
32
+ max_part_bytes: int = 16 * 1024 * 1024
33
+ max_entries: int = 4096
34
+ max_compression_ratio: int = 200
35
+
36
+ def __post_init__(self) -> None:
37
+ for name in (
38
+ "max_archive_bytes",
39
+ "max_uncompressed_bytes",
40
+ "max_part_bytes",
41
+ "max_entries",
42
+ "max_compression_ratio",
43
+ ):
44
+ value = getattr(self, name)
45
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
46
+ raise ValueError(f"{name} must be a positive integer")
47
+
48
+
49
+ class ParseError(ValueError):
50
+ """A malformed DOCX package or an input that exceeds configured limits."""
51
+
52
+ def __init__(self, code: str, message: str) -> None:
53
+ super().__init__(message)
54
+ self.code = code
55
+
56
+
57
+ @dataclass(frozen=True, slots=True)
58
+ class Run:
59
+ text: str
60
+ bold: bool = False
61
+ italic: bool = False
62
+ underline: bool = False
63
+ hyperlink: str | None = None
64
+ source_part: str = "word/document.xml"
65
+
66
+
67
+ @dataclass(frozen=True, slots=True)
68
+ class Paragraph:
69
+ runs: tuple[Run, ...]
70
+ style: str | None = None
71
+ heading_level: int | None = None
72
+ num_id: int | None = None
73
+ list_level: int = 0
74
+ list_format: str | None = None
75
+ list_text: str | None = None
76
+ list_start: int = 1
77
+ source_part: str = "word/document.xml"
78
+
79
+ @property
80
+ def text(self) -> str:
81
+ return "".join(run.text for run in self.runs)
82
+
83
+
84
+ @dataclass(frozen=True, slots=True)
85
+ class TableCell:
86
+ blocks: tuple[Block, ...]
87
+
88
+
89
+ @dataclass(frozen=True, slots=True)
90
+ class TableRow:
91
+ cells: tuple[TableCell, ...]
92
+
93
+
94
+ @dataclass(frozen=True, slots=True)
95
+ class Table:
96
+ rows: tuple[TableRow, ...]
97
+ source_part: str = "word/document.xml"
98
+
99
+
100
+ type Block = Paragraph | Table
101
+
102
+
103
+ @dataclass(frozen=True, slots=True)
104
+ class HeaderFooter:
105
+ kind: str
106
+ blocks: tuple[Block, ...]
107
+ source_part: str
108
+
109
+
110
+ @dataclass(frozen=True, slots=True)
111
+ class Note:
112
+ id: int
113
+ blocks: tuple[Block, ...]
114
+ source_part: str
115
+
116
+
117
+ @dataclass(frozen=True, slots=True)
118
+ class Document:
119
+ blocks: tuple[Block, ...]
120
+ source_part: str
121
+ headers: tuple[HeaderFooter, ...] = ()
122
+ footers: tuple[HeaderFooter, ...] = ()
123
+ footnotes: tuple[Note, ...] = ()
124
+ endnotes: tuple[Note, ...] = ()
125
+
126
+ @property
127
+ def text(self) -> str:
128
+ counters: dict[int, dict[int, int]] = {}
129
+ return "\n".join(_block_text(block, counters) for block in self.blocks)
130
+
131
+
132
+ @dataclass(frozen=True, slots=True)
133
+ class _Relationship:
134
+ rel_type: str
135
+ target: str | None
136
+ external: bool = False
137
+
138
+
139
+ def load(path: str | Path, *, limits: Limits | None = None) -> Document:
140
+ """Read and parse a DOCX from a filesystem path."""
141
+ if not isinstance(path, (str, Path)):
142
+ raise TypeError("path must be str or pathlib.Path")
143
+ bounds = limits or Limits()
144
+ file_path = Path(path)
145
+ try:
146
+ if file_path.stat().st_size > bounds.max_archive_bytes:
147
+ raise ParseError(
148
+ "archive-limit-exceeded", "DOCX exceeds archive size limit"
149
+ )
150
+ with file_path.open("rb") as stream:
151
+ data = stream.read(bounds.max_archive_bytes + 1)
152
+ except ParseError:
153
+ raise
154
+ except OSError as error:
155
+ raise ParseError(
156
+ "source-unreadable", f"could not read DOCX: {error}"
157
+ ) from error
158
+ if len(data) > bounds.max_archive_bytes:
159
+ raise ParseError("archive-limit-exceeded", "DOCX exceeds archive size limit")
160
+ return loads(data, limits=bounds)
161
+
162
+
163
+ def loads(data: bytes, *, limits: Limits | None = None) -> Document:
164
+ """Parse DOCX bytes into an immutable document model."""
165
+ if not isinstance(data, bytes):
166
+ raise TypeError("data must be bytes")
167
+ bounds = limits or Limits()
168
+ if len(data) > bounds.max_archive_bytes:
169
+ raise ParseError("archive-limit-exceeded", "DOCX exceeds archive size limit")
170
+ try:
171
+ archive = zipfile.ZipFile(io.BytesIO(data))
172
+ except (OSError, zipfile.BadZipFile, ValueError) as error:
173
+ raise ParseError(
174
+ "invalid-archive", f"not a valid DOCX ZIP package: {error}"
175
+ ) from error
176
+ with archive:
177
+ return _PackageReader(archive, bounds).document()
178
+
179
+
180
+ parse = loads
181
+
182
+
183
+ class _PackageReader:
184
+ def __init__(self, archive: zipfile.ZipFile, limits: Limits) -> None:
185
+ self.archive = archive
186
+ self.limits = limits
187
+ self.infos: dict[str, zipfile.ZipInfo] = {}
188
+ self.actual_uncompressed = 0
189
+ infos = archive.infolist()
190
+ if len(infos) > limits.max_entries:
191
+ raise ParseError(
192
+ "entry-limit-exceeded", "DOCX contains too many ZIP entries"
193
+ )
194
+ declared_total = 0
195
+ for info in infos:
196
+ name = info.filename
197
+ _validate_entry_name(name)
198
+ if name in self.infos:
199
+ raise ParseError("duplicate-entry", f"duplicate ZIP entry: {name}")
200
+ if info.flag_bits & 0x1:
201
+ raise ParseError("encrypted-entry", f"encrypted ZIP entry: {name}")
202
+ if stat.S_ISLNK(info.external_attr >> 16):
203
+ raise ParseError("invalid-entry", f"symbolic link ZIP entry: {name}")
204
+ if info.file_size < 0 or info.compress_size < 0:
205
+ raise ParseError("invalid-entry", f"invalid ZIP entry size: {name}")
206
+ if info.file_size > limits.max_part_bytes:
207
+ raise ParseError(
208
+ "part-limit-exceeded", f"ZIP entry exceeds part limit: {name}"
209
+ )
210
+ if info.file_size > 0 and (
211
+ info.compress_size == 0
212
+ or info.file_size > info.compress_size * limits.max_compression_ratio
213
+ ):
214
+ raise ParseError(
215
+ "compression-ratio-exceeded", f"suspicious ZIP entry: {name}"
216
+ )
217
+ declared_total += info.file_size
218
+ if declared_total > limits.max_uncompressed_bytes:
219
+ raise ParseError(
220
+ "package-limit-exceeded",
221
+ "DOCX exceeds total uncompressed package size limit",
222
+ )
223
+ self.infos[name] = info
224
+ self._require("[Content_Types].xml")
225
+ content_types = self._xml("[Content_Types].xml")
226
+ if (
227
+ content_types.tag
228
+ != "{http://schemas.openxmlformats.org/package/2006/content-types}Types"
229
+ ):
230
+ raise ParseError("invalid-content-types", "invalid OPC content types part")
231
+
232
+ def document(self) -> Document:
233
+ root_rels = self._relationships("")
234
+ document_part = next(
235
+ (
236
+ relation.target
237
+ for relation in root_rels.values()
238
+ if relation.rel_type == _OFFICE_DOCUMENT_REL
239
+ and not relation.external
240
+ and relation.target is not None
241
+ ),
242
+ None,
243
+ )
244
+ if document_part is None:
245
+ raise ParseError(
246
+ "missing-document", "package has no internal Word document part"
247
+ )
248
+ document_root = self._xml(document_part)
249
+ body = document_root.find("w:body", _NS)
250
+ if body is None:
251
+ raise ParseError("missing-document-body", "Word document has no body")
252
+
253
+ relations = self._relationships(document_part)
254
+ styles = self._styles(relations)
255
+ numbering = self._numbering(relations)
256
+ blocks = self._blocks(body, document_part, relations, styles, numbering)
257
+ headers: list[HeaderFooter] = []
258
+ footers: list[HeaderFooter] = []
259
+ seen_parts: set[str] = set()
260
+ for section in body.iter(f"{{{_W}}}sectPr"):
261
+ for reference in section:
262
+ kind = _local_name(reference.tag)
263
+ if kind not in {"headerReference", "footerReference"}:
264
+ continue
265
+ relationship_id = reference.get(f"{{{_R}}}id")
266
+ relationship = relations.get(relationship_id or "")
267
+ if (
268
+ relationship is None
269
+ or relationship.external
270
+ or relationship.target is None
271
+ ):
272
+ continue
273
+ expected_type = "/header" if kind == "headerReference" else "/footer"
274
+ if not relationship.rel_type.endswith(expected_type):
275
+ continue
276
+ part = relationship.target
277
+ if part in seen_parts:
278
+ continue
279
+ seen_parts.add(part)
280
+ section_root = self._xml(part)
281
+ section_blocks = self._blocks(
282
+ section_root,
283
+ part,
284
+ self._relationships(part),
285
+ styles,
286
+ numbering,
287
+ )
288
+ item = HeaderFooter(
289
+ "header" if kind == "headerReference" else "footer",
290
+ section_blocks,
291
+ part,
292
+ )
293
+ (headers if item.kind == "header" else footers).append(item)
294
+
295
+ return Document(
296
+ blocks=blocks,
297
+ source_part=document_part,
298
+ headers=tuple(headers),
299
+ footers=tuple(footers),
300
+ footnotes=self._notes(relations, styles, numbering, "footnotes"),
301
+ endnotes=self._notes(relations, styles, numbering, "endnotes"),
302
+ )
303
+
304
+ def _require(self, name: str) -> None:
305
+ if name not in self.infos:
306
+ raise ParseError(
307
+ "missing-part", f"required package part is missing: {name}"
308
+ )
309
+
310
+ def _read(self, name: str) -> bytes:
311
+ self._require(name)
312
+ try:
313
+ with self.archive.open(name) as part:
314
+ data = part.read(self.limits.max_part_bytes + 1)
315
+ except (
316
+ OSError,
317
+ RuntimeError,
318
+ NotImplementedError,
319
+ zipfile.BadZipFile,
320
+ zipfile.LargeZipFile,
321
+ lzma.LZMAError,
322
+ zlib.error,
323
+ ) as error:
324
+ raise ParseError(
325
+ "invalid-entry", f"could not read package part {name}: {error}"
326
+ ) from error
327
+ if len(data) > self.limits.max_part_bytes:
328
+ raise ParseError(
329
+ "part-limit-exceeded", f"ZIP entry exceeds part limit: {name}"
330
+ )
331
+ self.actual_uncompressed += len(data)
332
+ if self.actual_uncompressed > self.limits.max_uncompressed_bytes:
333
+ raise ParseError(
334
+ "package-limit-exceeded",
335
+ "DOCX exceeds total uncompressed package size limit",
336
+ )
337
+ return data
338
+
339
+ def _xml(self, name: str) -> ET.Element:
340
+ raw = self._read(name)
341
+ _reject_xml_declarations(raw, name)
342
+ try:
343
+ return ET.fromstring(raw)
344
+ except ET.ParseError as error:
345
+ raise ParseError(
346
+ "invalid-xml", f"invalid XML in {name}: {error}"
347
+ ) from error
348
+
349
+ def _relationships(self, source_part: str) -> dict[str, _Relationship]:
350
+ rels_part = (
351
+ posixpath.join(
352
+ posixpath.dirname(source_part),
353
+ "_rels",
354
+ f"{posixpath.basename(source_part)}.rels",
355
+ )
356
+ if source_part
357
+ else "_rels/.rels"
358
+ )
359
+ if rels_part not in self.infos:
360
+ return {}
361
+ root = self._xml(rels_part)
362
+ if root.tag != f"{{{_PKG_REL}}}Relationships":
363
+ raise ParseError(
364
+ "invalid-relationships", f"invalid relationships part: {rels_part}"
365
+ )
366
+ relationships: dict[str, _Relationship] = {}
367
+ for relationship in root:
368
+ if relationship.tag != f"{{{_PKG_REL}}}Relationship":
369
+ continue
370
+ relationship_id = relationship.get("Id")
371
+ rel_type = relationship.get("Type", "")
372
+ target = relationship.get("Target", "")
373
+ if not relationship_id:
374
+ raise ParseError(
375
+ "invalid-relationship", f"relationship without Id in {rels_part}"
376
+ )
377
+ if relationship_id in relationships:
378
+ raise ParseError(
379
+ "duplicate-relationship",
380
+ f"duplicate relationship Id in {rels_part}",
381
+ )
382
+ is_external = relationship.get("TargetMode") == "External"
383
+ relationships[relationship_id] = _Relationship(
384
+ rel_type,
385
+ target if is_external else _resolve_target(source_part, target),
386
+ is_external,
387
+ )
388
+ return relationships
389
+
390
+ def _styles(
391
+ self, relationships: dict[str, _Relationship]
392
+ ) -> dict[str, tuple[str, str | None]]:
393
+ part = self._related_part(relationships, "/styles")
394
+ if part is None:
395
+ return {}
396
+ root = self._xml(part)
397
+ styles: dict[str, tuple[str, str | None]] = {}
398
+ for style in root.findall("w:style", _NS):
399
+ style_id = style.get(f"{{{_W}}}styleId")
400
+ if not style_id:
401
+ continue
402
+ name = style.find("w:name", _NS)
403
+ based_on = style.find("w:basedOn", _NS)
404
+ styles[style_id] = (
405
+ name.get(f"{{{_W}}}val", style_id) if name is not None else style_id,
406
+ based_on.get(f"{{{_W}}}val") if based_on is not None else None,
407
+ )
408
+ return styles
409
+
410
+ def _numbering(
411
+ self, relationships: dict[str, _Relationship]
412
+ ) -> dict[int, dict[int, tuple[str, str, int]]]:
413
+ part = self._related_part(relationships, "/numbering")
414
+ if part is None:
415
+ return {}
416
+ root = self._xml(part)
417
+ abstract: dict[int, dict[int, tuple[str, str, int]]] = {}
418
+ for item in root.findall("w:abstractNum", _NS):
419
+ abstract_id = _int_attr(item, "abstractNumId")
420
+ if abstract_id is None:
421
+ continue
422
+ levels: dict[int, tuple[str, str, int]] = {}
423
+ for level in item.findall("w:lvl", _NS):
424
+ level_index = _int_attr(level, "ilvl")
425
+ if level_index is None or not 0 <= level_index <= 8:
426
+ continue
427
+ number_format = level.find("w:numFmt", _NS)
428
+ level_text = level.find("w:lvlText", _NS)
429
+ start = level.find("w:start", _NS)
430
+ start_value = _int_value(
431
+ start.get(f"{{{_W}}}val") if start is not None else None,
432
+ 1,
433
+ )
434
+ levels[level_index] = (
435
+ number_format.get(f"{{{_W}}}val", "decimal")
436
+ if number_format is not None
437
+ else "decimal",
438
+ level_text.get(f"{{{_W}}}val", "%1.")
439
+ if level_text is not None
440
+ else "%1.",
441
+ 1 if start_value is None else start_value,
442
+ )
443
+ abstract[abstract_id] = levels
444
+ result: dict[int, dict[int, tuple[str, str, int]]] = {}
445
+ for item in root.findall("w:num", _NS):
446
+ number_id = _int_attr(item, "numId")
447
+ abstract_num = item.find("w:abstractNumId", _NS)
448
+ abstract_id = (
449
+ _int_value(abstract_num.get(f"{{{_W}}}val"), -1)
450
+ if abstract_num is not None
451
+ else -1
452
+ )
453
+ if number_id is not None and abstract_id in abstract:
454
+ result[number_id] = abstract[abstract_id]
455
+ return result
456
+
457
+ def _related_part(
458
+ self, relationships: dict[str, _Relationship], suffix: str
459
+ ) -> str | None:
460
+ for relation in relationships.values():
461
+ if (
462
+ relation.rel_type.endswith(suffix)
463
+ and not relation.external
464
+ and relation.target in self.infos
465
+ ):
466
+ return relation.target
467
+ return None
468
+
469
+ def _blocks(
470
+ self,
471
+ root: ET.Element,
472
+ part: str,
473
+ relationships: dict[str, _Relationship],
474
+ styles: dict[str, tuple[str, str | None]],
475
+ numbering: dict[int, dict[int, tuple[str, str, int]]],
476
+ ) -> tuple[Block, ...]:
477
+ container = root.find("w:body", _NS)
478
+ if container is None:
479
+ container = root
480
+ output: list[Block] = []
481
+ for child in container:
482
+ if child.tag == f"{{{_W}}}p":
483
+ output.append(
484
+ self._paragraph(child, part, relationships, styles, numbering)
485
+ )
486
+ elif child.tag == f"{{{_W}}}tbl":
487
+ output.append(
488
+ self._table(child, part, relationships, styles, numbering)
489
+ )
490
+ return tuple(output)
491
+
492
+ def _paragraph(
493
+ self,
494
+ element: ET.Element,
495
+ part: str,
496
+ relationships: dict[str, _Relationship],
497
+ styles: dict[str, tuple[str, str | None]],
498
+ numbering: dict[int, dict[int, tuple[str, str, int]]],
499
+ ) -> Paragraph:
500
+ properties = element.find("w:pPr", _NS)
501
+ style_id: str | None = None
502
+ num_id: int | None = None
503
+ list_level = 0
504
+ outline_level: int | None = None
505
+ if properties is not None:
506
+ style = properties.find("w:pStyle", _NS)
507
+ style_id = style.get(f"{{{_W}}}val") if style is not None else None
508
+ num_properties = properties.find("w:numPr", _NS)
509
+ if num_properties is not None:
510
+ num_id = _int_value(_child_value(num_properties, "numId"), None)
511
+ list_level = _int_value(_child_value(num_properties, "ilvl"), 0) or 0
512
+ outline_level = _int_value(_child_value(properties, "outlineLvl"), None)
513
+ style_name = _style_name(style_id, styles)
514
+ heading_level = _heading_level(style_id, style_name, outline_level, styles)
515
+ list_data = (
516
+ numbering.get(num_id or -1, {}).get(list_level)
517
+ if num_id is not None
518
+ else None
519
+ )
520
+ runs: list[Run] = []
521
+ self._inline_runs(element, part, relationships, runs)
522
+ return Paragraph(
523
+ runs=tuple(runs),
524
+ style=style_name,
525
+ heading_level=heading_level,
526
+ num_id=num_id if list_data is not None else None,
527
+ list_level=list_level,
528
+ list_format=list_data[0] if list_data else None,
529
+ list_text=list_data[1] if list_data else None,
530
+ list_start=list_data[2] if list_data else 1,
531
+ source_part=part,
532
+ )
533
+
534
+ def _inline_runs(
535
+ self,
536
+ parent: ET.Element,
537
+ part: str,
538
+ relationships: dict[str, _Relationship],
539
+ output: list[Run],
540
+ hyperlink: str | None = None,
541
+ ) -> None:
542
+ for child in parent:
543
+ name = _local_name(child.tag)
544
+ if name in {"pPr", "del", "moveFrom", "instrText", "delText"}:
545
+ continue
546
+ if name == "hyperlink":
547
+ relation_id = child.get(f"{{{_R}}}id")
548
+ relation = relationships.get(relation_id or "")
549
+ target = relation.target if relation is not None else None
550
+ if target is None:
551
+ anchor = child.get(f"{{{_W}}}anchor")
552
+ target = f"#{anchor}" if anchor else None
553
+ self._inline_runs(child, part, relationships, output, target)
554
+ elif name == "r":
555
+ properties = child.find("w:rPr", _NS)
556
+ text = _run_text(child)
557
+ if text:
558
+ output.append(
559
+ Run(
560
+ text,
561
+ _toggle_property(properties, "b"),
562
+ _toggle_property(properties, "i"),
563
+ _toggle_property(properties, "u"),
564
+ hyperlink,
565
+ part,
566
+ )
567
+ )
568
+ elif name in {"smartTag", "sdt", "sdtContent", "customXml", "fldSimple"}:
569
+ self._inline_runs(child, part, relationships, output, hyperlink)
570
+
571
+ def _table(
572
+ self,
573
+ element: ET.Element,
574
+ part: str,
575
+ relationships: dict[str, _Relationship],
576
+ styles: dict[str, tuple[str, str | None]],
577
+ numbering: dict[int, dict[int, tuple[str, str, int]]],
578
+ ) -> Table:
579
+ rows: list[TableRow] = []
580
+ for row in element.findall("w:tr", _NS):
581
+ cells: list[TableCell] = []
582
+ for cell in row.findall("w:tc", _NS):
583
+ cells.append(
584
+ TableCell(
585
+ self._blocks(cell, part, relationships, styles, numbering)
586
+ )
587
+ )
588
+ rows.append(TableRow(tuple(cells)))
589
+ return Table(tuple(rows), part)
590
+
591
+ def _notes(
592
+ self,
593
+ relationships: dict[str, _Relationship],
594
+ styles: dict[str, tuple[str, str | None]],
595
+ numbering: dict[int, dict[int, tuple[str, str, int]]],
596
+ kind: str,
597
+ ) -> tuple[Note, ...]:
598
+ part = self._related_part(relationships, f"/{kind}")
599
+ if part is None:
600
+ return ()
601
+ root = self._xml(part)
602
+ part_relations = self._relationships(part)
603
+ output: list[Note] = []
604
+ note_tag = "footnote" if kind == "footnotes" else "endnote"
605
+ for note in root:
606
+ if _local_name(note.tag) != note_tag:
607
+ continue
608
+ note_id = _int_attr(note, "id")
609
+ if note_id is None or note_id < 0:
610
+ continue
611
+ output.append(
612
+ Note(
613
+ note_id,
614
+ self._blocks(note, part, part_relations, styles, numbering),
615
+ part,
616
+ )
617
+ )
618
+ return tuple(output)
619
+
620
+
621
+ def _reject_xml_declarations(raw: bytes, part_name: str) -> None:
622
+ parser = expat.ParserCreate()
623
+
624
+ def reject(*_args: object) -> None:
625
+ raise ParseError(
626
+ "unsafe-xml",
627
+ f"DTD and entity declarations are not allowed: {part_name}",
628
+ )
629
+
630
+ parser.StartDoctypeDeclHandler = reject
631
+ parser.EntityDeclHandler = reject
632
+ parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_NEVER)
633
+ try:
634
+ parser.Parse(raw, True)
635
+ except ParseError:
636
+ raise
637
+ except expat.ExpatError:
638
+ # ElementTree below provides the public malformed-XML error.
639
+ return
640
+
641
+
642
+ def _validate_entry_name(name: str) -> None:
643
+ if (
644
+ not name
645
+ or "\x00" in name
646
+ or "\\" in name
647
+ or name.startswith("/")
648
+ or any(piece in {"", ".", ".."} for piece in name.rstrip("/").split("/"))
649
+ or (len(name) >= 2 and name[1] == ":")
650
+ ):
651
+ raise ParseError("invalid-entry-name", f"unsafe ZIP entry name: {name!r}")
652
+
653
+
654
+ def _resolve_target(source_part: str, target: str) -> str:
655
+ if (
656
+ not target
657
+ or "\\" in target
658
+ or "\x00" in target
659
+ or "?" in target
660
+ or "#" in target
661
+ ):
662
+ raise ParseError(
663
+ "invalid-relationship", f"invalid internal relationship target: {target!r}"
664
+ )
665
+ try:
666
+ decoded = unquote(target, errors="strict")
667
+ except UnicodeDecodeError as error:
668
+ raise ParseError(
669
+ "invalid-relationship", f"invalid encoded relationship target: {target!r}"
670
+ ) from error
671
+ if "\\" in decoded or "\x00" in decoded or decoded.startswith("//"):
672
+ raise ParseError(
673
+ "invalid-relationship", f"invalid internal relationship target: {target!r}"
674
+ )
675
+ if decoded.startswith("/"):
676
+ joined = decoded.lstrip("/")
677
+ else:
678
+ joined = posixpath.join(posixpath.dirname(source_part), decoded)
679
+ normalized = posixpath.normpath(joined)
680
+ if normalized in {"", ".", ".."} or normalized.startswith("../"):
681
+ raise ParseError(
682
+ "invalid-relationship", f"relationship escapes package root: {target!r}"
683
+ )
684
+ _validate_entry_name(normalized)
685
+ return normalized
686
+
687
+
688
+ def _local_name(tag: str) -> str:
689
+ match = _QNAME.match(tag)
690
+ return match.group(1) if match else tag
691
+
692
+
693
+ def _int_attr(element: ET.Element, local: str) -> int | None:
694
+ return _int_value(element.get(f"{{{_W}}}{local}"), None)
695
+
696
+
697
+ def _int_value(value: str | None, default: int | None) -> int | None:
698
+ if value is None:
699
+ return default
700
+ try:
701
+ return int(value)
702
+ except ValueError:
703
+ return default
704
+
705
+
706
+ def _child_value(parent: ET.Element, local: str) -> str | None:
707
+ child = parent.find(f"w:{local}", _NS)
708
+ return child.get(f"{{{_W}}}val") if child is not None else None
709
+
710
+
711
+ def _style_name(
712
+ style_id: str | None, styles: dict[str, tuple[str, str | None]]
713
+ ) -> str | None:
714
+ if style_id is None:
715
+ return None
716
+ return styles.get(style_id, (style_id, None))[0]
717
+
718
+
719
+ def _heading_level(
720
+ style_id: str | None,
721
+ style_name: str | None,
722
+ outline_level: int | None,
723
+ styles: dict[str, tuple[str, str | None]],
724
+ ) -> int | None:
725
+ if outline_level is not None and 0 <= outline_level <= 8:
726
+ return outline_level + 1
727
+ current = style_id
728
+ seen: set[str] = set()
729
+ while current is not None and current not in seen:
730
+ seen.add(current)
731
+ name, based_on = styles.get(current, (current, None))
732
+ for candidate in (name, current):
733
+ match = re.fullmatch(r"heading\s*([1-9])", candidate, re.IGNORECASE)
734
+ if match:
735
+ return int(match.group(1))
736
+ current = based_on
737
+ if style_name:
738
+ match = re.fullmatch(r"heading\s*([1-9])", style_name, re.IGNORECASE)
739
+ if match:
740
+ return int(match.group(1))
741
+ return None
742
+
743
+
744
+ def _toggle_property(properties: ET.Element | None, name: str) -> bool:
745
+ if properties is None:
746
+ return False
747
+ element = properties.find(f"w:{name}", _NS)
748
+ if element is None:
749
+ return False
750
+ return element.get(f"{{{_W}}}val", "true").lower() not in {
751
+ "0",
752
+ "false",
753
+ "off",
754
+ "none",
755
+ }
756
+
757
+
758
+ def _run_text(run: ET.Element) -> str:
759
+ output: list[str] = []
760
+
761
+ def collect(parent: ET.Element) -> None:
762
+ for node in parent:
763
+ name = _local_name(node.tag)
764
+ if name in {
765
+ "drawing",
766
+ "pict",
767
+ "object",
768
+ "txbxContent",
769
+ "del",
770
+ "delText",
771
+ "instrText",
772
+ }:
773
+ continue
774
+ if name == "t":
775
+ if node.text:
776
+ output.append(node.text)
777
+ elif name == "tab":
778
+ output.append("\t")
779
+ elif name in {"br", "cr"}:
780
+ output.append("\n")
781
+ elif name == "noBreakHyphen":
782
+ output.append("\u2011")
783
+ elif name == "softHyphen":
784
+ output.append("\u00ad")
785
+ else:
786
+ collect(node)
787
+
788
+ collect(run)
789
+ return "".join(output)
790
+
791
+
792
+ def _block_text(block: Block, counters: dict[int, dict[int, int]]) -> str:
793
+ if isinstance(block, Paragraph):
794
+ text = block.text
795
+ if block.num_id is None or block.list_format is None:
796
+ return text
797
+ levels = counters.setdefault(block.num_id, {})
798
+ for deeper in tuple(levels):
799
+ if deeper > block.list_level:
800
+ del levels[deeper]
801
+ levels[block.list_level] = (
802
+ levels.get(block.list_level, block.list_start - 1) + 1
803
+ )
804
+ return f"{_list_marker(block, levels)} {text}".rstrip()
805
+ rows: list[str] = []
806
+ for row in block.rows:
807
+ cells = [
808
+ "\n".join(_block_text(child, counters) for child in cell.blocks)
809
+ for cell in row.cells
810
+ ]
811
+ rows.append("\t".join(cells))
812
+ return "\n".join(rows)
813
+
814
+
815
+ def _list_marker(paragraph: Paragraph, counters: dict[int, int]) -> str:
816
+ if paragraph.list_format == "bullet":
817
+ marker = paragraph.list_text or "•"
818
+ return marker.replace("%1", "•")
819
+ pattern = paragraph.list_text or "%1."
820
+
821
+ def substitute(match: re.Match[str]) -> str:
822
+ level = int(match.group(1)) - 1
823
+ number = counters.get(
824
+ level,
825
+ paragraph.list_start if level == paragraph.list_level else 1,
826
+ )
827
+ number_format = (
828
+ paragraph.list_format if level == paragraph.list_level else "decimal"
829
+ )
830
+ return _format_number(number, number_format)
831
+
832
+ return re.sub(r"%([1-9])", substitute, pattern)
833
+
834
+
835
+ def _format_number(number: int, number_format: str) -> str:
836
+ if number_format in {"lowerLetter", "upperLetter"}:
837
+ value = number
838
+ letters = ""
839
+ while value > 0:
840
+ value, remainder = divmod(value - 1, 26)
841
+ letters = (
842
+ chr((97 if number_format == "lowerLetter" else 65) + remainder)
843
+ + letters
844
+ )
845
+ return letters or str(number)
846
+ if number_format in {"lowerRoman", "upperRoman"}:
847
+ values = (
848
+ (1000, "M"),
849
+ (900, "CM"),
850
+ (500, "D"),
851
+ (400, "CD"),
852
+ (100, "C"),
853
+ (90, "XC"),
854
+ (50, "L"),
855
+ (40, "XL"),
856
+ (10, "X"),
857
+ (9, "IX"),
858
+ (5, "V"),
859
+ (4, "IV"),
860
+ (1, "I"),
861
+ )
862
+ remainder = number
863
+ output = ""
864
+ for value, numeral in values:
865
+ count, remainder = divmod(remainder, value)
866
+ output += numeral * count
867
+ return output.lower() if number_format == "lowerRoman" else output
868
+ return str(number)
parse_docx/py.typed ADDED
File without changes
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.4
2
+ Name: parse-docx
3
+ Version: 0.1.0
4
+ Summary: Bounded, dependency-free DOCX parsing for Python
5
+ Author: wispsy
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Programming Language :: Python :: 3.14
10
+ Classifier: Typing :: Typed
11
+ Requires-Python: >=3.14
12
+ Project-URL: Repository, https://github.com/wispsy/parse-docx
13
+ Project-URL: Issues, https://github.com/wispsy/parse-docx/issues
14
+ Description-Content-Type: text/markdown
15
+
16
+ # parse-docx
17
+ `parse-docx` is a bounded, dependency-free DOCX parser for Python 3.14+.
18
+ It reads the Office Open XML package without executing or resolving document
19
+ content and returns an immutable, source-part-aware document model.
20
+
21
+ ```python
22
+ from parse_docx import load
23
+
24
+ document = load("report.docx")
25
+ print(document.text)
26
+
27
+ for block in document.blocks:
28
+ print(block.source_part, block)
29
+ ```
30
+
31
+ The model preserves paragraph and table order, run formatting, common heading
32
+ styles, basic list numbering, and inert hyperlink targets. Headers, footers,
33
+ footnotes, and endnotes are available separately. `Document.text` provides a
34
+ safe plain-text projection of the body.
35
+
36
+ See [supported features](docs/supported-features.md) and
37
+ [security boundaries](docs/security.md) for parsing details, limits, and
38
+ unsupported content.
39
+
40
+ ## Development
41
+
42
+ ```sh
43
+ uv sync --locked
44
+ uv run --frozen python -W error::ResourceWarning -m pytest -q
45
+ uv run --frozen python scripts/check_distribution.py --output-dir dist
46
+ ```
47
+
48
+ The distribution is named `parse-docx`; the Python import package is
49
+ `parse_docx`.
50
+
51
+ See [release instructions](docs/releasing.md) for Trusted Publishing setup.
@@ -0,0 +1,7 @@
1
+ parse_docx/__init__.py,sha256=9gIn1obU4Swp3pwLFixhKSo9clFQ2RLioS3yw2d-G9Y,444
2
+ parse_docx/parser.py,sha256=A2nmqMCWqM4HOsXcvQvYKYo9gVakXozzev9KwA00kMw,30382
3
+ parse_docx/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ parse_docx-0.1.0.dist-info/licenses/LICENSE,sha256=dJjxPlUliHO6iuJiKxsIn0HSnRRb-dp_8lpVtAunRj8,1063
5
+ parse_docx-0.1.0.dist-info/WHEEL,sha256=3NO1oYsF7mANFUWVdyEQLM-zmecczWWEmmF5rEbXrWk,80
6
+ parse_docx-0.1.0.dist-info/METADATA,sha256=PW7y4VWl0eMYkJ9sDLu6JgCwZfbQUunn12FQdli7f1k,1645
7
+ parse_docx-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.6
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 wispsy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.