document-to-markdown 0.6.1__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.
- document_converter/__init__.py +7 -0
- document_converter/__main__.py +6 -0
- document_converter/cli.py +182 -0
- document_converter/csv_adapter.py +67 -0
- document_converter/docx_adapter.py +435 -0
- document_converter/email_adapter.py +308 -0
- document_converter/excel_adapter.py +396 -0
- document_converter/html_adapter.py +413 -0
- document_converter/image_adapter.py +161 -0
- document_converter/markdown.py +129 -0
- document_converter/models.py +36 -0
- document_converter/ocr_engine.py +1129 -0
- document_converter/pdf_adapter.py +622 -0
- document_converter/pipeline.py +137 -0
- document_converter/pptx_adapter.py +347 -0
- document_to_markdown-0.6.1.dist-info/METADATA +329 -0
- document_to_markdown-0.6.1.dist-info/RECORD +21 -0
- document_to_markdown-0.6.1.dist-info/WHEEL +5 -0
- document_to_markdown-0.6.1.dist-info/entry_points.txt +2 -0
- document_to_markdown-0.6.1.dist-info/licenses/LICENSE +45 -0
- document_to_markdown-0.6.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""Command-line entry point for the free-form document converter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import getpass
|
|
7
|
+
import logging
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Iterable, List
|
|
11
|
+
|
|
12
|
+
from . import __version__
|
|
13
|
+
from .pipeline import SUPPORTED_SUFFIXES, convert_file
|
|
14
|
+
|
|
15
|
+
SUPPORTED = SUPPORTED_SUFFIXES
|
|
16
|
+
|
|
17
|
+
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _inputs(values: Iterable[str]) -> List[Path]:
|
|
21
|
+
result: List[Path] = []
|
|
22
|
+
for value in values:
|
|
23
|
+
path = Path(value)
|
|
24
|
+
if path.is_dir():
|
|
25
|
+
result.extend(
|
|
26
|
+
sorted(
|
|
27
|
+
item
|
|
28
|
+
for item in path.rglob("*")
|
|
29
|
+
if item.is_file() and item.suffix.lower() in SUPPORTED
|
|
30
|
+
)
|
|
31
|
+
)
|
|
32
|
+
elif path.is_file():
|
|
33
|
+
result.append(path)
|
|
34
|
+
else:
|
|
35
|
+
print(f"[skip] Input not found: {path}", file=sys.stderr)
|
|
36
|
+
return list(dict.fromkeys(result))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _parser() -> argparse.ArgumentParser:
|
|
40
|
+
parser = argparse.ArgumentParser(
|
|
41
|
+
description="Convert PDF, Office (DOCX, PPTX, Excel), Email (EML/MSG), HTML, CSV, and images to AI-friendly Markdown."
|
|
42
|
+
)
|
|
43
|
+
parser.add_argument("inputs", nargs="+", help="Files or directories to convert")
|
|
44
|
+
parser.add_argument("-o", "--output", help="Output .md file or output directory")
|
|
45
|
+
parser.add_argument(
|
|
46
|
+
"--mode",
|
|
47
|
+
choices=["balanced", "fidelity", "ai"],
|
|
48
|
+
default="balanced",
|
|
49
|
+
help="Markdown style: balanced (default), fidelity (more structure), ai (source comments)",
|
|
50
|
+
)
|
|
51
|
+
parser.add_argument(
|
|
52
|
+
"--ocr",
|
|
53
|
+
choices=["off", "auto", "paddle", "tesseract"],
|
|
54
|
+
default="auto",
|
|
55
|
+
help="OCR engine: auto (prefer PaddleOCR / PP-Structure), paddle, tesseract, or off",
|
|
56
|
+
)
|
|
57
|
+
parser.add_argument(
|
|
58
|
+
"--lang",
|
|
59
|
+
default="vie",
|
|
60
|
+
help="OCR language (vie, eng, eng+vie, …). Default 'vie' also handles English/Latin in PaddleOCR.",
|
|
61
|
+
)
|
|
62
|
+
parser.add_argument(
|
|
63
|
+
"--ocr-profile",
|
|
64
|
+
choices=["auto", "mobile", "server"],
|
|
65
|
+
default="auto",
|
|
66
|
+
help="PaddleOCR model profile: auto (library default), mobile (fast/lightweight on CPU), or server (highest accuracy)",
|
|
67
|
+
)
|
|
68
|
+
parser.add_argument(
|
|
69
|
+
"--ocr-version",
|
|
70
|
+
default=None,
|
|
71
|
+
help="PaddleOCR model version (e.g. PP-OCRv5, PP-OCRv4, PP-OCRv3)",
|
|
72
|
+
)
|
|
73
|
+
parser.add_argument(
|
|
74
|
+
"--det-model",
|
|
75
|
+
default=None,
|
|
76
|
+
help="Explicit PaddleOCR text detection model name (e.g. PP-OCRv5_mobile_det)",
|
|
77
|
+
)
|
|
78
|
+
parser.add_argument(
|
|
79
|
+
"--rec-model",
|
|
80
|
+
default=None,
|
|
81
|
+
help="Explicit PaddleOCR text recognition model name (e.g. latin_PP-OCRv5_mobile_rec)",
|
|
82
|
+
)
|
|
83
|
+
parser.add_argument(
|
|
84
|
+
"--no-structure",
|
|
85
|
+
action="store_true",
|
|
86
|
+
help="Disable PP-Structure layout/table analysis (use plain OCR only)",
|
|
87
|
+
)
|
|
88
|
+
parser.add_argument(
|
|
89
|
+
"--assets",
|
|
90
|
+
"--images",
|
|
91
|
+
dest="export_images",
|
|
92
|
+
action="store_true",
|
|
93
|
+
default=False,
|
|
94
|
+
help="Export embedded images / attachments (PDF, DOCX, PPTX, Email) into an _assets directory",
|
|
95
|
+
)
|
|
96
|
+
parser.add_argument(
|
|
97
|
+
"--no-images",
|
|
98
|
+
dest="export_images",
|
|
99
|
+
action="store_false",
|
|
100
|
+
help=argparse.SUPPRESS,
|
|
101
|
+
)
|
|
102
|
+
parser.add_argument(
|
|
103
|
+
"--meta",
|
|
104
|
+
dest="export_meta",
|
|
105
|
+
action="store_true",
|
|
106
|
+
default=False,
|
|
107
|
+
help="Export machine-readable .meta.json sidecar file",
|
|
108
|
+
)
|
|
109
|
+
parser.add_argument(
|
|
110
|
+
"--preview",
|
|
111
|
+
action="store_true",
|
|
112
|
+
help="Convert only the first three PDF pages",
|
|
113
|
+
)
|
|
114
|
+
parser.add_argument(
|
|
115
|
+
"--password",
|
|
116
|
+
action="store_true",
|
|
117
|
+
help="Prompt for a PDF password when needed",
|
|
118
|
+
)
|
|
119
|
+
parser.add_argument(
|
|
120
|
+
"--no-recalculate",
|
|
121
|
+
action="store_true",
|
|
122
|
+
help="Do not ask LibreOffice to recalculate Excel formulas",
|
|
123
|
+
)
|
|
124
|
+
parser.add_argument("--version", action="version", version=__version__)
|
|
125
|
+
parser.add_argument("-v", "--verbose", action="store_true", help="Enable debug logging")
|
|
126
|
+
return parser
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def main(argv: List[str] | None = None) -> int:
|
|
130
|
+
args = _parser().parse_args(argv)
|
|
131
|
+
if args.verbose:
|
|
132
|
+
logging.getLogger().setLevel(logging.DEBUG)
|
|
133
|
+
|
|
134
|
+
sources = _inputs(args.inputs)
|
|
135
|
+
if not sources:
|
|
136
|
+
print("No supported input files found.", file=sys.stderr)
|
|
137
|
+
return 2
|
|
138
|
+
|
|
139
|
+
output_arg = Path(args.output) if args.output else None
|
|
140
|
+
multiple = len(sources) > 1 or any(Path(value).is_dir() for value in args.inputs)
|
|
141
|
+
failures = 0
|
|
142
|
+
for source in sources:
|
|
143
|
+
if output_arg is None:
|
|
144
|
+
target = source.with_suffix(".md")
|
|
145
|
+
elif multiple or output_arg.is_dir() or output_arg.suffix.lower() != ".md":
|
|
146
|
+
target = output_arg / (source.stem + ".md")
|
|
147
|
+
else:
|
|
148
|
+
target = output_arg
|
|
149
|
+
password = (
|
|
150
|
+
getpass.getpass(f"Password for {source.name}: ")
|
|
151
|
+
if args.password and source.suffix.lower() == ".pdf"
|
|
152
|
+
else None
|
|
153
|
+
)
|
|
154
|
+
try:
|
|
155
|
+
result = convert_file(
|
|
156
|
+
source,
|
|
157
|
+
target,
|
|
158
|
+
mode=args.mode,
|
|
159
|
+
ocr=args.ocr,
|
|
160
|
+
ocr_lang=args.lang,
|
|
161
|
+
export_images=args.export_images,
|
|
162
|
+
export_meta=args.export_meta,
|
|
163
|
+
preview=args.preview,
|
|
164
|
+
password=password,
|
|
165
|
+
recalculate=not args.no_recalculate,
|
|
166
|
+
use_structure=not args.no_structure,
|
|
167
|
+
ocr_version=args.ocr_version,
|
|
168
|
+
ocr_profile=args.ocr_profile,
|
|
169
|
+
det_model=args.det_model,
|
|
170
|
+
rec_model=args.rec_model,
|
|
171
|
+
)
|
|
172
|
+
print(f"[ok] {source} -> {result}")
|
|
173
|
+
except Exception as exc:
|
|
174
|
+
failures += 1
|
|
175
|
+
print(f"[error] {source}: {exc}", file=sys.stderr)
|
|
176
|
+
if args.verbose:
|
|
177
|
+
logging.exception("Conversion failed")
|
|
178
|
+
return 1 if failures else 0
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
if __name__ == "__main__":
|
|
182
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""CSV / TSV → Document adapter using Python's standard library csv module."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import io
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import List
|
|
9
|
+
|
|
10
|
+
from .models import Block, Document
|
|
11
|
+
|
|
12
|
+
CSV_SUFFIXES = {".csv", ".tsv"}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _read_text_fallback(path: Path) -> str:
|
|
16
|
+
raw = path.read_bytes()
|
|
17
|
+
for encoding in ("utf-8-sig", "utf-8", "cp1252", "latin-1"):
|
|
18
|
+
try:
|
|
19
|
+
return raw.decode(encoding)
|
|
20
|
+
except UnicodeDecodeError:
|
|
21
|
+
continue
|
|
22
|
+
return raw.decode("utf-8", errors="replace")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _detect_delimiter(text: str, suffix: str) -> str:
|
|
26
|
+
if suffix == ".tsv":
|
|
27
|
+
return "\t"
|
|
28
|
+
sample = "\n".join(text.splitlines()[:20])
|
|
29
|
+
if sample.strip():
|
|
30
|
+
try:
|
|
31
|
+
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
|
|
32
|
+
return dialect.delimiter
|
|
33
|
+
except csv.Error:
|
|
34
|
+
pass
|
|
35
|
+
return ","
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def convert_csv(path: Path) -> Document:
|
|
39
|
+
"""Convert a .csv or .tsv file into a Document with a Markdown table."""
|
|
40
|
+
text = _read_text_fallback(path)
|
|
41
|
+
delimiter = _detect_delimiter(text, path.suffix.lower())
|
|
42
|
+
reader = csv.reader(io.StringIO(text), delimiter=delimiter)
|
|
43
|
+
rows: List[List[str]] = []
|
|
44
|
+
for row in reader:
|
|
45
|
+
cleaned = [cell.strip() for cell in row]
|
|
46
|
+
if any(cleaned):
|
|
47
|
+
rows.append(cleaned)
|
|
48
|
+
|
|
49
|
+
col_count = max((len(r) for r in rows), default=0)
|
|
50
|
+
document = Document(
|
|
51
|
+
str(path),
|
|
52
|
+
path.suffix.lower().lstrip("."),
|
|
53
|
+
path.stem,
|
|
54
|
+
metadata={"rows": len(rows), "columns": col_count, "delimiter": delimiter},
|
|
55
|
+
)
|
|
56
|
+
if rows:
|
|
57
|
+
document.add(
|
|
58
|
+
Block(
|
|
59
|
+
"table",
|
|
60
|
+
rows=rows,
|
|
61
|
+
source={"rows": len(rows)},
|
|
62
|
+
confidence=1.0,
|
|
63
|
+
)
|
|
64
|
+
)
|
|
65
|
+
else:
|
|
66
|
+
document.warn("CSV/TSV file is empty.")
|
|
67
|
+
return document
|
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
"""Word (.docx) → Document adapter using Python's stdlib zipfile + XML parser."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import posixpath
|
|
6
|
+
import re
|
|
7
|
+
import xml.etree.ElementTree as ET
|
|
8
|
+
import zipfile
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Dict, List, Optional, Tuple
|
|
11
|
+
|
|
12
|
+
from .models import Block, Document
|
|
13
|
+
|
|
14
|
+
DOCX_SUFFIXES = {".docx"}
|
|
15
|
+
|
|
16
|
+
_NS = {
|
|
17
|
+
"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
|
|
18
|
+
"r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
|
|
19
|
+
"a": "http://schemas.openxmlformats.org/drawingml/2006/main",
|
|
20
|
+
"v": "urn:schemas-microsoft-com:vml",
|
|
21
|
+
"dc": "http://purl.org/dc/elements/1.1/",
|
|
22
|
+
"rel": "http://schemas.openxmlformats.org/package/2006/relationships",
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
_W = f"{{{_NS['w']}}}"
|
|
26
|
+
_R = f"{{{_NS['r']}}}"
|
|
27
|
+
_A = f"{{{_NS['a']}}}"
|
|
28
|
+
_V = f"{{{_NS['v']}}}"
|
|
29
|
+
|
|
30
|
+
_ORDERED_NUM_FMTS = {
|
|
31
|
+
"decimal",
|
|
32
|
+
"decimalZero",
|
|
33
|
+
"lowerLetter",
|
|
34
|
+
"upperLetter",
|
|
35
|
+
"lowerRoman",
|
|
36
|
+
"upperRoman",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _read_xml(zf: zipfile.ZipFile, member: str) -> Optional[ET.Element]:
|
|
41
|
+
try:
|
|
42
|
+
data = zf.read(member)
|
|
43
|
+
except KeyError:
|
|
44
|
+
return None
|
|
45
|
+
try:
|
|
46
|
+
return ET.fromstring(data)
|
|
47
|
+
except ET.ParseError:
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _read_rels(zf: zipfile.ZipFile, rels_path: str) -> Dict[str, Tuple[str, str]]:
|
|
52
|
+
"""Return {rId: (target, target_mode)} from an OOXML .rels file."""
|
|
53
|
+
root = _read_xml(zf, rels_path)
|
|
54
|
+
if root is None:
|
|
55
|
+
return {}
|
|
56
|
+
rels: Dict[str, Tuple[str, str]] = {}
|
|
57
|
+
for rel in root:
|
|
58
|
+
if rel.tag.endswith("Relationship"):
|
|
59
|
+
rid = rel.attrib.get("Id")
|
|
60
|
+
target = rel.attrib.get("Target", "")
|
|
61
|
+
mode = rel.attrib.get("TargetMode", "")
|
|
62
|
+
if rid:
|
|
63
|
+
rels[rid] = (target, mode)
|
|
64
|
+
return rels
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _resolve_zip_path(base_dir: str, target: str) -> str:
|
|
68
|
+
if target.startswith("/"):
|
|
69
|
+
return target.lstrip("/")
|
|
70
|
+
return posixpath.normpath(posixpath.join(base_dir, target))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _read_core_title(zf: zipfile.ZipFile) -> Optional[str]:
|
|
74
|
+
root = _read_xml(zf, "docProps/core.xml")
|
|
75
|
+
if root is None:
|
|
76
|
+
return None
|
|
77
|
+
title_el = root.find("dc:title", _NS)
|
|
78
|
+
if title_el is not None and title_el.text and title_el.text.strip():
|
|
79
|
+
return title_el.text.strip()
|
|
80
|
+
return None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _parse_styles(zf: zipfile.ZipFile) -> Dict[str, Tuple[str, Optional[int]]]:
|
|
84
|
+
"""Return {styleId: (styleNameLower, outline_level_1_to_6_or_None)}."""
|
|
85
|
+
root = _read_xml(zf, "word/styles.xml")
|
|
86
|
+
if root is None:
|
|
87
|
+
return {}
|
|
88
|
+
styles: Dict[str, Tuple[str, Optional[int]]] = {}
|
|
89
|
+
for style in root.findall("w:style", _NS):
|
|
90
|
+
style_id = style.attrib.get(f"{_W}styleId")
|
|
91
|
+
if not style_id:
|
|
92
|
+
continue
|
|
93
|
+
name_el = style.find("w:name", _NS)
|
|
94
|
+
name = (name_el.attrib.get(f"{_W}val", "") if name_el is not None else "").strip().lower()
|
|
95
|
+
outline_level: Optional[int] = None
|
|
96
|
+
outline_el = style.find("w:pPr/w:outlineLvl", _NS)
|
|
97
|
+
if outline_el is not None:
|
|
98
|
+
raw_val = outline_el.attrib.get(f"{_W}val")
|
|
99
|
+
if raw_val is not None and raw_val.isdigit():
|
|
100
|
+
lvl = int(raw_val)
|
|
101
|
+
if 0 <= lvl <= 5:
|
|
102
|
+
outline_level = lvl + 1
|
|
103
|
+
styles[style_id] = (name, outline_level)
|
|
104
|
+
return styles
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _parse_numbering(zf: zipfile.ZipFile) -> Dict[str, Dict[int, str]]:
|
|
108
|
+
"""Return {numId: {ilvl: numFmt}}."""
|
|
109
|
+
root = _read_xml(zf, "word/numbering.xml")
|
|
110
|
+
if root is None:
|
|
111
|
+
return {}
|
|
112
|
+
abstract_map: Dict[str, Dict[int, str]] = {}
|
|
113
|
+
for ab in root.findall("w:abstractNum", _NS):
|
|
114
|
+
ab_id = ab.attrib.get(f"{_W}abstractNumId")
|
|
115
|
+
if ab_id is None:
|
|
116
|
+
continue
|
|
117
|
+
levels: Dict[int, str] = {}
|
|
118
|
+
for lvl in ab.findall("w:lvl", _NS):
|
|
119
|
+
ilvl_raw = lvl.attrib.get(f"{_W}ilvl", "0")
|
|
120
|
+
fmt_el = lvl.find("w:numFmt", _NS)
|
|
121
|
+
fmt = fmt_el.attrib.get(f"{_W}val", "bullet") if fmt_el is not None else "bullet"
|
|
122
|
+
try:
|
|
123
|
+
levels[int(ilvl_raw)] = fmt
|
|
124
|
+
except ValueError:
|
|
125
|
+
pass
|
|
126
|
+
abstract_map[ab_id] = levels
|
|
127
|
+
|
|
128
|
+
num_map: Dict[str, Dict[int, str]] = {}
|
|
129
|
+
for num in root.findall("w:num", _NS):
|
|
130
|
+
num_id = num.attrib.get(f"{_W}numId")
|
|
131
|
+
ab_ref = num.find("w:abstractNumId", _NS)
|
|
132
|
+
if num_id is not None and ab_ref is not None:
|
|
133
|
+
ab_id = ab_ref.attrib.get(f"{_W}val")
|
|
134
|
+
if ab_id in abstract_map:
|
|
135
|
+
num_map[num_id] = abstract_map[ab_id]
|
|
136
|
+
return num_map
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _heading_level(p: ET.Element, styles: Dict[str, Tuple[str, Optional[int]]]) -> Optional[int]:
|
|
140
|
+
ppr = p.find("w:pPr", _NS)
|
|
141
|
+
if ppr is None:
|
|
142
|
+
return None
|
|
143
|
+
outline_el = ppr.find("w:outlineLvl", _NS)
|
|
144
|
+
if outline_el is not None:
|
|
145
|
+
raw = outline_el.attrib.get(f"{_W}val")
|
|
146
|
+
if raw is not None and raw.isdigit() and 0 <= int(raw) <= 5:
|
|
147
|
+
return int(raw) + 1
|
|
148
|
+
|
|
149
|
+
style_el = ppr.find("w:pStyle", _NS)
|
|
150
|
+
if style_el is not None:
|
|
151
|
+
sid = style_el.attrib.get(f"{_W}val", "")
|
|
152
|
+
style_name, style_outline = styles.get(sid, (sid.lower(), None))
|
|
153
|
+
if style_outline is not None:
|
|
154
|
+
return style_outline
|
|
155
|
+
for candidate in (style_name, sid.lower()):
|
|
156
|
+
if candidate == "title":
|
|
157
|
+
return 1
|
|
158
|
+
if candidate == "subtitle":
|
|
159
|
+
return 2
|
|
160
|
+
m = re.match(r"^(?:heading|titre|überschrift|tiêu đề)\s*(\d)$", candidate)
|
|
161
|
+
if m:
|
|
162
|
+
return max(1, min(6, int(m.group(1))))
|
|
163
|
+
return None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _list_info(
|
|
167
|
+
p: ET.Element, numbering: Dict[str, Dict[int, str]], styles: Dict[str, Tuple[str, Optional[int]]]
|
|
168
|
+
) -> Optional[Tuple[int, bool]]:
|
|
169
|
+
"""Return (indent_level, is_ordered) if paragraph is a list item, else None."""
|
|
170
|
+
ppr = p.find("w:pPr", _NS)
|
|
171
|
+
if ppr is None:
|
|
172
|
+
return None
|
|
173
|
+
num_pr = ppr.find("w:numPr", _NS)
|
|
174
|
+
if num_pr is not None:
|
|
175
|
+
ilvl_el = num_pr.find("w:ilvl", _NS)
|
|
176
|
+
num_id_el = num_pr.find("w:numId", _NS)
|
|
177
|
+
num_id = num_id_el.attrib.get(f"{_W}val") if num_id_el is not None else None
|
|
178
|
+
if num_id == "0":
|
|
179
|
+
return None
|
|
180
|
+
try:
|
|
181
|
+
ilvl = int(ilvl_el.attrib.get(f"{_W}val", "0")) if ilvl_el is not None else 0
|
|
182
|
+
except ValueError:
|
|
183
|
+
ilvl = 0
|
|
184
|
+
fmt = numbering.get(num_id or "", {}).get(ilvl, "bullet")
|
|
185
|
+
return (max(0, ilvl), fmt in _ORDERED_NUM_FMTS)
|
|
186
|
+
|
|
187
|
+
style_el = ppr.find("w:pStyle", _NS)
|
|
188
|
+
if style_el is not None:
|
|
189
|
+
sid = style_el.attrib.get(f"{_W}val", "")
|
|
190
|
+
style_name = styles.get(sid, (sid.lower(), None))[0]
|
|
191
|
+
if "list bullet" in style_name or style_name == "listbullet":
|
|
192
|
+
return (0, False)
|
|
193
|
+
if "list number" in style_name or style_name == "listnumber":
|
|
194
|
+
return (0, True)
|
|
195
|
+
return None
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _extract_runs_text(
|
|
199
|
+
node: ET.Element, rels: Dict[str, Tuple[str, str]]
|
|
200
|
+
) -> Tuple[str, List[str]]:
|
|
201
|
+
"""Extract paragraph text (ignoring tracked deletions) and embedded image rIds."""
|
|
202
|
+
parts: List[str] = []
|
|
203
|
+
image_rids: List[str] = []
|
|
204
|
+
|
|
205
|
+
def walk(el: ET.Element) -> None:
|
|
206
|
+
tag = el.tag
|
|
207
|
+
if tag == f"{_W}del" or tag == f"{_W}instrText":
|
|
208
|
+
return
|
|
209
|
+
if tag == f"{_W}hyperlink":
|
|
210
|
+
rid = el.attrib.get(f"{_R}id")
|
|
211
|
+
sub_parts: List[str] = []
|
|
212
|
+
for child in el:
|
|
213
|
+
txt, imgs = _extract_runs_text(child, rels)
|
|
214
|
+
sub_parts.append(txt)
|
|
215
|
+
image_rids.extend(imgs)
|
|
216
|
+
link_text = "".join(sub_parts).strip()
|
|
217
|
+
target = rels.get(rid or "", ("", ""))[0] if rid else ""
|
|
218
|
+
if target.startswith(("http://", "https://")) and link_text and link_text != target:
|
|
219
|
+
parts.append(f"{link_text} ({target})")
|
|
220
|
+
else:
|
|
221
|
+
parts.append(link_text or target)
|
|
222
|
+
return
|
|
223
|
+
if tag == f"{_W}t":
|
|
224
|
+
if el.text:
|
|
225
|
+
parts.append(el.text)
|
|
226
|
+
return
|
|
227
|
+
if tag == f"{_W}tab":
|
|
228
|
+
parts.append(" ")
|
|
229
|
+
return
|
|
230
|
+
if tag in {f"{_W}br", f"{_W}cr"}:
|
|
231
|
+
parts.append("\n")
|
|
232
|
+
return
|
|
233
|
+
if tag == f"{_A}blip":
|
|
234
|
+
rid = el.attrib.get(f"{_R}embed")
|
|
235
|
+
if rid:
|
|
236
|
+
image_rids.append(rid)
|
|
237
|
+
return
|
|
238
|
+
if tag == f"{_V}imagedata":
|
|
239
|
+
rid = el.attrib.get(f"{_R}id")
|
|
240
|
+
if rid:
|
|
241
|
+
image_rids.append(rid)
|
|
242
|
+
return
|
|
243
|
+
for child in el:
|
|
244
|
+
walk(child)
|
|
245
|
+
|
|
246
|
+
walk(node)
|
|
247
|
+
text = "".join(parts)
|
|
248
|
+
text = re.sub(r"[ \t]+", " ", text)
|
|
249
|
+
text = re.sub(r" *\n *", "\n", text).strip()
|
|
250
|
+
return text, image_rids
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _extract_table(tbl: ET.Element, rels: Dict[str, Tuple[str, str]]) -> List[List[str]]:
|
|
254
|
+
rows: List[List[str]] = []
|
|
255
|
+
for tr in tbl.findall("w:tr", _NS):
|
|
256
|
+
row_cells: List[str] = []
|
|
257
|
+
for tc in tr.findall("w:tc", _NS):
|
|
258
|
+
tcpr = tc.find("w:tcPr", _NS)
|
|
259
|
+
grid_span = 1
|
|
260
|
+
is_vmerge_cont = False
|
|
261
|
+
if tcpr is not None:
|
|
262
|
+
span_el = tcpr.find("w:gridSpan", _NS)
|
|
263
|
+
if span_el is not None:
|
|
264
|
+
try:
|
|
265
|
+
grid_span = max(1, int(span_el.attrib.get(f"{_W}val", "1")))
|
|
266
|
+
except ValueError:
|
|
267
|
+
grid_span = 1
|
|
268
|
+
vmerge_el = tcpr.find("w:vMerge", _NS)
|
|
269
|
+
if vmerge_el is not None and vmerge_el.attrib.get(f"{_W}val") != "restart":
|
|
270
|
+
is_vmerge_cont = True
|
|
271
|
+
|
|
272
|
+
if is_vmerge_cont:
|
|
273
|
+
cell_text = ""
|
|
274
|
+
else:
|
|
275
|
+
para_texts: List[str] = []
|
|
276
|
+
for p in tc.findall("w:p", _NS):
|
|
277
|
+
t, _ = _extract_runs_text(p, rels)
|
|
278
|
+
if t:
|
|
279
|
+
para_texts.append(t)
|
|
280
|
+
cell_text = "\n".join(para_texts)
|
|
281
|
+
|
|
282
|
+
row_cells.append(cell_text)
|
|
283
|
+
for _ in range(grid_span - 1):
|
|
284
|
+
row_cells.append("")
|
|
285
|
+
if any(c.strip() for c in row_cells):
|
|
286
|
+
rows.append(row_cells)
|
|
287
|
+
return rows
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _iter_body_elements(container: ET.Element) -> List[ET.Element]:
|
|
291
|
+
items: List[ET.Element] = []
|
|
292
|
+
for child in container:
|
|
293
|
+
if child.tag in {f"{_W}p", f"{_W}tbl"}:
|
|
294
|
+
items.append(child)
|
|
295
|
+
elif child.tag == f"{_W}sdt":
|
|
296
|
+
content = child.find("w:sdtContent", _NS)
|
|
297
|
+
if content is not None:
|
|
298
|
+
items.extend(_iter_body_elements(content))
|
|
299
|
+
return items
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def convert_docx(path: Path, output_assets: Optional[Path] = None) -> Document:
|
|
303
|
+
"""Convert a .docx Word document into a structured Document."""
|
|
304
|
+
if not zipfile.is_zipfile(path):
|
|
305
|
+
raise RuntimeError(f"Not a valid .docx archive: {path}")
|
|
306
|
+
|
|
307
|
+
with zipfile.ZipFile(path, "r") as zf:
|
|
308
|
+
doc_root = _read_xml(zf, "word/document.xml")
|
|
309
|
+
if doc_root is None:
|
|
310
|
+
raise RuntimeError(f"Missing word/document.xml inside {path}")
|
|
311
|
+
body = doc_root.find("w:body", _NS)
|
|
312
|
+
if body is None:
|
|
313
|
+
raise RuntimeError(f"Malformed word/document.xml inside {path}")
|
|
314
|
+
|
|
315
|
+
title = _read_core_title(zf) or path.stem
|
|
316
|
+
styles = _parse_styles(zf)
|
|
317
|
+
numbering = _parse_numbering(zf)
|
|
318
|
+
rels = _read_rels(zf, "word/_rels/document.xml.rels")
|
|
319
|
+
|
|
320
|
+
document = Document(str(path), "docx", title, metadata={})
|
|
321
|
+
list_lines: List[str] = []
|
|
322
|
+
list_counters: Dict[int, int] = {}
|
|
323
|
+
image_count = 0
|
|
324
|
+
table_count = 0
|
|
325
|
+
para_index = 0
|
|
326
|
+
|
|
327
|
+
def flush_list() -> None:
|
|
328
|
+
if list_lines:
|
|
329
|
+
document.add(Block("list", "\n".join(list_lines), source={"section": "body"}))
|
|
330
|
+
list_lines.clear()
|
|
331
|
+
list_counters.clear()
|
|
332
|
+
|
|
333
|
+
for elem in _iter_body_elements(body):
|
|
334
|
+
if elem.tag == f"{_W}tbl":
|
|
335
|
+
flush_list()
|
|
336
|
+
rows = _extract_table(elem, rels)
|
|
337
|
+
if rows:
|
|
338
|
+
table_count += 1
|
|
339
|
+
document.add(
|
|
340
|
+
Block(
|
|
341
|
+
"table",
|
|
342
|
+
rows=rows,
|
|
343
|
+
source={"table": table_count},
|
|
344
|
+
confidence=1.0,
|
|
345
|
+
)
|
|
346
|
+
)
|
|
347
|
+
continue
|
|
348
|
+
|
|
349
|
+
para_index += 1
|
|
350
|
+
text, img_rids = _extract_runs_text(elem, rels)
|
|
351
|
+
heading_lvl = _heading_level(elem, styles)
|
|
352
|
+
list_meta = None if heading_lvl is not None else _list_info(elem, numbering, styles)
|
|
353
|
+
|
|
354
|
+
if heading_lvl is not None and text:
|
|
355
|
+
flush_list()
|
|
356
|
+
document.add(
|
|
357
|
+
Block(
|
|
358
|
+
"heading",
|
|
359
|
+
text.replace("\n", " "),
|
|
360
|
+
source={"paragraph": para_index},
|
|
361
|
+
metadata={"level": heading_lvl},
|
|
362
|
+
)
|
|
363
|
+
)
|
|
364
|
+
elif list_meta is not None and text:
|
|
365
|
+
ilvl, is_ordered = list_meta
|
|
366
|
+
for k in list(list_counters.keys()):
|
|
367
|
+
if k > ilvl:
|
|
368
|
+
del list_counters[k]
|
|
369
|
+
indent = " " * min(ilvl, 4)
|
|
370
|
+
if is_ordered:
|
|
371
|
+
list_counters[ilvl] = list_counters.get(ilvl, 0) + 1
|
|
372
|
+
marker = f"{list_counters[ilvl]}. "
|
|
373
|
+
else:
|
|
374
|
+
marker = "- "
|
|
375
|
+
list_lines.append(f"{indent}{marker}{text.replace(chr(10), ' ')}")
|
|
376
|
+
elif text:
|
|
377
|
+
flush_list()
|
|
378
|
+
document.add(Block("paragraph", text, source={"paragraph": para_index}))
|
|
379
|
+
elif img_rids:
|
|
380
|
+
flush_list()
|
|
381
|
+
|
|
382
|
+
if output_assets is not None and img_rids:
|
|
383
|
+
output_assets.mkdir(parents=True, exist_ok=True)
|
|
384
|
+
for rid in img_rids:
|
|
385
|
+
target, mode = rels.get(rid, ("", ""))
|
|
386
|
+
if not target or mode.lower() == "external":
|
|
387
|
+
continue
|
|
388
|
+
zip_member = _resolve_zip_path("word", target)
|
|
389
|
+
try:
|
|
390
|
+
img_bytes = zf.read(zip_member)
|
|
391
|
+
except KeyError:
|
|
392
|
+
continue
|
|
393
|
+
image_count += 1
|
|
394
|
+
ext = Path(zip_member).suffix.lower() or ".png"
|
|
395
|
+
filename = f"docx-image-{image_count:02d}{ext}"
|
|
396
|
+
(output_assets / filename).write_bytes(img_bytes)
|
|
397
|
+
document.add(
|
|
398
|
+
Block(
|
|
399
|
+
"image",
|
|
400
|
+
filename,
|
|
401
|
+
source={"paragraph": para_index},
|
|
402
|
+
metadata={"alt": f"Embedded image {image_count}"},
|
|
403
|
+
)
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
flush_list()
|
|
407
|
+
|
|
408
|
+
# Optional footnotes
|
|
409
|
+
fn_root = _read_xml(zf, "word/footnotes.xml")
|
|
410
|
+
if fn_root is not None:
|
|
411
|
+
fn_lines: List[str] = []
|
|
412
|
+
for fn in fn_root.findall("w:footnote", _NS):
|
|
413
|
+
fn_type = fn.attrib.get(f"{_W}type", "")
|
|
414
|
+
if fn_type in {"separator", "continuationSeparator"}:
|
|
415
|
+
continue
|
|
416
|
+
fn_id = fn.attrib.get(f"{_W}id", "")
|
|
417
|
+
texts = []
|
|
418
|
+
for p in fn.findall("w:p", _NS):
|
|
419
|
+
t, _ = _extract_runs_text(p, rels)
|
|
420
|
+
if t:
|
|
421
|
+
texts.append(t)
|
|
422
|
+
joined = " ".join(texts).strip()
|
|
423
|
+
if joined:
|
|
424
|
+
prefix = f"{fn_id}. " if fn_id.isdigit() else "- "
|
|
425
|
+
fn_lines.append(prefix + joined)
|
|
426
|
+
if fn_lines:
|
|
427
|
+
document.add(
|
|
428
|
+
Block("heading", "Footnotes", source={"section": "footnotes"}, metadata={"level": 2})
|
|
429
|
+
)
|
|
430
|
+
document.add(Block("list", "\n".join(fn_lines), source={"section": "footnotes"}))
|
|
431
|
+
|
|
432
|
+
document.metadata.update({"tables": table_count, "exported_images": image_count})
|
|
433
|
+
if not document.blocks:
|
|
434
|
+
document.warn("DOCX file contained no extractable text or tables.")
|
|
435
|
+
return document
|