@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,1334 @@
|
|
|
1
|
+
"""Template extraction module for creating reusable DOCX templates."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Dict, List, Optional, Tuple, Any
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from xml.etree import ElementTree as ET
|
|
7
|
+
from xml.dom import minidom
|
|
8
|
+
import shutil
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
from docx import Document
|
|
12
|
+
from docx.shared import Pt
|
|
13
|
+
from docx.oxml.ns import qn
|
|
14
|
+
|
|
15
|
+
from .style_extractor import extract_styles, extract_table_styles, save_styles
|
|
16
|
+
from .textbox_extractor import (
|
|
17
|
+
extract_textboxes_from_docx,
|
|
18
|
+
display_textboxes,
|
|
19
|
+
replace_text_in_textbox,
|
|
20
|
+
TextBoxElement
|
|
21
|
+
)
|
|
22
|
+
from .font_manager import (
|
|
23
|
+
extract_fonts_from_docx,
|
|
24
|
+
extract_embedded_fonts,
|
|
25
|
+
find_font_file,
|
|
26
|
+
get_font_name_from_file,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class DocumentElement:
|
|
32
|
+
"""Represents an element that can be converted to a variable."""
|
|
33
|
+
index: int
|
|
34
|
+
content: str
|
|
35
|
+
location: str # 'cover', 'header', 'footer', 'body'
|
|
36
|
+
position: str # 'title', 'author', 'date', 'left', 'center', 'right', etc.
|
|
37
|
+
style_info: str # Human-readable style description
|
|
38
|
+
element_path: str # Path to element in document
|
|
39
|
+
paragraph_index: int = 0
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class TemplateVariable:
|
|
44
|
+
"""A variable defined in the template."""
|
|
45
|
+
name: str
|
|
46
|
+
location: str
|
|
47
|
+
position: str
|
|
48
|
+
original_content: str
|
|
49
|
+
syntax: str = "both" # 'angle', 'brace', or 'both'
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def get_style_description(paragraph) -> str:
|
|
53
|
+
"""Get a human-readable style description for a paragraph.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
paragraph: The paragraph to describe.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
String describing the style (e.g., "36pt bold").
|
|
60
|
+
"""
|
|
61
|
+
parts = []
|
|
62
|
+
|
|
63
|
+
# Get font size
|
|
64
|
+
for run in paragraph.runs:
|
|
65
|
+
if run.font.size:
|
|
66
|
+
parts.append(f"{run.font.size.pt}pt")
|
|
67
|
+
break
|
|
68
|
+
|
|
69
|
+
# Check for bold
|
|
70
|
+
for run in paragraph.runs:
|
|
71
|
+
if run.bold:
|
|
72
|
+
parts.append("bold")
|
|
73
|
+
break
|
|
74
|
+
|
|
75
|
+
# Check for italic
|
|
76
|
+
for run in paragraph.runs:
|
|
77
|
+
if run.italic:
|
|
78
|
+
parts.append("italic")
|
|
79
|
+
break
|
|
80
|
+
|
|
81
|
+
# Get style name
|
|
82
|
+
if paragraph.style and paragraph.style.name:
|
|
83
|
+
parts.append(f"({paragraph.style.name})")
|
|
84
|
+
|
|
85
|
+
return ' '.join(parts) if parts else "normal"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def has_page_break(paragraph) -> bool:
|
|
89
|
+
"""Check if a paragraph contains a page break.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
paragraph: The paragraph to check.
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
True if the paragraph contains a page break.
|
|
96
|
+
"""
|
|
97
|
+
for run in paragraph.runs:
|
|
98
|
+
for elem in run._r:
|
|
99
|
+
if elem.tag == qn('w:br'):
|
|
100
|
+
br_type = elem.get(qn('w:type'))
|
|
101
|
+
if br_type == 'page':
|
|
102
|
+
return True
|
|
103
|
+
return False
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def display_paragraphs_for_selection(doc: Document, max_paragraphs: int = 30) -> List[dict]:
|
|
107
|
+
"""Display numbered paragraphs with styles and page breaks for user selection.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
doc: The document to analyze.
|
|
111
|
+
max_paragraphs: Maximum number of paragraphs to display.
|
|
112
|
+
|
|
113
|
+
Returns:
|
|
114
|
+
List of paragraph info dictionaries.
|
|
115
|
+
"""
|
|
116
|
+
paragraphs_info = []
|
|
117
|
+
|
|
118
|
+
print("\n--- Document Paragraphs ---")
|
|
119
|
+
print("(Use paragraph number or 'p' for first page break)")
|
|
120
|
+
print()
|
|
121
|
+
|
|
122
|
+
for i, para in enumerate(doc.paragraphs[:max_paragraphs]):
|
|
123
|
+
text = para.text.strip()
|
|
124
|
+
style_name = para.style.name if para.style else "Normal"
|
|
125
|
+
style_desc = get_style_description(para)
|
|
126
|
+
|
|
127
|
+
# Check for page break
|
|
128
|
+
is_page_break = has_page_break(para)
|
|
129
|
+
|
|
130
|
+
info = {
|
|
131
|
+
'index': i + 1,
|
|
132
|
+
'text': text[:60] + ('...' if len(text) > 60 else ''),
|
|
133
|
+
'style': style_name,
|
|
134
|
+
'style_desc': style_desc,
|
|
135
|
+
'has_page_break': is_page_break
|
|
136
|
+
}
|
|
137
|
+
paragraphs_info.append(info)
|
|
138
|
+
|
|
139
|
+
# Display
|
|
140
|
+
page_break_marker = " [PAGE BREAK]" if is_page_break else ""
|
|
141
|
+
if text:
|
|
142
|
+
print(f" [{i + 1}] \"{info['text']}\"")
|
|
143
|
+
print(f" Style: {style_name} ({style_desc}){page_break_marker}")
|
|
144
|
+
elif is_page_break:
|
|
145
|
+
print(f" [{i + 1}] <empty paragraph> [PAGE BREAK]")
|
|
146
|
+
else:
|
|
147
|
+
print(f" [{i + 1}] <empty paragraph>")
|
|
148
|
+
|
|
149
|
+
return paragraphs_info
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def prompt_cover_boundary(doc: Document) -> int:
|
|
153
|
+
"""Prompt user to specify the cover page boundary.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
doc: The document to analyze.
|
|
157
|
+
|
|
158
|
+
Returns:
|
|
159
|
+
Paragraph index (0-based) where cover page ends.
|
|
160
|
+
-1 if no cover page should be kept.
|
|
161
|
+
"""
|
|
162
|
+
paragraphs_info = display_paragraphs_for_selection(doc)
|
|
163
|
+
|
|
164
|
+
print("\nEnter cover page boundary:")
|
|
165
|
+
print(" - Paragraph number (e.g., '5') = keep paragraphs 1-5 as cover page")
|
|
166
|
+
print(" - 'p' = use first page break as boundary")
|
|
167
|
+
print(" - 'none' or 0 = no cover page")
|
|
168
|
+
print()
|
|
169
|
+
|
|
170
|
+
try:
|
|
171
|
+
response = input("Cover page ends after: ").strip().lower()
|
|
172
|
+
except EOFError:
|
|
173
|
+
return -1
|
|
174
|
+
|
|
175
|
+
if response == 'none' or response == '0' or response == '':
|
|
176
|
+
return -1
|
|
177
|
+
|
|
178
|
+
if response == 'p':
|
|
179
|
+
# Find first page break
|
|
180
|
+
for info in paragraphs_info:
|
|
181
|
+
if info['has_page_break']:
|
|
182
|
+
print(f"Using page break at paragraph {info['index']} as boundary.")
|
|
183
|
+
return info['index'] - 1 # Return 0-based index
|
|
184
|
+
print("No page break found. Using first 5 paragraphs as cover.")
|
|
185
|
+
return 4 # Default to first 5 paragraphs
|
|
186
|
+
|
|
187
|
+
try:
|
|
188
|
+
para_num = int(response)
|
|
189
|
+
if 1 <= para_num <= len(paragraphs_info):
|
|
190
|
+
return para_num - 1 # Convert to 0-based index
|
|
191
|
+
else:
|
|
192
|
+
print(f"Invalid paragraph number. Using default (5).")
|
|
193
|
+
return 4
|
|
194
|
+
except ValueError:
|
|
195
|
+
print("Invalid input. Using default (5).")
|
|
196
|
+
return 4
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def find_cover_page_elements(
|
|
200
|
+
doc: Document,
|
|
201
|
+
cover_boundary: int = -1
|
|
202
|
+
) -> List[DocumentElement]:
|
|
203
|
+
"""Find potential variable elements on the cover page.
|
|
204
|
+
|
|
205
|
+
Args:
|
|
206
|
+
doc: The document to analyze.
|
|
207
|
+
cover_boundary: Paragraph index (0-based) where cover page ends.
|
|
208
|
+
If -1, auto-detect based on page breaks or headings.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
List of DocumentElement objects representing cover page elements.
|
|
212
|
+
"""
|
|
213
|
+
elements = []
|
|
214
|
+
element_index = 1
|
|
215
|
+
|
|
216
|
+
# Determine the range of paragraphs to consider
|
|
217
|
+
if cover_boundary >= 0:
|
|
218
|
+
max_para = cover_boundary + 1
|
|
219
|
+
else:
|
|
220
|
+
max_para = 20 # Default: check first 20 paragraphs
|
|
221
|
+
|
|
222
|
+
# Analyze paragraphs within the cover page boundary
|
|
223
|
+
for i, para in enumerate(doc.paragraphs[:max_para]):
|
|
224
|
+
text = para.text.strip()
|
|
225
|
+
if not text:
|
|
226
|
+
continue
|
|
227
|
+
|
|
228
|
+
# If no explicit boundary, stop at regular headings
|
|
229
|
+
if cover_boundary < 0:
|
|
230
|
+
style_name = para.style.name if para.style else ""
|
|
231
|
+
if style_name.startswith('Heading') and style_name != 'Heading 1':
|
|
232
|
+
break
|
|
233
|
+
|
|
234
|
+
# Determine position based on style and content
|
|
235
|
+
style_name = para.style.name if para.style else ""
|
|
236
|
+
position = "unknown"
|
|
237
|
+
if style_name == 'Title' or (i == 0 and len(text) < 100):
|
|
238
|
+
position = "title"
|
|
239
|
+
elif style_name == 'Subtitle':
|
|
240
|
+
position = "subtitle"
|
|
241
|
+
elif _looks_like_date(text):
|
|
242
|
+
position = "date"
|
|
243
|
+
elif _looks_like_author(text):
|
|
244
|
+
position = "author"
|
|
245
|
+
elif len(text) < 50:
|
|
246
|
+
position = f"line_{i + 1}"
|
|
247
|
+
|
|
248
|
+
style_desc = get_style_description(para)
|
|
249
|
+
|
|
250
|
+
elements.append(DocumentElement(
|
|
251
|
+
index=element_index,
|
|
252
|
+
content=text[:50] + ('...' if len(text) > 50 else ''),
|
|
253
|
+
location='cover',
|
|
254
|
+
position=position,
|
|
255
|
+
style_info=style_desc,
|
|
256
|
+
element_path=f"/w:body/w:p[{i + 1}]",
|
|
257
|
+
paragraph_index=i
|
|
258
|
+
))
|
|
259
|
+
element_index += 1
|
|
260
|
+
|
|
261
|
+
# If no explicit boundary, stop after finding several elements
|
|
262
|
+
if cover_boundary < 0 and element_index > 10:
|
|
263
|
+
break
|
|
264
|
+
|
|
265
|
+
return elements
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _looks_like_date(text: str) -> bool:
|
|
269
|
+
"""Check if text looks like a date."""
|
|
270
|
+
date_patterns = [
|
|
271
|
+
r'\d{4}[-/]\d{1,2}[-/]\d{1,2}', # 2024-01-15
|
|
272
|
+
r'\d{1,2}[-/]\d{1,2}[-/]\d{4}', # 15/01/2024
|
|
273
|
+
r'(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{1,2},?\s+\d{4}',
|
|
274
|
+
r'\d{1,2}\s+(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{4}',
|
|
275
|
+
]
|
|
276
|
+
for pattern in date_patterns:
|
|
277
|
+
if re.search(pattern, text, re.IGNORECASE):
|
|
278
|
+
return True
|
|
279
|
+
return False
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _looks_like_author(text: str) -> bool:
|
|
283
|
+
"""Check if text looks like an author name."""
|
|
284
|
+
# Simple heuristic: 2-4 words, title case, no numbers
|
|
285
|
+
if re.search(r'\d', text):
|
|
286
|
+
return False
|
|
287
|
+
words = text.split()
|
|
288
|
+
if 2 <= len(words) <= 4:
|
|
289
|
+
if all(word[0].isupper() for word in words if word):
|
|
290
|
+
return True
|
|
291
|
+
return False
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def find_header_elements(doc: Document) -> List[DocumentElement]:
|
|
295
|
+
"""Find elements in document headers (default header only).
|
|
296
|
+
|
|
297
|
+
Args:
|
|
298
|
+
doc: The document to analyze.
|
|
299
|
+
|
|
300
|
+
Returns:
|
|
301
|
+
List of DocumentElement objects representing header elements.
|
|
302
|
+
"""
|
|
303
|
+
elements = []
|
|
304
|
+
element_index = 1
|
|
305
|
+
|
|
306
|
+
for section in doc.sections:
|
|
307
|
+
header = section.header
|
|
308
|
+
if not header.paragraphs:
|
|
309
|
+
continue
|
|
310
|
+
|
|
311
|
+
for i, para in enumerate(header.paragraphs):
|
|
312
|
+
text = para.text.strip()
|
|
313
|
+
if not text:
|
|
314
|
+
continue
|
|
315
|
+
|
|
316
|
+
# Determine position (left/center/right) based on alignment
|
|
317
|
+
alignment = para.alignment
|
|
318
|
+
if alignment == 1: # Center
|
|
319
|
+
position = "center"
|
|
320
|
+
elif alignment == 2: # Right
|
|
321
|
+
position = "right"
|
|
322
|
+
else:
|
|
323
|
+
position = "left"
|
|
324
|
+
|
|
325
|
+
style_desc = get_style_description(para)
|
|
326
|
+
|
|
327
|
+
elements.append(DocumentElement(
|
|
328
|
+
index=element_index,
|
|
329
|
+
content=text[:50] + ('...' if len(text) > 50 else ''),
|
|
330
|
+
location='header',
|
|
331
|
+
position=position,
|
|
332
|
+
style_info=style_desc,
|
|
333
|
+
element_path=f"/w:sectPr/w:headerReference/w:p[{i + 1}]",
|
|
334
|
+
paragraph_index=i
|
|
335
|
+
))
|
|
336
|
+
element_index += 1
|
|
337
|
+
|
|
338
|
+
return elements
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def find_first_page_header_elements(doc: Document) -> List[DocumentElement]:
|
|
342
|
+
"""Find elements in the first page (cover) header.
|
|
343
|
+
|
|
344
|
+
Args:
|
|
345
|
+
doc: The document to analyze.
|
|
346
|
+
|
|
347
|
+
Returns:
|
|
348
|
+
List of DocumentElement objects representing first page header elements.
|
|
349
|
+
"""
|
|
350
|
+
elements = []
|
|
351
|
+
element_index = 1
|
|
352
|
+
|
|
353
|
+
for section in doc.sections:
|
|
354
|
+
# Check if section has different first page header
|
|
355
|
+
if not section.different_first_page_header_footer:
|
|
356
|
+
continue
|
|
357
|
+
|
|
358
|
+
first_header = section.first_page_header
|
|
359
|
+
if not first_header or not first_header.paragraphs:
|
|
360
|
+
continue
|
|
361
|
+
|
|
362
|
+
for i, para in enumerate(first_header.paragraphs):
|
|
363
|
+
text = para.text.strip()
|
|
364
|
+
if not text:
|
|
365
|
+
continue
|
|
366
|
+
|
|
367
|
+
alignment = para.alignment
|
|
368
|
+
if alignment == 1:
|
|
369
|
+
position = "center"
|
|
370
|
+
elif alignment == 2:
|
|
371
|
+
position = "right"
|
|
372
|
+
else:
|
|
373
|
+
position = "left"
|
|
374
|
+
|
|
375
|
+
style_desc = get_style_description(para)
|
|
376
|
+
|
|
377
|
+
elements.append(DocumentElement(
|
|
378
|
+
index=element_index,
|
|
379
|
+
content=text[:50] + ('...' if len(text) > 50 else ''),
|
|
380
|
+
location='header_first',
|
|
381
|
+
position=position,
|
|
382
|
+
style_info=style_desc,
|
|
383
|
+
element_path=f"/w:sectPr/w:headerReference[@w:type='first']/w:p[{i + 1}]",
|
|
384
|
+
paragraph_index=i
|
|
385
|
+
))
|
|
386
|
+
element_index += 1
|
|
387
|
+
|
|
388
|
+
return elements
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def find_footer_elements(doc: Document) -> List[DocumentElement]:
|
|
392
|
+
"""Find elements in document footers (default footer only).
|
|
393
|
+
|
|
394
|
+
Args:
|
|
395
|
+
doc: The document to analyze.
|
|
396
|
+
|
|
397
|
+
Returns:
|
|
398
|
+
List of DocumentElement objects representing footer elements.
|
|
399
|
+
"""
|
|
400
|
+
elements = []
|
|
401
|
+
element_index = 1
|
|
402
|
+
|
|
403
|
+
for section in doc.sections:
|
|
404
|
+
footer = section.footer
|
|
405
|
+
if not footer.paragraphs:
|
|
406
|
+
continue
|
|
407
|
+
|
|
408
|
+
for i, para in enumerate(footer.paragraphs):
|
|
409
|
+
text = para.text.strip()
|
|
410
|
+
if not text:
|
|
411
|
+
continue
|
|
412
|
+
|
|
413
|
+
# Determine position
|
|
414
|
+
alignment = para.alignment
|
|
415
|
+
if alignment == 1:
|
|
416
|
+
position = "center"
|
|
417
|
+
elif alignment == 2:
|
|
418
|
+
position = "right"
|
|
419
|
+
else:
|
|
420
|
+
position = "left"
|
|
421
|
+
|
|
422
|
+
style_desc = get_style_description(para)
|
|
423
|
+
|
|
424
|
+
elements.append(DocumentElement(
|
|
425
|
+
index=element_index,
|
|
426
|
+
content=text[:50] + ('...' if len(text) > 50 else ''),
|
|
427
|
+
location='footer',
|
|
428
|
+
position=position,
|
|
429
|
+
style_info=style_desc,
|
|
430
|
+
element_path=f"/w:sectPr/w:footerReference/w:p[{i + 1}]",
|
|
431
|
+
paragraph_index=i
|
|
432
|
+
))
|
|
433
|
+
element_index += 1
|
|
434
|
+
|
|
435
|
+
return elements
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def find_first_page_footer_elements(doc: Document) -> List[DocumentElement]:
|
|
439
|
+
"""Find elements in the first page (cover) footer.
|
|
440
|
+
|
|
441
|
+
Args:
|
|
442
|
+
doc: The document to analyze.
|
|
443
|
+
|
|
444
|
+
Returns:
|
|
445
|
+
List of DocumentElement objects representing first page footer elements.
|
|
446
|
+
"""
|
|
447
|
+
elements = []
|
|
448
|
+
element_index = 1
|
|
449
|
+
|
|
450
|
+
for section in doc.sections:
|
|
451
|
+
if not section.different_first_page_header_footer:
|
|
452
|
+
continue
|
|
453
|
+
|
|
454
|
+
first_footer = section.first_page_footer
|
|
455
|
+
if not first_footer or not first_footer.paragraphs:
|
|
456
|
+
continue
|
|
457
|
+
|
|
458
|
+
for i, para in enumerate(first_footer.paragraphs):
|
|
459
|
+
text = para.text.strip()
|
|
460
|
+
if not text:
|
|
461
|
+
continue
|
|
462
|
+
|
|
463
|
+
alignment = para.alignment
|
|
464
|
+
if alignment == 1:
|
|
465
|
+
position = "center"
|
|
466
|
+
elif alignment == 2:
|
|
467
|
+
position = "right"
|
|
468
|
+
else:
|
|
469
|
+
position = "left"
|
|
470
|
+
|
|
471
|
+
style_desc = get_style_description(para)
|
|
472
|
+
|
|
473
|
+
elements.append(DocumentElement(
|
|
474
|
+
index=element_index,
|
|
475
|
+
content=text[:50] + ('...' if len(text) > 50 else ''),
|
|
476
|
+
location='footer_first',
|
|
477
|
+
position=position,
|
|
478
|
+
style_info=style_desc,
|
|
479
|
+
element_path=f"/w:sectPr/w:footerReference[@w:type='first']/w:p[{i + 1}]",
|
|
480
|
+
paragraph_index=i
|
|
481
|
+
))
|
|
482
|
+
element_index += 1
|
|
483
|
+
|
|
484
|
+
return elements
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def present_elements(elements: List[DocumentElement], section_name: str) -> str:
|
|
488
|
+
"""Format elements for display to the user.
|
|
489
|
+
|
|
490
|
+
Args:
|
|
491
|
+
elements: List of elements to display.
|
|
492
|
+
section_name: Name of the section (e.g., "cover page").
|
|
493
|
+
|
|
494
|
+
Returns:
|
|
495
|
+
Formatted string for display.
|
|
496
|
+
"""
|
|
497
|
+
if not elements:
|
|
498
|
+
return f"No {section_name} elements found.\n"
|
|
499
|
+
|
|
500
|
+
lines = [f"\nFound {section_name} elements:"]
|
|
501
|
+
for elem in elements:
|
|
502
|
+
lines.append(f' [{elem.index}] "{elem.content}" ({elem.style_info})')
|
|
503
|
+
|
|
504
|
+
return '\n'.join(lines)
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def prompt_variable_selection(elements: List[DocumentElement], section_name: str) -> List[DocumentElement]:
|
|
508
|
+
"""Prompt user to select which elements should become variables.
|
|
509
|
+
|
|
510
|
+
Args:
|
|
511
|
+
elements: List of available elements.
|
|
512
|
+
section_name: Name of the section for the prompt.
|
|
513
|
+
|
|
514
|
+
Returns:
|
|
515
|
+
List of selected elements.
|
|
516
|
+
"""
|
|
517
|
+
if not elements:
|
|
518
|
+
return []
|
|
519
|
+
|
|
520
|
+
print(present_elements(elements, section_name))
|
|
521
|
+
print(f"\nWhich {section_name} elements should be substitutable? (comma-separated, or 'none'): ", end='')
|
|
522
|
+
|
|
523
|
+
try:
|
|
524
|
+
response = input().strip().lower()
|
|
525
|
+
except EOFError:
|
|
526
|
+
return []
|
|
527
|
+
|
|
528
|
+
if response == 'none' or response == '':
|
|
529
|
+
return []
|
|
530
|
+
|
|
531
|
+
selected = []
|
|
532
|
+
try:
|
|
533
|
+
indices = [int(x.strip()) for x in response.split(',')]
|
|
534
|
+
for idx in indices:
|
|
535
|
+
for elem in elements:
|
|
536
|
+
if elem.index == idx:
|
|
537
|
+
selected.append(elem)
|
|
538
|
+
break
|
|
539
|
+
except ValueError:
|
|
540
|
+
print("Invalid input. No elements selected.")
|
|
541
|
+
return []
|
|
542
|
+
|
|
543
|
+
return selected
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def prompt_textbox_variable_selection(
|
|
547
|
+
textboxes: List[TextBoxElement]
|
|
548
|
+
) -> Tuple[List[Tuple[TextBoxElement, int, str]], Dict[str, str]]:
|
|
549
|
+
"""Prompt user to select text box lines as variables.
|
|
550
|
+
|
|
551
|
+
Args:
|
|
552
|
+
textboxes: List of text box elements.
|
|
553
|
+
|
|
554
|
+
Returns:
|
|
555
|
+
Tuple of (selected items as (textbox, line_index, var_name), replacements dict).
|
|
556
|
+
"""
|
|
557
|
+
if not textboxes:
|
|
558
|
+
return [], {}
|
|
559
|
+
|
|
560
|
+
display_textboxes(textboxes)
|
|
561
|
+
|
|
562
|
+
print("\nWhich text box lines should be variables?")
|
|
563
|
+
print("Format: textbox.line (e.g., '1.1,1.2,1.3' for lines 1-3 of textbox 1)")
|
|
564
|
+
print("Or 'none' to skip: ", end='')
|
|
565
|
+
|
|
566
|
+
try:
|
|
567
|
+
response = input().strip().lower()
|
|
568
|
+
except EOFError:
|
|
569
|
+
return [], {}
|
|
570
|
+
|
|
571
|
+
if response == 'none' or response == '':
|
|
572
|
+
return [], {}
|
|
573
|
+
|
|
574
|
+
selected = []
|
|
575
|
+
replacements = {}
|
|
576
|
+
|
|
577
|
+
for item in response.split(','):
|
|
578
|
+
item = item.strip()
|
|
579
|
+
if '.' in item:
|
|
580
|
+
try:
|
|
581
|
+
tb_idx, line_idx = item.split('.')
|
|
582
|
+
tb_idx = int(tb_idx)
|
|
583
|
+
line_idx = int(line_idx)
|
|
584
|
+
|
|
585
|
+
for tb in textboxes:
|
|
586
|
+
if tb.index == tb_idx and line_idx <= len(tb.paragraphs):
|
|
587
|
+
para_text = tb.paragraphs[line_idx - 1]
|
|
588
|
+
display = para_text[:50] + ('...' if len(para_text) > 50 else '')
|
|
589
|
+
|
|
590
|
+
print(f"\nVariable name for \"{display}\": ", end='')
|
|
591
|
+
try:
|
|
592
|
+
var_name = input().strip()
|
|
593
|
+
except EOFError:
|
|
594
|
+
var_name = f"textbox_{tb_idx}_{line_idx}"
|
|
595
|
+
|
|
596
|
+
if not var_name:
|
|
597
|
+
var_name = f"textbox_{tb_idx}_{line_idx}"
|
|
598
|
+
|
|
599
|
+
var_name = re.sub(r'[^a-zA-Z0-9_]', '_', var_name)
|
|
600
|
+
replacements[para_text] = f"{{{{{var_name}}}}}"
|
|
601
|
+
selected.append((tb, line_idx, var_name, para_text))
|
|
602
|
+
break
|
|
603
|
+
except ValueError:
|
|
604
|
+
continue
|
|
605
|
+
|
|
606
|
+
return selected, replacements
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def textbox_selections_to_variables(
|
|
610
|
+
selections: List[Tuple[TextBoxElement, int, str, str]]
|
|
611
|
+
) -> List[TemplateVariable]:
|
|
612
|
+
"""Convert text box selections to TemplateVariable objects.
|
|
613
|
+
|
|
614
|
+
Args:
|
|
615
|
+
selections: List of (textbox, line_index, var_name, original_text) tuples.
|
|
616
|
+
|
|
617
|
+
Returns:
|
|
618
|
+
List of TemplateVariable objects.
|
|
619
|
+
"""
|
|
620
|
+
variables = []
|
|
621
|
+
for tb, line_idx, var_name, original_text in selections:
|
|
622
|
+
variables.append(TemplateVariable(
|
|
623
|
+
name=var_name,
|
|
624
|
+
location='textbox',
|
|
625
|
+
position=f"line_{line_idx}",
|
|
626
|
+
original_content=original_text,
|
|
627
|
+
syntax='both'
|
|
628
|
+
))
|
|
629
|
+
return variables
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
def prompt_variable_names(elements: List[DocumentElement]) -> List[TemplateVariable]:
|
|
633
|
+
"""Prompt user to assign variable names to selected elements.
|
|
634
|
+
|
|
635
|
+
Args:
|
|
636
|
+
elements: List of selected elements.
|
|
637
|
+
|
|
638
|
+
Returns:
|
|
639
|
+
List of TemplateVariable objects.
|
|
640
|
+
"""
|
|
641
|
+
variables = []
|
|
642
|
+
|
|
643
|
+
for elem in elements:
|
|
644
|
+
print(f'\nEnter variable name for "{elem.content}": ', end='')
|
|
645
|
+
try:
|
|
646
|
+
name = input().strip()
|
|
647
|
+
except EOFError:
|
|
648
|
+
name = f"var_{elem.index}"
|
|
649
|
+
|
|
650
|
+
if not name:
|
|
651
|
+
name = f"var_{elem.index}"
|
|
652
|
+
|
|
653
|
+
# Sanitize variable name
|
|
654
|
+
name = re.sub(r'[^a-zA-Z0-9_]', '_', name)
|
|
655
|
+
|
|
656
|
+
variables.append(TemplateVariable(
|
|
657
|
+
name=name,
|
|
658
|
+
location=elem.location,
|
|
659
|
+
position=elem.position,
|
|
660
|
+
original_content=elem.content,
|
|
661
|
+
syntax="both"
|
|
662
|
+
))
|
|
663
|
+
|
|
664
|
+
return variables
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def _run_has_drawing(run) -> bool:
|
|
668
|
+
"""Check if a run contains a drawing element (image).
|
|
669
|
+
|
|
670
|
+
Args:
|
|
671
|
+
run: The run to check.
|
|
672
|
+
|
|
673
|
+
Returns:
|
|
674
|
+
True if the run contains a drawing element.
|
|
675
|
+
"""
|
|
676
|
+
# Check for w:drawing elements in the run's XML
|
|
677
|
+
drawing_elements = run._r.findall(qn('w:drawing'))
|
|
678
|
+
return len(drawing_elements) > 0
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def _replace_paragraph_text_preserve_images(para, placeholder: str) -> None:
|
|
682
|
+
"""Replace text in a paragraph while preserving images/drawings.
|
|
683
|
+
|
|
684
|
+
This function clears text from runs that don't contain drawings,
|
|
685
|
+
and sets the placeholder in the first text-only run.
|
|
686
|
+
|
|
687
|
+
Args:
|
|
688
|
+
para: The paragraph to modify.
|
|
689
|
+
placeholder: The placeholder text to insert.
|
|
690
|
+
"""
|
|
691
|
+
first_text_run = None
|
|
692
|
+
|
|
693
|
+
for run in para.runs:
|
|
694
|
+
if _run_has_drawing(run):
|
|
695
|
+
# Preserve runs with drawings - don't touch them
|
|
696
|
+
continue
|
|
697
|
+
else:
|
|
698
|
+
# This is a text-only run
|
|
699
|
+
if first_text_run is None:
|
|
700
|
+
first_text_run = run
|
|
701
|
+
run.text = placeholder
|
|
702
|
+
else:
|
|
703
|
+
# Clear subsequent text runs
|
|
704
|
+
run.text = ''
|
|
705
|
+
|
|
706
|
+
# If no text runs found, add a new one
|
|
707
|
+
if first_text_run is None and para.runs:
|
|
708
|
+
# Check if we can add text to an existing run
|
|
709
|
+
para.add_run(placeholder)
|
|
710
|
+
elif first_text_run is None:
|
|
711
|
+
para.add_run(placeholder)
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
def replace_with_placeholder(
|
|
715
|
+
doc: Document,
|
|
716
|
+
element: DocumentElement,
|
|
717
|
+
variable: TemplateVariable
|
|
718
|
+
) -> None:
|
|
719
|
+
"""Replace an element's content with a variable placeholder.
|
|
720
|
+
|
|
721
|
+
Supports both <variable> and {{variable}} syntax by using {{variable}}.
|
|
722
|
+
Preserves images and drawings in headers/footers.
|
|
723
|
+
|
|
724
|
+
Args:
|
|
725
|
+
doc: The document to modify.
|
|
726
|
+
element: The element to replace.
|
|
727
|
+
variable: The variable definition.
|
|
728
|
+
"""
|
|
729
|
+
# Create placeholder using double brace syntax as the canonical form
|
|
730
|
+
placeholder = f"{{{{{variable.name}}}}}"
|
|
731
|
+
|
|
732
|
+
if element.location == 'cover' or element.location == 'body':
|
|
733
|
+
# Replace in body paragraphs
|
|
734
|
+
if element.paragraph_index < len(doc.paragraphs):
|
|
735
|
+
para = doc.paragraphs[element.paragraph_index]
|
|
736
|
+
_replace_paragraph_text_preserve_images(para, placeholder)
|
|
737
|
+
|
|
738
|
+
elif element.location == 'header':
|
|
739
|
+
for section in doc.sections:
|
|
740
|
+
for para in section.header.paragraphs:
|
|
741
|
+
if element.content.rstrip('...') in para.text:
|
|
742
|
+
_replace_paragraph_text_preserve_images(para, placeholder)
|
|
743
|
+
break
|
|
744
|
+
|
|
745
|
+
elif element.location == 'header_first':
|
|
746
|
+
for section in doc.sections:
|
|
747
|
+
if section.different_first_page_header_footer:
|
|
748
|
+
for para in section.first_page_header.paragraphs:
|
|
749
|
+
if element.content.rstrip('...') in para.text:
|
|
750
|
+
_replace_paragraph_text_preserve_images(para, placeholder)
|
|
751
|
+
break
|
|
752
|
+
|
|
753
|
+
elif element.location == 'footer':
|
|
754
|
+
for section in doc.sections:
|
|
755
|
+
for para in section.footer.paragraphs:
|
|
756
|
+
if element.content.rstrip('...') in para.text:
|
|
757
|
+
_replace_paragraph_text_preserve_images(para, placeholder)
|
|
758
|
+
break
|
|
759
|
+
|
|
760
|
+
elif element.location == 'footer_first':
|
|
761
|
+
for section in doc.sections:
|
|
762
|
+
if section.different_first_page_header_footer:
|
|
763
|
+
for para in section.first_page_footer.paragraphs:
|
|
764
|
+
if element.content.rstrip('...') in para.text:
|
|
765
|
+
_replace_paragraph_text_preserve_images(para, placeholder)
|
|
766
|
+
break
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
def remove_body_content(doc: Document, keep_first_n: int = 0) -> None:
|
|
770
|
+
"""Remove body content after the cover page.
|
|
771
|
+
|
|
772
|
+
This removes all paragraphs and tables after the cover page boundary,
|
|
773
|
+
not just clearing their content. The cover page paragraphs are preserved.
|
|
774
|
+
|
|
775
|
+
Args:
|
|
776
|
+
doc: The document to modify.
|
|
777
|
+
keep_first_n: Number of paragraphs to keep (for cover page).
|
|
778
|
+
"""
|
|
779
|
+
body = doc.element.body
|
|
780
|
+
paragraphs = body.findall(qn('w:p'))
|
|
781
|
+
tables = body.findall(qn('w:tbl'))
|
|
782
|
+
|
|
783
|
+
# Remove paragraphs after the cover page
|
|
784
|
+
for i, p in enumerate(paragraphs):
|
|
785
|
+
if i >= keep_first_n:
|
|
786
|
+
body.remove(p)
|
|
787
|
+
|
|
788
|
+
# Remove all tables (they come after cover page typically)
|
|
789
|
+
for tbl in tables:
|
|
790
|
+
body.remove(tbl)
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
def strip_body_content(doc: Document, keep_first_n: int = 0) -> None:
|
|
794
|
+
"""Remove body content while preserving structure and styles.
|
|
795
|
+
|
|
796
|
+
DEPRECATED: Use remove_body_content() instead for proper content removal.
|
|
797
|
+
|
|
798
|
+
Args:
|
|
799
|
+
doc: The document to modify.
|
|
800
|
+
keep_first_n: Number of paragraphs to keep (for cover page).
|
|
801
|
+
"""
|
|
802
|
+
# Remove paragraphs after the cover page section
|
|
803
|
+
body = doc.element.body
|
|
804
|
+
paragraphs = body.findall(qn('w:p'))
|
|
805
|
+
|
|
806
|
+
for i, p in enumerate(paragraphs):
|
|
807
|
+
if i >= keep_first_n:
|
|
808
|
+
# Clear paragraph content but keep the element
|
|
809
|
+
for child in list(p):
|
|
810
|
+
if child.tag != qn('w:pPr'): # Keep paragraph properties
|
|
811
|
+
p.remove(child)
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
def generate_manifest(
|
|
815
|
+
template_name: str,
|
|
816
|
+
source_file: str,
|
|
817
|
+
variables: List[TemplateVariable],
|
|
818
|
+
output_path: Path,
|
|
819
|
+
cover_page_enabled: bool = False
|
|
820
|
+
) -> None:
|
|
821
|
+
"""Generate the template manifest.xml file.
|
|
822
|
+
|
|
823
|
+
Args:
|
|
824
|
+
template_name: Name of the template.
|
|
825
|
+
source_file: Original source file name.
|
|
826
|
+
variables: List of defined variables.
|
|
827
|
+
output_path: Path to save the manifest.
|
|
828
|
+
cover_page_enabled: Whether the template includes a cover page.
|
|
829
|
+
"""
|
|
830
|
+
from datetime import timezone
|
|
831
|
+
|
|
832
|
+
root = ET.Element('template')
|
|
833
|
+
root.set('name', template_name)
|
|
834
|
+
root.set('version', '1.0')
|
|
835
|
+
|
|
836
|
+
source = ET.SubElement(root, 'source')
|
|
837
|
+
source.text = source_file
|
|
838
|
+
|
|
839
|
+
created = ET.SubElement(root, 'created')
|
|
840
|
+
created.text = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
|
|
841
|
+
|
|
842
|
+
features = ET.SubElement(root, 'features')
|
|
843
|
+
|
|
844
|
+
# Cover page feature flag
|
|
845
|
+
cover_elem = ET.SubElement(features, 'cover-page')
|
|
846
|
+
cover_elem.set('enabled', 'true' if cover_page_enabled else 'false')
|
|
847
|
+
|
|
848
|
+
# Variables feature flag
|
|
849
|
+
if variables:
|
|
850
|
+
vars_elem = ET.SubElement(features, 'variables')
|
|
851
|
+
vars_elem.set('enabled', 'true')
|
|
852
|
+
|
|
853
|
+
# Group variables by location
|
|
854
|
+
locations = {}
|
|
855
|
+
for var in variables:
|
|
856
|
+
if var.location not in locations:
|
|
857
|
+
locations[var.location] = []
|
|
858
|
+
locations[var.location].append(var)
|
|
859
|
+
|
|
860
|
+
for location, vars_list in locations.items():
|
|
861
|
+
loc_elem = ET.SubElement(features, location.replace('_', '-'))
|
|
862
|
+
loc_elem.set('enabled', 'true')
|
|
863
|
+
|
|
864
|
+
for var in vars_list:
|
|
865
|
+
var_elem = ET.SubElement(loc_elem, 'variable')
|
|
866
|
+
var_elem.set('name', var.name)
|
|
867
|
+
var_elem.set('location', f"{location}/{var.position}")
|
|
868
|
+
var_elem.set('syntax', var.syntax)
|
|
869
|
+
|
|
870
|
+
# Pretty print and save
|
|
871
|
+
rough_string = ET.tostring(root, encoding='unicode')
|
|
872
|
+
reparsed = minidom.parseString(rough_string)
|
|
873
|
+
formatted = reparsed.toprettyxml(indent=" ")
|
|
874
|
+
|
|
875
|
+
output_path.write_text(formatted, encoding='utf-8')
|
|
876
|
+
|
|
877
|
+
|
|
878
|
+
def generate_variables_xml(
|
|
879
|
+
variables: List[TemplateVariable],
|
|
880
|
+
output_path: Path
|
|
881
|
+
) -> None:
|
|
882
|
+
"""Generate the template variables.xml file.
|
|
883
|
+
|
|
884
|
+
The original content of each variable becomes its default value,
|
|
885
|
+
which is used when the variable is not provided or in non-interactive mode.
|
|
886
|
+
|
|
887
|
+
Args:
|
|
888
|
+
variables: List of defined variables.
|
|
889
|
+
output_path: Path to save the variables file.
|
|
890
|
+
"""
|
|
891
|
+
root = ET.Element('variables')
|
|
892
|
+
root.set('version', '1.0')
|
|
893
|
+
|
|
894
|
+
for var in variables:
|
|
895
|
+
var_elem = ET.SubElement(root, 'variable')
|
|
896
|
+
var_elem.set('name', var.name)
|
|
897
|
+
|
|
898
|
+
# Default value is the original content (without truncation ellipsis)
|
|
899
|
+
default = ET.SubElement(var_elem, 'default')
|
|
900
|
+
original_text = var.original_content.rstrip('...')
|
|
901
|
+
default.text = original_text
|
|
902
|
+
|
|
903
|
+
# Description based on location and position
|
|
904
|
+
description = ET.SubElement(var_elem, 'description')
|
|
905
|
+
description.text = f"Variable in {var.location} ({var.position})"
|
|
906
|
+
|
|
907
|
+
# Location info for reference
|
|
908
|
+
location = ET.SubElement(var_elem, 'location')
|
|
909
|
+
location.text = f"{var.location}/{var.position}"
|
|
910
|
+
|
|
911
|
+
# Pretty print and save
|
|
912
|
+
rough_string = ET.tostring(root, encoding='unicode')
|
|
913
|
+
reparsed = minidom.parseString(rough_string)
|
|
914
|
+
formatted = reparsed.toprettyxml(indent=" ")
|
|
915
|
+
|
|
916
|
+
output_path.write_text(formatted, encoding='utf-8')
|
|
917
|
+
|
|
918
|
+
|
|
919
|
+
@dataclass
|
|
920
|
+
class VariableCandidate:
|
|
921
|
+
"""A potential variable candidate found during document analysis."""
|
|
922
|
+
id: str # e.g., "A1", "B1", "C2"
|
|
923
|
+
category: str # e.g., "textbox", "header", "header_first", "footer"
|
|
924
|
+
category_label: str # e.g., "Text Box", "Default Header"
|
|
925
|
+
content: str # The actual text content
|
|
926
|
+
suggested_name: str # Suggested variable name
|
|
927
|
+
description: str # Human-readable description
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
@dataclass
|
|
931
|
+
class DocumentAnalysis:
|
|
932
|
+
"""Result of analyzing a document for potential template variables."""
|
|
933
|
+
source_file: str
|
|
934
|
+
candidates: List[VariableCandidate]
|
|
935
|
+
has_cover_page: bool
|
|
936
|
+
has_different_first_page_header: bool
|
|
937
|
+
paragraph_count: int
|
|
938
|
+
cover_boundary: Optional[int] # Detected cover page boundary
|
|
939
|
+
|
|
940
|
+
def get_candidates_by_category(self, category: str) -> List[VariableCandidate]:
|
|
941
|
+
"""Get candidates filtered by category."""
|
|
942
|
+
return [c for c in self.candidates if c.category == category]
|
|
943
|
+
|
|
944
|
+
def print_summary(self) -> None:
|
|
945
|
+
"""Print a formatted summary of available variables."""
|
|
946
|
+
print("=" * 60)
|
|
947
|
+
print("AVAILABLE ELEMENTS FOR VARIABLES")
|
|
948
|
+
print("=" * 60)
|
|
949
|
+
|
|
950
|
+
categories = {}
|
|
951
|
+
for c in self.candidates:
|
|
952
|
+
if c.category not in categories:
|
|
953
|
+
categories[c.category] = []
|
|
954
|
+
categories[c.category].append(c)
|
|
955
|
+
|
|
956
|
+
category_order = ['textbox', 'header', 'header_first', 'footer', 'footer_first']
|
|
957
|
+
for cat in category_order:
|
|
958
|
+
if cat in categories:
|
|
959
|
+
items = categories[cat]
|
|
960
|
+
label = items[0].category_label
|
|
961
|
+
print(f"\n[{items[0].id[0]}] {label.upper()}")
|
|
962
|
+
print("-" * 40)
|
|
963
|
+
for item in items:
|
|
964
|
+
print(f" {item.id}. \"{item.content}\"")
|
|
965
|
+
|
|
966
|
+
print("\n" + "=" * 60)
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
def analyze_document_for_variables(source_docx: Path) -> DocumentAnalysis:
|
|
970
|
+
"""Analyze a DOCX document to find all potential template variables.
|
|
971
|
+
|
|
972
|
+
This function examines a document and identifies elements that can be
|
|
973
|
+
converted to template variables, including:
|
|
974
|
+
- Text boxes (commonly used for cover page titles)
|
|
975
|
+
- Headers (default and first page)
|
|
976
|
+
- Footers (default and first page)
|
|
977
|
+
- Cover page paragraphs
|
|
978
|
+
|
|
979
|
+
Args:
|
|
980
|
+
source_docx: Path to the DOCX file to analyze.
|
|
981
|
+
|
|
982
|
+
Returns:
|
|
983
|
+
DocumentAnalysis object containing all found variable candidates.
|
|
984
|
+
|
|
985
|
+
Example:
|
|
986
|
+
>>> analysis = analyze_document_for_variables(Path("proposal.docx"))
|
|
987
|
+
>>> analysis.print_summary()
|
|
988
|
+
>>> for candidate in analysis.candidates:
|
|
989
|
+
... print(f"{candidate.id}: {candidate.content}")
|
|
990
|
+
"""
|
|
991
|
+
source_docx = Path(source_docx)
|
|
992
|
+
if not source_docx.exists():
|
|
993
|
+
raise FileNotFoundError(f"Source file not found: {source_docx}")
|
|
994
|
+
|
|
995
|
+
doc = Document(source_docx)
|
|
996
|
+
candidates = []
|
|
997
|
+
|
|
998
|
+
# Detect cover page boundary (first page break)
|
|
999
|
+
cover_boundary = None
|
|
1000
|
+
for i, para in enumerate(doc.paragraphs[:30]):
|
|
1001
|
+
if has_page_break(para):
|
|
1002
|
+
cover_boundary = i
|
|
1003
|
+
break
|
|
1004
|
+
|
|
1005
|
+
# Check for different first page header/footer
|
|
1006
|
+
has_different_first = any(
|
|
1007
|
+
section.different_first_page_header_footer
|
|
1008
|
+
for section in doc.sections
|
|
1009
|
+
)
|
|
1010
|
+
|
|
1011
|
+
# === A. Text Box Elements ===
|
|
1012
|
+
textboxes = extract_textboxes_from_docx(source_docx)
|
|
1013
|
+
if textboxes:
|
|
1014
|
+
tb = textboxes[0]
|
|
1015
|
+
suggested_names = ['document_type', 'project_description', 'client_name', 'version']
|
|
1016
|
+
for i, line in enumerate(tb.paragraphs):
|
|
1017
|
+
suggested = suggested_names[i] if i < len(suggested_names) else f'textbox_line_{i+1}'
|
|
1018
|
+
candidates.append(VariableCandidate(
|
|
1019
|
+
id=f"A{i+1}",
|
|
1020
|
+
category='textbox',
|
|
1021
|
+
category_label='Text Box (Cover Page Title)',
|
|
1022
|
+
content=line.strip(),
|
|
1023
|
+
suggested_name=suggested,
|
|
1024
|
+
description=f"Text box line {i+1}"
|
|
1025
|
+
))
|
|
1026
|
+
|
|
1027
|
+
# === B. Default Header Elements ===
|
|
1028
|
+
header_elements = find_header_elements(doc)
|
|
1029
|
+
for elem in header_elements:
|
|
1030
|
+
candidates.append(VariableCandidate(
|
|
1031
|
+
id=f"B{elem.index}",
|
|
1032
|
+
category='header',
|
|
1033
|
+
category_label='Default Header (Normal Pages)',
|
|
1034
|
+
content=elem.content,
|
|
1035
|
+
suggested_name='project_name' if elem.index == 1 else f'header_{elem.index}',
|
|
1036
|
+
description=f"Header element {elem.index}"
|
|
1037
|
+
))
|
|
1038
|
+
|
|
1039
|
+
# === C. First Page Header Elements ===
|
|
1040
|
+
if has_different_first:
|
|
1041
|
+
first_header_elements = find_first_page_header_elements(doc)
|
|
1042
|
+
# Get full text from headers
|
|
1043
|
+
for section in doc.sections:
|
|
1044
|
+
if section.different_first_page_header_footer:
|
|
1045
|
+
paras = section.first_page_header.paragraphs
|
|
1046
|
+
for i, elem in enumerate(first_header_elements):
|
|
1047
|
+
full_text = paras[i].text.strip() if i < len(paras) else elem.content
|
|
1048
|
+
suggested = 'company_info' if i == 0 else 'date_contact' if i == 1 else f'header_first_{i+1}'
|
|
1049
|
+
candidates.append(VariableCandidate(
|
|
1050
|
+
id=f"C{elem.index}",
|
|
1051
|
+
category='header_first',
|
|
1052
|
+
category_label='First Page Header (Cover Page)',
|
|
1053
|
+
content=full_text,
|
|
1054
|
+
suggested_name=suggested,
|
|
1055
|
+
description=f"First page header line {elem.index} (has logo)" if i == 0 else f"First page header line {elem.index}"
|
|
1056
|
+
))
|
|
1057
|
+
break
|
|
1058
|
+
|
|
1059
|
+
# === D. Default Footer Elements ===
|
|
1060
|
+
footer_elements = find_footer_elements(doc)
|
|
1061
|
+
for elem in footer_elements:
|
|
1062
|
+
candidates.append(VariableCandidate(
|
|
1063
|
+
id=f"D{elem.index}",
|
|
1064
|
+
category='footer',
|
|
1065
|
+
category_label='Default Footer',
|
|
1066
|
+
content=elem.content,
|
|
1067
|
+
suggested_name=f'footer_{elem.index}',
|
|
1068
|
+
description=f"Footer element {elem.index} (usually page number)"
|
|
1069
|
+
))
|
|
1070
|
+
|
|
1071
|
+
# === E. First Page Footer Elements ===
|
|
1072
|
+
if has_different_first:
|
|
1073
|
+
first_footer_elements = find_first_page_footer_elements(doc)
|
|
1074
|
+
for elem in first_footer_elements:
|
|
1075
|
+
candidates.append(VariableCandidate(
|
|
1076
|
+
id=f"E{elem.index}",
|
|
1077
|
+
category='footer_first',
|
|
1078
|
+
category_label='First Page Footer',
|
|
1079
|
+
content=elem.content,
|
|
1080
|
+
suggested_name=f'footer_first_{elem.index}',
|
|
1081
|
+
description=f"First page footer element {elem.index}"
|
|
1082
|
+
))
|
|
1083
|
+
|
|
1084
|
+
return DocumentAnalysis(
|
|
1085
|
+
source_file=str(source_docx),
|
|
1086
|
+
candidates=candidates,
|
|
1087
|
+
has_cover_page=cover_boundary is not None,
|
|
1088
|
+
has_different_first_page_header=has_different_first,
|
|
1089
|
+
paragraph_count=len(doc.paragraphs),
|
|
1090
|
+
cover_boundary=cover_boundary
|
|
1091
|
+
)
|
|
1092
|
+
|
|
1093
|
+
|
|
1094
|
+
def create_template(
|
|
1095
|
+
source_docx: Path,
|
|
1096
|
+
template_name: str,
|
|
1097
|
+
templates_dir: Optional[Path] = None,
|
|
1098
|
+
variables: Optional[Dict[str, str]] = None,
|
|
1099
|
+
interactive: bool = True,
|
|
1100
|
+
include_cover_page: bool = True,
|
|
1101
|
+
cover_boundary: Optional[int] = None
|
|
1102
|
+
) -> Path:
|
|
1103
|
+
"""Create a reusable template from a DOCX file.
|
|
1104
|
+
|
|
1105
|
+
When creating a template:
|
|
1106
|
+
- Body content after the cover page is removed
|
|
1107
|
+
- Cover page content is preserved (up to the specified boundary)
|
|
1108
|
+
- Text boxes on cover page are scanned for variables
|
|
1109
|
+
- Variable placeholders replace original values (e.g., "John Doe" → <author>)
|
|
1110
|
+
- Original values are stored as defaults in variables.xml
|
|
1111
|
+
|
|
1112
|
+
Args:
|
|
1113
|
+
source_docx: Path to the source DOCX file.
|
|
1114
|
+
template_name: Name for the template.
|
|
1115
|
+
templates_dir: Directory to store templates (default: ./templates).
|
|
1116
|
+
variables: Pre-defined variables for non-interactive mode.
|
|
1117
|
+
interactive: Whether to prompt for variable selection.
|
|
1118
|
+
include_cover_page: Whether to preserve cover page in template.
|
|
1119
|
+
cover_boundary: Paragraph index (0-based) where cover ends.
|
|
1120
|
+
If None and interactive, user will be prompted.
|
|
1121
|
+
|
|
1122
|
+
Returns:
|
|
1123
|
+
Path to the created template directory.
|
|
1124
|
+
"""
|
|
1125
|
+
source_docx = Path(source_docx)
|
|
1126
|
+
if not source_docx.exists():
|
|
1127
|
+
raise FileNotFoundError(f"Source file not found: {source_docx}")
|
|
1128
|
+
|
|
1129
|
+
# Set up template directory
|
|
1130
|
+
if templates_dir is None:
|
|
1131
|
+
templates_dir = Path('./templates')
|
|
1132
|
+
templates_dir = Path(templates_dir)
|
|
1133
|
+
|
|
1134
|
+
template_path = templates_dir / template_name
|
|
1135
|
+
template_path.mkdir(parents=True, exist_ok=True)
|
|
1136
|
+
|
|
1137
|
+
# Load the document
|
|
1138
|
+
doc = Document(source_docx)
|
|
1139
|
+
|
|
1140
|
+
# Determine cover page boundary
|
|
1141
|
+
if include_cover_page:
|
|
1142
|
+
if cover_boundary is None and interactive:
|
|
1143
|
+
cover_boundary = prompt_cover_boundary(doc)
|
|
1144
|
+
elif cover_boundary is None:
|
|
1145
|
+
cover_boundary = 4 # Default: first 5 paragraphs
|
|
1146
|
+
else:
|
|
1147
|
+
cover_boundary = -1 # No cover page
|
|
1148
|
+
|
|
1149
|
+
# Find potential variable elements
|
|
1150
|
+
cover_elements = find_cover_page_elements(doc, cover_boundary)
|
|
1151
|
+
header_elements = find_header_elements(doc)
|
|
1152
|
+
first_header_elements = find_first_page_header_elements(doc)
|
|
1153
|
+
footer_elements = find_footer_elements(doc)
|
|
1154
|
+
first_footer_elements = find_first_page_footer_elements(doc)
|
|
1155
|
+
|
|
1156
|
+
# Extract text boxes (common for cover pages)
|
|
1157
|
+
textboxes = extract_textboxes_from_docx(source_docx)
|
|
1158
|
+
|
|
1159
|
+
template_variables = []
|
|
1160
|
+
textbox_replacements = {}
|
|
1161
|
+
|
|
1162
|
+
if interactive:
|
|
1163
|
+
# Interactive variable selection for paragraphs
|
|
1164
|
+
selected_cover = prompt_variable_selection(cover_elements, "cover page paragraphs")
|
|
1165
|
+
selected_header = prompt_variable_selection(header_elements, "default header")
|
|
1166
|
+
selected_first_header = prompt_variable_selection(first_header_elements, "first page (cover) header")
|
|
1167
|
+
selected_footer = prompt_variable_selection(footer_elements, "default footer")
|
|
1168
|
+
selected_first_footer = prompt_variable_selection(first_footer_elements, "first page (cover) footer")
|
|
1169
|
+
|
|
1170
|
+
all_selected = selected_cover + selected_header + selected_first_header + selected_footer + selected_first_footer
|
|
1171
|
+
|
|
1172
|
+
if all_selected:
|
|
1173
|
+
template_variables = prompt_variable_names(all_selected)
|
|
1174
|
+
|
|
1175
|
+
# Replace selected elements with placeholders
|
|
1176
|
+
for elem, var in zip(all_selected, template_variables):
|
|
1177
|
+
replace_with_placeholder(doc, elem, var)
|
|
1178
|
+
|
|
1179
|
+
# Interactive variable selection for text boxes
|
|
1180
|
+
if textboxes:
|
|
1181
|
+
textbox_selections, textbox_replacements = prompt_textbox_variable_selection(textboxes)
|
|
1182
|
+
if textbox_selections:
|
|
1183
|
+
textbox_vars = textbox_selections_to_variables(textbox_selections)
|
|
1184
|
+
template_variables.extend(textbox_vars)
|
|
1185
|
+
else:
|
|
1186
|
+
# Non-interactive mode: use provided variables
|
|
1187
|
+
if variables:
|
|
1188
|
+
for var_name, location in variables.items():
|
|
1189
|
+
template_variables.append(TemplateVariable(
|
|
1190
|
+
name=var_name,
|
|
1191
|
+
location=location.split('/')[0] if '/' in location else 'body',
|
|
1192
|
+
position=location.split('/')[1] if '/' in location else location,
|
|
1193
|
+
original_content='',
|
|
1194
|
+
syntax='both'
|
|
1195
|
+
))
|
|
1196
|
+
|
|
1197
|
+
# Extract and save styles
|
|
1198
|
+
styles = extract_styles(source_docx)
|
|
1199
|
+
table_styles = extract_table_styles(source_docx)
|
|
1200
|
+
save_styles(styles, table_styles, template_path / 'styles.xml')
|
|
1201
|
+
|
|
1202
|
+
# Remove body content after cover page
|
|
1203
|
+
if include_cover_page and cover_boundary >= 0:
|
|
1204
|
+
remove_body_content(doc, keep_first_n=cover_boundary + 1)
|
|
1205
|
+
else:
|
|
1206
|
+
# Remove all body content if no cover page
|
|
1207
|
+
remove_body_content(doc, keep_first_n=0)
|
|
1208
|
+
|
|
1209
|
+
# Save template document (without text box replacements first)
|
|
1210
|
+
doc.save(template_path / 'template.docx')
|
|
1211
|
+
|
|
1212
|
+
# Apply text box replacements if any
|
|
1213
|
+
if textbox_replacements:
|
|
1214
|
+
replace_text_in_textbox(
|
|
1215
|
+
template_path / 'template.docx',
|
|
1216
|
+
template_path / 'template.docx',
|
|
1217
|
+
textbox_replacements
|
|
1218
|
+
)
|
|
1219
|
+
|
|
1220
|
+
# Generate manifest with cover page feature flag
|
|
1221
|
+
generate_manifest(
|
|
1222
|
+
template_name,
|
|
1223
|
+
source_docx.name,
|
|
1224
|
+
template_variables,
|
|
1225
|
+
template_path / 'manifest.xml',
|
|
1226
|
+
cover_page_enabled=include_cover_page and cover_boundary >= 0
|
|
1227
|
+
)
|
|
1228
|
+
|
|
1229
|
+
# Generate variables.xml with defaults from original content
|
|
1230
|
+
generate_variables_xml(template_variables, template_path / 'variables.xml')
|
|
1231
|
+
|
|
1232
|
+
# Extract fonts from source document
|
|
1233
|
+
fonts_extracted = _extract_template_fonts(source_docx, template_path, templates_dir)
|
|
1234
|
+
|
|
1235
|
+
print(f"\nTemplate created: {template_path}/")
|
|
1236
|
+
if include_cover_page and cover_boundary >= 0:
|
|
1237
|
+
print(f" Cover page: paragraphs 1-{cover_boundary + 1} preserved")
|
|
1238
|
+
if textboxes:
|
|
1239
|
+
print(f" Text boxes found: {len(textboxes)}")
|
|
1240
|
+
print(f" Variables: {len(template_variables)}")
|
|
1241
|
+
if fonts_extracted:
|
|
1242
|
+
print(f" Fonts extracted: {len(fonts_extracted)}")
|
|
1243
|
+
|
|
1244
|
+
return template_path
|
|
1245
|
+
|
|
1246
|
+
|
|
1247
|
+
def _extract_template_fonts(
|
|
1248
|
+
source_docx: Path,
|
|
1249
|
+
template_path: Path,
|
|
1250
|
+
templates_dir: Path
|
|
1251
|
+
) -> List[str]:
|
|
1252
|
+
"""Extract fonts from source document to template fonts directory.
|
|
1253
|
+
|
|
1254
|
+
If fonts are embedded in the source, extracts and deobfuscates them.
|
|
1255
|
+
If fonts are not embedded, searches default fonts and system fonts.
|
|
1256
|
+
|
|
1257
|
+
Args:
|
|
1258
|
+
source_docx: Path to the source DOCX file.
|
|
1259
|
+
template_path: Path to the template directory.
|
|
1260
|
+
templates_dir: Path to the templates directory (for default fonts).
|
|
1261
|
+
|
|
1262
|
+
Returns:
|
|
1263
|
+
List of font names that were extracted.
|
|
1264
|
+
"""
|
|
1265
|
+
fonts_dir = template_path / 'fonts'
|
|
1266
|
+
extracted_fonts = []
|
|
1267
|
+
|
|
1268
|
+
# Get fonts used in the document
|
|
1269
|
+
doc_fonts = extract_fonts_from_docx(source_docx)
|
|
1270
|
+
|
|
1271
|
+
if not doc_fonts:
|
|
1272
|
+
return extracted_fonts
|
|
1273
|
+
|
|
1274
|
+
# Check which fonts are embedded
|
|
1275
|
+
embedded_font_names = [name for name, info in doc_fonts.items() if info['embedded']]
|
|
1276
|
+
non_embedded_font_names = [name for name, info in doc_fonts.items() if not info['embedded']]
|
|
1277
|
+
|
|
1278
|
+
# Extract embedded fonts
|
|
1279
|
+
if embedded_font_names:
|
|
1280
|
+
fonts_dir.mkdir(parents=True, exist_ok=True)
|
|
1281
|
+
extracted_paths = extract_embedded_fonts(source_docx, fonts_dir)
|
|
1282
|
+
if extracted_paths:
|
|
1283
|
+
for path in extracted_paths:
|
|
1284
|
+
font_name = get_font_name_from_file(path)
|
|
1285
|
+
if font_name:
|
|
1286
|
+
extracted_fonts.append(font_name)
|
|
1287
|
+
|
|
1288
|
+
# Search for non-embedded fonts in default fonts directory and system
|
|
1289
|
+
if non_embedded_font_names:
|
|
1290
|
+
default_fonts_dir = templates_dir / 'default' / 'fonts'
|
|
1291
|
+
search_dirs = []
|
|
1292
|
+
if default_fonts_dir.exists():
|
|
1293
|
+
search_dirs.append(default_fonts_dir)
|
|
1294
|
+
|
|
1295
|
+
for font_name in non_embedded_font_names:
|
|
1296
|
+
# Skip common system fonts that don't need embedding
|
|
1297
|
+
if _is_common_system_font(font_name):
|
|
1298
|
+
continue
|
|
1299
|
+
|
|
1300
|
+
# Find font files
|
|
1301
|
+
found = find_font_file(font_name, search_dirs, include_system=True)
|
|
1302
|
+
if found:
|
|
1303
|
+
fonts_dir.mkdir(parents=True, exist_ok=True)
|
|
1304
|
+
# Copy font files to template
|
|
1305
|
+
for variant, font_path in found.items():
|
|
1306
|
+
dest_name = f"{font_name.replace(' ', '')}-{variant.capitalize()}{font_path.suffix}"
|
|
1307
|
+
dest_path = fonts_dir / dest_name
|
|
1308
|
+
if not dest_path.exists():
|
|
1309
|
+
shutil.copy2(font_path, dest_path)
|
|
1310
|
+
extracted_fonts.append(font_name)
|
|
1311
|
+
else:
|
|
1312
|
+
print(f" Warning: Could not find font '{font_name}' for embedding")
|
|
1313
|
+
|
|
1314
|
+
return extracted_fonts
|
|
1315
|
+
|
|
1316
|
+
|
|
1317
|
+
def _is_common_system_font(font_name: str) -> bool:
|
|
1318
|
+
"""Check if a font is a common system font that doesn't need embedding.
|
|
1319
|
+
|
|
1320
|
+
Args:
|
|
1321
|
+
font_name: Font family name.
|
|
1322
|
+
|
|
1323
|
+
Returns:
|
|
1324
|
+
True if the font is commonly available on most systems.
|
|
1325
|
+
"""
|
|
1326
|
+
common_fonts = {
|
|
1327
|
+
'arial', 'times new roman', 'times', 'courier new', 'courier',
|
|
1328
|
+
'verdana', 'georgia', 'trebuchet ms', 'impact', 'comic sans ms',
|
|
1329
|
+
'calibri', 'cambria', 'consolas', 'segoe ui',
|
|
1330
|
+
'helvetica', 'helvetica neue',
|
|
1331
|
+
'liberation sans', 'liberation serif', 'liberation mono',
|
|
1332
|
+
'dejavu sans', 'dejavu serif', 'dejavu sans mono',
|
|
1333
|
+
}
|
|
1334
|
+
return font_name.lower() in common_fonts
|