@blackbelt-technology/pi-dashboard-document-converter 0.5.4
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.
- package/.pi/skills/document-converter/SKILL.md +79 -0
- package/README.md +106 -0
- package/engine/.dockerignore +4 -0
- package/engine/Dockerfile +75 -0
- package/engine/IMAGE_VERSION +1 -0
- package/engine/README.md +65 -0
- package/engine/VENDOR.md +40 -0
- package/engine/build-image.sh +29 -0
- package/engine/document_converter/LICENSE +21 -0
- package/engine/document_converter/__init__.py +365 -0
- package/engine/document_converter/__main__.py +5 -0
- package/engine/document_converter/asciidoc_converter.py +534 -0
- package/engine/document_converter/cli.py +751 -0
- package/engine/document_converter/code_renderer.py +356 -0
- package/engine/document_converter/converter.py +928 -0
- package/engine/document_converter/cover_page.py +448 -0
- package/engine/document_converter/diagram_resizer.py +311 -0
- package/engine/document_converter/diagram_sizing.py +357 -0
- package/engine/document_converter/docx_reader.py +627 -0
- package/engine/document_converter/field_updater.py +277 -0
- package/engine/document_converter/font_manager.py +850 -0
- package/engine/document_converter/frontmatter_parser.py +644 -0
- package/engine/document_converter/graphviz_renderer.py +354 -0
- package/engine/document_converter/image_extractor.py +281 -0
- package/engine/document_converter/image_style.py +237 -0
- package/engine/document_converter/logo_manager.py +1021 -0
- package/engine/document_converter/manifest_manager.py +288 -0
- package/engine/document_converter/mermaid_renderer.py +371 -0
- package/engine/document_converter/meta_mapper.py +398 -0
- package/engine/document_converter/pandoc_styles.py +222 -0
- package/engine/document_converter/pdf_converter.py +735 -0
- package/engine/document_converter/pdf_server.py +283 -0
- package/engine/document_converter/plantuml_renderer.py +460 -0
- package/engine/document_converter/plantuml_server.py +273 -0
- package/engine/document_converter/pyproject.toml +80 -0
- package/engine/document_converter/round_trip.py +312 -0
- package/engine/document_converter/spacing_applier.py +332 -0
- package/engine/document_converter/spacing_config.py +323 -0
- package/engine/document_converter/style_extractor.py +420 -0
- package/engine/document_converter/svg_embedder.py +294 -0
- package/engine/document_converter/system_variables.py +158 -0
- package/engine/document_converter/table_formatter.py +450 -0
- package/engine/document_converter/template_extractor.py +1334 -0
- package/engine/document_converter/template_manager.py +427 -0
- package/engine/document_converter/textbox_extractor.py +551 -0
- package/engine/document_converter/toc_generator.py +559 -0
- package/engine/document_converter/toc_style.py +290 -0
- package/engine/document_converter/tree_renderer.py +328 -0
- package/engine/document_converter/utils.py +134 -0
- package/engine/document_converter/variable_manager.py +394 -0
- package/engine/engine_cli.py +371 -0
- package/engine/frontmatter_filler/doc-meta.sample.yaml +106 -0
- package/engine/frontmatter_filler/fill.py +517 -0
- package/engine/markdown_table_profiler/profile.py +442 -0
- package/engine/nano-banana-styles.yaml +59 -0
- package/engine/tests/test_styled_diagrams.py +109 -0
- package/package.json +32 -0
- package/src/__tests__/engine.test.ts +72 -0
- package/src/__tests__/facade.test.ts +120 -0
- package/src/__tests__/integration.test.ts +101 -0
- package/src/__tests__/ocr.test.ts +34 -0
- package/src/__tests__/provenance.test.ts +89 -0
- package/src/__tests__/routing.test.ts +40 -0
- package/src/engine.ts +187 -0
- package/src/errors.ts +43 -0
- package/src/index.ts +179 -0
- package/src/ocr.ts +43 -0
- package/src/provenance.ts +79 -0
- package/src/routing.ts +49 -0
- package/src/schema.json +69 -0
- package/src/schema.ts +107 -0
- package/src/types.ts +90 -0
|
@@ -0,0 +1,627 @@
|
|
|
1
|
+
"""DOCX to Markdown extraction module."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import List, Dict, Tuple, Optional, Any
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from docx import Document
|
|
6
|
+
from docx.document import Document as DocxDocument
|
|
7
|
+
from docx.text.paragraph import Paragraph
|
|
8
|
+
from docx.table import Table
|
|
9
|
+
from docx.oxml.ns import qn
|
|
10
|
+
import re
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class ExtractedElement:
|
|
15
|
+
"""Represents an extracted document element."""
|
|
16
|
+
type: str # 'heading', 'paragraph', 'list_item', 'table', 'image'
|
|
17
|
+
content: str
|
|
18
|
+
level: int = 0 # For headings (1-6) or list nesting
|
|
19
|
+
style_name: str = ""
|
|
20
|
+
docx_path: str = "" # XPath-like reference to original element
|
|
21
|
+
line_start: int = 0
|
|
22
|
+
line_end: int = 0
|
|
23
|
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class ExtractionResult:
|
|
28
|
+
"""Result of DOCX extraction."""
|
|
29
|
+
markdown: str
|
|
30
|
+
elements: List[ExtractedElement]
|
|
31
|
+
preserved_elements: List[Dict[str, Any]]
|
|
32
|
+
images: List[Dict[str, Any]]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def get_paragraph_style_level(paragraph: Paragraph) -> Tuple[str, int]:
|
|
36
|
+
"""Determine the type and level of a paragraph based on its style.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
paragraph: The paragraph to analyze.
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
Tuple of (element_type, level) where element_type is 'heading',
|
|
43
|
+
'list_item', or 'paragraph'.
|
|
44
|
+
"""
|
|
45
|
+
style_name = paragraph.style.name if paragraph.style else ""
|
|
46
|
+
|
|
47
|
+
# Check for heading styles
|
|
48
|
+
if style_name.startswith('Heading'):
|
|
49
|
+
try:
|
|
50
|
+
level = int(style_name.split()[-1])
|
|
51
|
+
return ('heading', min(level, 6))
|
|
52
|
+
except (ValueError, IndexError):
|
|
53
|
+
pass
|
|
54
|
+
|
|
55
|
+
# Check for Title style (treat as H1)
|
|
56
|
+
if style_name == 'Title':
|
|
57
|
+
return ('heading', 1)
|
|
58
|
+
|
|
59
|
+
# Check for Subtitle style (treat as H2)
|
|
60
|
+
if style_name == 'Subtitle':
|
|
61
|
+
return ('heading', 2)
|
|
62
|
+
|
|
63
|
+
# Check for list styles
|
|
64
|
+
if 'List' in style_name or 'Bullet' in style_name:
|
|
65
|
+
return ('list_item', 1)
|
|
66
|
+
|
|
67
|
+
return ('paragraph', 0)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def get_list_info(paragraph: Paragraph) -> Tuple[bool, bool, int]:
|
|
71
|
+
"""Check if paragraph is a list item and get its properties.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
paragraph: The paragraph to check.
|
|
75
|
+
|
|
76
|
+
Returns:
|
|
77
|
+
Tuple of (is_list, is_numbered, indent_level).
|
|
78
|
+
"""
|
|
79
|
+
# Check for numbering in the paragraph's XML
|
|
80
|
+
pPr = paragraph._element.pPr
|
|
81
|
+
if pPr is None:
|
|
82
|
+
return (False, False, 0)
|
|
83
|
+
|
|
84
|
+
numPr = pPr.find(qn('w:numPr'))
|
|
85
|
+
if numPr is None:
|
|
86
|
+
return (False, False, 0)
|
|
87
|
+
|
|
88
|
+
# Get indent level
|
|
89
|
+
ilvl = numPr.find(qn('w:ilvl'))
|
|
90
|
+
indent_level = int(ilvl.get(qn('w:val'))) if ilvl is not None else 0
|
|
91
|
+
|
|
92
|
+
# Check if numbered (vs bullet)
|
|
93
|
+
numId = numPr.find(qn('w:numId'))
|
|
94
|
+
is_numbered = False
|
|
95
|
+
if numId is not None:
|
|
96
|
+
# NumId > 0 indicates a list; we'd need to check the numbering definitions
|
|
97
|
+
# for now, assume non-zero numId with certain patterns are numbered
|
|
98
|
+
num_val = numId.get(qn('w:val'))
|
|
99
|
+
# This is a simplification - proper detection requires checking abstractNum
|
|
100
|
+
is_numbered = num_val is not None and int(num_val) > 0
|
|
101
|
+
|
|
102
|
+
return (True, is_numbered, indent_level)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def parse_paragraph(paragraph: Paragraph, index: int) -> ExtractedElement:
|
|
106
|
+
"""Parse a single paragraph into an ExtractedElement.
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
paragraph: The paragraph to parse.
|
|
110
|
+
index: The paragraph index in the document.
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
ExtractedElement with parsed content.
|
|
114
|
+
"""
|
|
115
|
+
text = paragraph.text.strip()
|
|
116
|
+
style_name = paragraph.style.name if paragraph.style else ""
|
|
117
|
+
element_type, level = get_paragraph_style_level(paragraph)
|
|
118
|
+
|
|
119
|
+
# Check for list formatting
|
|
120
|
+
is_list, is_numbered, indent_level = get_list_info(paragraph)
|
|
121
|
+
if is_list:
|
|
122
|
+
element_type = 'list_item'
|
|
123
|
+
level = indent_level
|
|
124
|
+
|
|
125
|
+
return ExtractedElement(
|
|
126
|
+
type=element_type,
|
|
127
|
+
content=text,
|
|
128
|
+
level=level,
|
|
129
|
+
style_name=style_name,
|
|
130
|
+
docx_path=f"/w:body/w:p[{index + 1}]",
|
|
131
|
+
metadata={
|
|
132
|
+
'is_numbered': is_numbered if is_list else None,
|
|
133
|
+
'indent_level': indent_level if is_list else None,
|
|
134
|
+
}
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def parse_table(table: Table, index: int) -> ExtractedElement:
|
|
139
|
+
"""Parse a table into Markdown format.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
table: The table to parse.
|
|
143
|
+
index: The table index in the document.
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
ExtractedElement with Markdown table content.
|
|
147
|
+
"""
|
|
148
|
+
rows = []
|
|
149
|
+
for row in table.rows:
|
|
150
|
+
cells = [cell.text.strip().replace('|', '\\|') for cell in row.cells]
|
|
151
|
+
rows.append(cells)
|
|
152
|
+
|
|
153
|
+
if not rows:
|
|
154
|
+
return ExtractedElement(
|
|
155
|
+
type='table',
|
|
156
|
+
content='',
|
|
157
|
+
docx_path=f"/w:body/w:tbl[{index + 1}]"
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
# Build Markdown table
|
|
161
|
+
md_lines = []
|
|
162
|
+
|
|
163
|
+
# Header row
|
|
164
|
+
header = rows[0]
|
|
165
|
+
md_lines.append('| ' + ' | '.join(header) + ' |')
|
|
166
|
+
|
|
167
|
+
# Separator
|
|
168
|
+
md_lines.append('| ' + ' | '.join(['---'] * len(header)) + ' |')
|
|
169
|
+
|
|
170
|
+
# Data rows
|
|
171
|
+
for row in rows[1:]:
|
|
172
|
+
# Pad row if necessary
|
|
173
|
+
while len(row) < len(header):
|
|
174
|
+
row.append('')
|
|
175
|
+
md_lines.append('| ' + ' | '.join(row[:len(header)]) + ' |')
|
|
176
|
+
|
|
177
|
+
return ExtractedElement(
|
|
178
|
+
type='table',
|
|
179
|
+
content='\n'.join(md_lines),
|
|
180
|
+
docx_path=f"/w:body/w:tbl[{index + 1}]",
|
|
181
|
+
metadata={'rows': len(rows), 'cols': len(header) if header else 0}
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def extract_table_style(table: Table) -> Dict[str, Any]:
|
|
186
|
+
"""Extract style information from a table.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
table: The table to extract styles from.
|
|
190
|
+
|
|
191
|
+
Returns:
|
|
192
|
+
Dictionary with table style properties.
|
|
193
|
+
"""
|
|
194
|
+
style: Dict[str, Any] = {}
|
|
195
|
+
|
|
196
|
+
# Try to get table properties
|
|
197
|
+
tbl = table._tbl
|
|
198
|
+
tbl_pr = tbl.find(qn('w:tblPr'))
|
|
199
|
+
|
|
200
|
+
if tbl_pr is not None:
|
|
201
|
+
# Check for table style reference
|
|
202
|
+
tbl_style = tbl_pr.find(qn('w:tblStyle'))
|
|
203
|
+
if tbl_style is not None:
|
|
204
|
+
style['style_name'] = tbl_style.get(qn('w:val'))
|
|
205
|
+
|
|
206
|
+
# Extract styles from first row (header)
|
|
207
|
+
if table.rows:
|
|
208
|
+
header_row = table.rows[0]
|
|
209
|
+
for cell in header_row.cells:
|
|
210
|
+
tc = cell._tc
|
|
211
|
+
tcPr = tc.find(qn('w:tcPr'))
|
|
212
|
+
if tcPr is not None:
|
|
213
|
+
# Check for shading (background color)
|
|
214
|
+
shd = tcPr.find(qn('w:shd'))
|
|
215
|
+
if shd is not None:
|
|
216
|
+
fill = shd.get(qn('w:fill'))
|
|
217
|
+
if fill and fill != 'auto':
|
|
218
|
+
style['header_bg_color'] = fill
|
|
219
|
+
|
|
220
|
+
# Check for borders
|
|
221
|
+
tcBorders = tcPr.find(qn('w:tcBorders'))
|
|
222
|
+
if tcBorders is not None:
|
|
223
|
+
# Get border properties from any border
|
|
224
|
+
for border_name in ['top', 'left', 'bottom', 'right']:
|
|
225
|
+
border = tcBorders.find(qn(f'w:{border_name}'))
|
|
226
|
+
if border is not None:
|
|
227
|
+
border_color = border.get(qn('w:color'))
|
|
228
|
+
if border_color:
|
|
229
|
+
style['border_color'] = border_color
|
|
230
|
+
border_size = border.get(qn('w:sz'))
|
|
231
|
+
if border_size:
|
|
232
|
+
style['border_size'] = int(border_size)
|
|
233
|
+
break
|
|
234
|
+
|
|
235
|
+
# Check for text color in header
|
|
236
|
+
for para in cell.paragraphs:
|
|
237
|
+
for run in para.runs:
|
|
238
|
+
if run.font.color.rgb:
|
|
239
|
+
# Convert RGBColor to hex string
|
|
240
|
+
rgb = run.font.color.rgb
|
|
241
|
+
style['header_text_color'] = f"{rgb}"
|
|
242
|
+
break
|
|
243
|
+
break
|
|
244
|
+
break
|
|
245
|
+
|
|
246
|
+
# Check for alternating row colors (striping)
|
|
247
|
+
if len(table.rows) > 2:
|
|
248
|
+
row1_color = None
|
|
249
|
+
row2_color = None
|
|
250
|
+
|
|
251
|
+
# Check second row
|
|
252
|
+
if len(table.rows) > 1:
|
|
253
|
+
for cell in table.rows[1].cells:
|
|
254
|
+
tcPr = cell._tc.find(qn('w:tcPr'))
|
|
255
|
+
if tcPr is not None:
|
|
256
|
+
shd = tcPr.find(qn('w:shd'))
|
|
257
|
+
if shd is not None:
|
|
258
|
+
row1_color = shd.get(qn('w:fill'))
|
|
259
|
+
break
|
|
260
|
+
|
|
261
|
+
# Check third row
|
|
262
|
+
if len(table.rows) > 2:
|
|
263
|
+
for cell in table.rows[2].cells:
|
|
264
|
+
tcPr = cell._tc.find(qn('w:tcPr'))
|
|
265
|
+
if tcPr is not None:
|
|
266
|
+
shd = tcPr.find(qn('w:shd'))
|
|
267
|
+
if shd is not None:
|
|
268
|
+
row2_color = shd.get(qn('w:fill'))
|
|
269
|
+
break
|
|
270
|
+
|
|
271
|
+
# If colors alternate, it's striped
|
|
272
|
+
if row1_color and row2_color and row1_color != row2_color:
|
|
273
|
+
style['striped'] = True
|
|
274
|
+
style['odd_row_color'] = row1_color
|
|
275
|
+
style['even_row_color'] = row2_color
|
|
276
|
+
elif row1_color:
|
|
277
|
+
style['striped'] = False
|
|
278
|
+
|
|
279
|
+
return style
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def extract_table_styles(doc: DocxDocument) -> Dict[str, Any]:
|
|
283
|
+
"""Extract default table style from document.
|
|
284
|
+
|
|
285
|
+
Args:
|
|
286
|
+
doc: The document to extract styles from.
|
|
287
|
+
|
|
288
|
+
Returns:
|
|
289
|
+
Dictionary with default table style (from most common style).
|
|
290
|
+
"""
|
|
291
|
+
if not doc.tables:
|
|
292
|
+
return {}
|
|
293
|
+
|
|
294
|
+
# Collect styles from all tables
|
|
295
|
+
all_styles = []
|
|
296
|
+
for table in doc.tables:
|
|
297
|
+
style = extract_table_style(table)
|
|
298
|
+
if style:
|
|
299
|
+
all_styles.append(style)
|
|
300
|
+
|
|
301
|
+
if not all_styles:
|
|
302
|
+
return {}
|
|
303
|
+
|
|
304
|
+
# Return most common style properties
|
|
305
|
+
# For simplicity, use the first table's style as default
|
|
306
|
+
return all_styles[0] if all_styles else {}
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def extract_per_table_styles(doc: DocxDocument) -> List[Dict[str, Any]]:
|
|
310
|
+
"""Extract per-table style overrides.
|
|
311
|
+
|
|
312
|
+
Args:
|
|
313
|
+
doc: The document to analyze.
|
|
314
|
+
|
|
315
|
+
Returns:
|
|
316
|
+
List of style dictionaries for tables that differ from default.
|
|
317
|
+
"""
|
|
318
|
+
if not doc.tables:
|
|
319
|
+
return []
|
|
320
|
+
|
|
321
|
+
# Get default style from first table
|
|
322
|
+
default_style = extract_table_style(doc.tables[0]) if doc.tables else {}
|
|
323
|
+
|
|
324
|
+
per_table_styles = []
|
|
325
|
+
for i, table in enumerate(doc.tables):
|
|
326
|
+
table_style = extract_table_style(table)
|
|
327
|
+
|
|
328
|
+
# Check if this table differs from default
|
|
329
|
+
diff_style = {}
|
|
330
|
+
for key, value in table_style.items():
|
|
331
|
+
if default_style.get(key) != value:
|
|
332
|
+
diff_style[key] = value
|
|
333
|
+
|
|
334
|
+
if diff_style:
|
|
335
|
+
diff_style['table_index'] = i
|
|
336
|
+
per_table_styles.append(diff_style)
|
|
337
|
+
|
|
338
|
+
return per_table_styles
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def calculate_column_widths(table: Table) -> Dict[str, float]:
|
|
342
|
+
"""Calculate column width multipliers for a table.
|
|
343
|
+
|
|
344
|
+
Args:
|
|
345
|
+
table: The table to analyze.
|
|
346
|
+
|
|
347
|
+
Returns:
|
|
348
|
+
Dictionary mapping column header text to width multipliers.
|
|
349
|
+
"""
|
|
350
|
+
if not table.rows:
|
|
351
|
+
return {}
|
|
352
|
+
|
|
353
|
+
header_row = table.rows[0]
|
|
354
|
+
widths: Dict[str, float] = {}
|
|
355
|
+
total_width = 0
|
|
356
|
+
cell_widths = []
|
|
357
|
+
|
|
358
|
+
# Get widths from each header cell
|
|
359
|
+
for cell in header_row.cells:
|
|
360
|
+
cell_text = cell.text.strip()
|
|
361
|
+
tcPr = cell._tc.find(qn('w:tcPr'))
|
|
362
|
+
|
|
363
|
+
width = 1.0 # Default width
|
|
364
|
+
if tcPr is not None:
|
|
365
|
+
tcW = tcPr.find(qn('w:tcW'))
|
|
366
|
+
if tcW is not None:
|
|
367
|
+
w_val = tcW.get(qn('w:w'))
|
|
368
|
+
if w_val and w_val.isdigit():
|
|
369
|
+
width = int(w_val)
|
|
370
|
+
|
|
371
|
+
cell_widths.append((cell_text, width))
|
|
372
|
+
total_width += width
|
|
373
|
+
|
|
374
|
+
# Normalize to multipliers (relative to average)
|
|
375
|
+
if total_width > 0 and cell_widths:
|
|
376
|
+
avg_width = total_width / len(cell_widths)
|
|
377
|
+
for cell_text, width in cell_widths:
|
|
378
|
+
if cell_text: # Only include cells with text
|
|
379
|
+
widths[cell_text] = round(width / avg_width, 2)
|
|
380
|
+
|
|
381
|
+
return widths
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def find_images(doc: DocxDocument) -> List[Dict[str, Any]]:
|
|
385
|
+
"""Find all images in the document.
|
|
386
|
+
|
|
387
|
+
Args:
|
|
388
|
+
doc: The document to search.
|
|
389
|
+
|
|
390
|
+
Returns:
|
|
391
|
+
List of image information dictionaries.
|
|
392
|
+
"""
|
|
393
|
+
images = []
|
|
394
|
+
|
|
395
|
+
# Find all drawing elements
|
|
396
|
+
for i, para in enumerate(doc.paragraphs):
|
|
397
|
+
for run in para.runs:
|
|
398
|
+
# Check for inline shapes (images)
|
|
399
|
+
drawing_elements = run._element.findall('.//' + qn('w:drawing'))
|
|
400
|
+
for j, drawing in enumerate(drawing_elements):
|
|
401
|
+
# Look for blip elements which contain image references
|
|
402
|
+
blips = drawing.findall('.//' + qn('a:blip'))
|
|
403
|
+
for blip in blips:
|
|
404
|
+
embed = blip.get(qn('r:embed'))
|
|
405
|
+
if embed:
|
|
406
|
+
images.append({
|
|
407
|
+
'type': 'image',
|
|
408
|
+
'embed_id': embed,
|
|
409
|
+
'paragraph_index': i,
|
|
410
|
+
'docx_path': f"/w:body/w:p[{i + 1}]/w:r/w:drawing[{j + 1}]"
|
|
411
|
+
})
|
|
412
|
+
|
|
413
|
+
return images
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def find_preserved_elements(doc: DocxDocument) -> List[Dict[str, Any]]:
|
|
417
|
+
"""Find elements that should be preserved (charts, shapes, etc).
|
|
418
|
+
|
|
419
|
+
Args:
|
|
420
|
+
doc: The document to search.
|
|
421
|
+
|
|
422
|
+
Returns:
|
|
423
|
+
List of preserved element information.
|
|
424
|
+
"""
|
|
425
|
+
preserved = []
|
|
426
|
+
|
|
427
|
+
# Find charts
|
|
428
|
+
for i, para in enumerate(doc.paragraphs):
|
|
429
|
+
for run in para.runs:
|
|
430
|
+
drawing_elements = run._element.findall('.//' + qn('w:drawing'))
|
|
431
|
+
for j, drawing in enumerate(drawing_elements):
|
|
432
|
+
# Check for chart references
|
|
433
|
+
charts = drawing.findall('.//' + qn('c:chart'))
|
|
434
|
+
for chart in charts:
|
|
435
|
+
chart_id = chart.get(qn('r:id'))
|
|
436
|
+
if chart_id:
|
|
437
|
+
preserved.append({
|
|
438
|
+
'type': 'chart',
|
|
439
|
+
'ref_id': chart_id,
|
|
440
|
+
'paragraph_index': i,
|
|
441
|
+
'docx_path': f"/w:body/w:p[{i + 1}]/w:r/w:drawing[{j + 1}]/chart"
|
|
442
|
+
})
|
|
443
|
+
|
|
444
|
+
return preserved
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def element_to_markdown(element: ExtractedElement, prev_element: Optional[ExtractedElement] = None) -> str:
|
|
448
|
+
"""Convert an ExtractedElement to Markdown.
|
|
449
|
+
|
|
450
|
+
Args:
|
|
451
|
+
element: The element to convert.
|
|
452
|
+
prev_element: The previous element (for context).
|
|
453
|
+
|
|
454
|
+
Returns:
|
|
455
|
+
Markdown string.
|
|
456
|
+
"""
|
|
457
|
+
if element.type == 'heading':
|
|
458
|
+
prefix = '#' * element.level
|
|
459
|
+
return f"{prefix} {element.content}"
|
|
460
|
+
|
|
461
|
+
elif element.type == 'list_item':
|
|
462
|
+
indent = ' ' * element.level
|
|
463
|
+
is_numbered = element.metadata.get('is_numbered', False)
|
|
464
|
+
if is_numbered:
|
|
465
|
+
return f"{indent}1. {element.content}"
|
|
466
|
+
else:
|
|
467
|
+
return f"{indent}- {element.content}"
|
|
468
|
+
|
|
469
|
+
elif element.type == 'table':
|
|
470
|
+
return element.content
|
|
471
|
+
|
|
472
|
+
elif element.type == 'image':
|
|
473
|
+
# Image placeholder - actual path set during extraction
|
|
474
|
+
return element.content
|
|
475
|
+
|
|
476
|
+
else: # paragraph
|
|
477
|
+
return element.content
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def extract_content(doc_path: Path) -> ExtractionResult:
|
|
481
|
+
"""Extract content from a DOCX file.
|
|
482
|
+
|
|
483
|
+
Args:
|
|
484
|
+
doc_path: Path to the DOCX file.
|
|
485
|
+
|
|
486
|
+
Returns:
|
|
487
|
+
ExtractionResult with markdown content and element mappings.
|
|
488
|
+
"""
|
|
489
|
+
doc = Document(doc_path)
|
|
490
|
+
elements: List[ExtractedElement] = []
|
|
491
|
+
|
|
492
|
+
# Track indices for different element types
|
|
493
|
+
para_index = 0
|
|
494
|
+
table_index = 0
|
|
495
|
+
|
|
496
|
+
# Iterate through document body
|
|
497
|
+
for child in doc.element.body:
|
|
498
|
+
tag = child.tag.split('}')[-1] # Get tag name without namespace
|
|
499
|
+
|
|
500
|
+
if tag == 'p': # Paragraph
|
|
501
|
+
para = doc.paragraphs[para_index]
|
|
502
|
+
if para.text.strip(): # Only include non-empty paragraphs
|
|
503
|
+
element = parse_paragraph(para, para_index)
|
|
504
|
+
elements.append(element)
|
|
505
|
+
para_index += 1
|
|
506
|
+
|
|
507
|
+
elif tag == 'tbl': # Table
|
|
508
|
+
table = doc.tables[table_index]
|
|
509
|
+
element = parse_table(table, table_index)
|
|
510
|
+
if element.content:
|
|
511
|
+
elements.append(element)
|
|
512
|
+
table_index += 1
|
|
513
|
+
|
|
514
|
+
# Find images and preserved elements
|
|
515
|
+
images = find_images(doc)
|
|
516
|
+
preserved = find_preserved_elements(doc)
|
|
517
|
+
|
|
518
|
+
# Convert to Markdown with line tracking
|
|
519
|
+
md_lines = []
|
|
520
|
+
current_line = 1
|
|
521
|
+
prev_element = None
|
|
522
|
+
in_list = False
|
|
523
|
+
|
|
524
|
+
for element in elements:
|
|
525
|
+
# Add blank line before headings (except at start)
|
|
526
|
+
if element.type == 'heading' and md_lines:
|
|
527
|
+
md_lines.append('')
|
|
528
|
+
current_line += 1
|
|
529
|
+
|
|
530
|
+
# Add blank line before tables
|
|
531
|
+
if element.type == 'table' and md_lines:
|
|
532
|
+
md_lines.append('')
|
|
533
|
+
current_line += 1
|
|
534
|
+
|
|
535
|
+
# Add blank line after lists when switching to non-list
|
|
536
|
+
if prev_element and prev_element.type == 'list_item' and element.type != 'list_item':
|
|
537
|
+
md_lines.append('')
|
|
538
|
+
current_line += 1
|
|
539
|
+
in_list = False
|
|
540
|
+
|
|
541
|
+
# Add blank line before first list item
|
|
542
|
+
if element.type == 'list_item' and not in_list and md_lines:
|
|
543
|
+
md_lines.append('')
|
|
544
|
+
current_line += 1
|
|
545
|
+
in_list = True
|
|
546
|
+
|
|
547
|
+
# Track line numbers
|
|
548
|
+
element.line_start = current_line
|
|
549
|
+
|
|
550
|
+
# Convert to markdown
|
|
551
|
+
md_content = element_to_markdown(element, prev_element)
|
|
552
|
+
content_lines = md_content.split('\n')
|
|
553
|
+
md_lines.extend(content_lines)
|
|
554
|
+
|
|
555
|
+
element.line_end = current_line + len(content_lines) - 1
|
|
556
|
+
current_line = element.line_end + 1
|
|
557
|
+
|
|
558
|
+
# Add blank line after headings
|
|
559
|
+
if element.type == 'heading':
|
|
560
|
+
md_lines.append('')
|
|
561
|
+
current_line += 1
|
|
562
|
+
|
|
563
|
+
# Add blank line after tables
|
|
564
|
+
if element.type == 'table':
|
|
565
|
+
md_lines.append('')
|
|
566
|
+
current_line += 1
|
|
567
|
+
|
|
568
|
+
prev_element = element
|
|
569
|
+
|
|
570
|
+
markdown = '\n'.join(md_lines)
|
|
571
|
+
|
|
572
|
+
return ExtractionResult(
|
|
573
|
+
markdown=markdown,
|
|
574
|
+
elements=elements,
|
|
575
|
+
preserved_elements=preserved,
|
|
576
|
+
images=images
|
|
577
|
+
)
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def convert_docx_to_md(
|
|
581
|
+
input_path: Path,
|
|
582
|
+
output_path: Path,
|
|
583
|
+
include_meta: bool = True,
|
|
584
|
+
extract_images: bool = True
|
|
585
|
+
) -> ExtractionResult:
|
|
586
|
+
"""Convert a DOCX file to Markdown.
|
|
587
|
+
|
|
588
|
+
This is the main entry point for DOCX to Markdown conversion.
|
|
589
|
+
|
|
590
|
+
Args:
|
|
591
|
+
input_path: Path to the DOCX file.
|
|
592
|
+
output_path: Path for the output Markdown file.
|
|
593
|
+
include_meta: Whether to generate metadata XML file.
|
|
594
|
+
extract_images: Whether to extract images to files.
|
|
595
|
+
|
|
596
|
+
Returns:
|
|
597
|
+
ExtractionResult with extraction details.
|
|
598
|
+
"""
|
|
599
|
+
input_path = Path(input_path)
|
|
600
|
+
output_path = Path(output_path)
|
|
601
|
+
|
|
602
|
+
# Validate input
|
|
603
|
+
if not input_path.exists():
|
|
604
|
+
raise FileNotFoundError(f"Input file not found: {input_path}")
|
|
605
|
+
|
|
606
|
+
if not input_path.suffix.lower() == '.docx':
|
|
607
|
+
raise ValueError(f"Input file must be a .docx file: {input_path}")
|
|
608
|
+
|
|
609
|
+
# Extract content
|
|
610
|
+
result = extract_content(input_path)
|
|
611
|
+
|
|
612
|
+
# Handle image extraction
|
|
613
|
+
if extract_images and result.images:
|
|
614
|
+
from .image_extractor import extract_images as do_extract_images
|
|
615
|
+
result = do_extract_images(input_path, output_path, result)
|
|
616
|
+
|
|
617
|
+
# Write markdown output
|
|
618
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
619
|
+
output_path.write_text(result.markdown, encoding='utf-8')
|
|
620
|
+
|
|
621
|
+
# Generate metadata if requested
|
|
622
|
+
if include_meta:
|
|
623
|
+
from .meta_mapper import save_metadata
|
|
624
|
+
meta_path = output_path.parent / f"{output_path.stem}_meta.xml"
|
|
625
|
+
save_metadata(result, input_path, output_path, meta_path)
|
|
626
|
+
|
|
627
|
+
return result
|