@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,551 @@
|
|
|
1
|
+
"""Text box extraction and manipulation for DOCX documents.
|
|
2
|
+
|
|
3
|
+
Handles text boxes (txbxContent elements) which are commonly used for
|
|
4
|
+
cover pages, callouts, and other formatted text blocks in Word documents.
|
|
5
|
+
"""
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import List, Dict, Any, Optional, Tuple
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from docx import Document
|
|
10
|
+
from docx.oxml.ns import qn
|
|
11
|
+
from lxml import etree
|
|
12
|
+
import zipfile
|
|
13
|
+
import re
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# XML namespaces used in DOCX
|
|
17
|
+
NAMESPACES = {
|
|
18
|
+
'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main',
|
|
19
|
+
'wp': 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing',
|
|
20
|
+
'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
|
|
21
|
+
'wps': 'http://schemas.microsoft.com/office/word/2010/wordprocessingShape',
|
|
22
|
+
'mc': 'http://schemas.openxmlformats.org/markup-compatibility/2006',
|
|
23
|
+
'v': 'urn:schemas-microsoft-com:vml',
|
|
24
|
+
'w14': 'http://schemas.microsoft.com/office/word/2010/wordml',
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class TextBoxElement:
|
|
30
|
+
"""Represents a text element within a text box."""
|
|
31
|
+
index: int
|
|
32
|
+
full_text: str
|
|
33
|
+
paragraphs: List[str]
|
|
34
|
+
location: str # 'textbox'
|
|
35
|
+
xpath: str # XPath to the txbxContent element
|
|
36
|
+
paragraph_index: int # Index in document paragraphs (approximate)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def extract_textboxes_from_docx(doc_path: Path) -> List[TextBoxElement]:
|
|
40
|
+
"""Extract all text boxes from a DOCX file.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
doc_path: Path to the DOCX file.
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
List of TextBoxElement objects.
|
|
47
|
+
"""
|
|
48
|
+
textboxes = []
|
|
49
|
+
|
|
50
|
+
with zipfile.ZipFile(doc_path, 'r') as zf:
|
|
51
|
+
with zf.open('word/document.xml') as f:
|
|
52
|
+
tree = etree.parse(f)
|
|
53
|
+
root = tree.getroot()
|
|
54
|
+
|
|
55
|
+
# Find all txbxContent elements (text box content)
|
|
56
|
+
# Two common patterns:
|
|
57
|
+
# 1. Drawing-based: w:drawing/...wps:txbx/w:txbxContent
|
|
58
|
+
# 2. VML-based: w:pict/v:rect/v:textbox/w:txbxContent
|
|
59
|
+
|
|
60
|
+
w_ns = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
|
|
61
|
+
|
|
62
|
+
index = 1
|
|
63
|
+
seen_texts = set() # Avoid duplicates from MC alternateContent
|
|
64
|
+
|
|
65
|
+
for txbx_content in root.iter(f'{w_ns}txbxContent'):
|
|
66
|
+
paragraphs = []
|
|
67
|
+
|
|
68
|
+
# Extract text from each paragraph in the text box
|
|
69
|
+
for p_elem in txbx_content.findall(f'{w_ns}p'):
|
|
70
|
+
para_texts = []
|
|
71
|
+
for t_elem in p_elem.iter(f'{w_ns}t'):
|
|
72
|
+
if t_elem.text:
|
|
73
|
+
para_texts.append(t_elem.text)
|
|
74
|
+
if para_texts:
|
|
75
|
+
paragraphs.append(''.join(para_texts))
|
|
76
|
+
|
|
77
|
+
if paragraphs:
|
|
78
|
+
full_text = '\n'.join(paragraphs)
|
|
79
|
+
|
|
80
|
+
# Skip duplicates (MC alternateContent creates copies)
|
|
81
|
+
if full_text in seen_texts:
|
|
82
|
+
continue
|
|
83
|
+
seen_texts.add(full_text)
|
|
84
|
+
|
|
85
|
+
# Try to find approximate paragraph index
|
|
86
|
+
para_idx = _find_paragraph_index(root, txbx_content, w_ns)
|
|
87
|
+
|
|
88
|
+
textboxes.append(TextBoxElement(
|
|
89
|
+
index=index,
|
|
90
|
+
full_text=full_text,
|
|
91
|
+
paragraphs=paragraphs,
|
|
92
|
+
location='textbox',
|
|
93
|
+
xpath=_get_xpath(txbx_content),
|
|
94
|
+
paragraph_index=para_idx
|
|
95
|
+
))
|
|
96
|
+
index += 1
|
|
97
|
+
|
|
98
|
+
return textboxes
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _find_paragraph_index(root, txbx_content, w_ns: str) -> int:
|
|
102
|
+
"""Find the approximate paragraph index containing the text box."""
|
|
103
|
+
# Walk up to find the containing paragraph
|
|
104
|
+
parent = txbx_content.getparent()
|
|
105
|
+
while parent is not None:
|
|
106
|
+
if parent.tag == f'{w_ns}p':
|
|
107
|
+
# Count paragraphs before this one
|
|
108
|
+
body = root.find(f'{w_ns}body')
|
|
109
|
+
if body is not None:
|
|
110
|
+
for i, p in enumerate(body.findall(f'{w_ns}p')):
|
|
111
|
+
if p is parent:
|
|
112
|
+
return i
|
|
113
|
+
break
|
|
114
|
+
parent = parent.getparent()
|
|
115
|
+
return 0
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _get_xpath(element) -> str:
|
|
119
|
+
"""Get a simplified XPath for an element."""
|
|
120
|
+
parts = []
|
|
121
|
+
current = element
|
|
122
|
+
while current is not None:
|
|
123
|
+
tag = current.tag.split('}')[-1] if '}' in current.tag else current.tag
|
|
124
|
+
parts.insert(0, tag)
|
|
125
|
+
current = current.getparent()
|
|
126
|
+
return '/' + '/'.join(parts[-5:]) # Last 5 elements
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def display_textboxes(textboxes: List[TextBoxElement]) -> None:
|
|
130
|
+
"""Display text boxes for user selection.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
textboxes: List of text box elements.
|
|
134
|
+
"""
|
|
135
|
+
if not textboxes:
|
|
136
|
+
print("\nNo text boxes found in document.")
|
|
137
|
+
return
|
|
138
|
+
|
|
139
|
+
print("\n=== Text Boxes ===")
|
|
140
|
+
for tb in textboxes:
|
|
141
|
+
print(f"\n[{tb.index}] Text Box (at paragraph ~{tb.paragraph_index + 1}):")
|
|
142
|
+
for i, para in enumerate(tb.paragraphs):
|
|
143
|
+
display_text = para[:60] + ('...' if len(para) > 60 else '')
|
|
144
|
+
print(f" Line {i+1}: \"{display_text}\"")
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def escape_xml(text: str) -> str:
|
|
148
|
+
"""Escape special XML characters in text.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
text: Text to escape.
|
|
152
|
+
|
|
153
|
+
Returns:
|
|
154
|
+
XML-escaped text.
|
|
155
|
+
"""
|
|
156
|
+
return (text
|
|
157
|
+
.replace('&', '&')
|
|
158
|
+
.replace('<', '<')
|
|
159
|
+
.replace('>', '>')
|
|
160
|
+
.replace('"', '"')
|
|
161
|
+
.replace("'", '''))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def replace_fragmented_text(content: str, old_text: str, new_text: str) -> str:
|
|
165
|
+
"""Replace text that may be fragmented across multiple w:t elements.
|
|
166
|
+
|
|
167
|
+
Word often splits text across multiple <w:t> elements due to formatting,
|
|
168
|
+
spelling/grammar checks, and other processing. This function handles:
|
|
169
|
+
- Simple contiguous text
|
|
170
|
+
- Text split by XML tags like </w:t><w:proofErr.../><w:r><w:t>
|
|
171
|
+
- Variable patterns like {{var_name}} split across elements
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
content: XML content.
|
|
175
|
+
old_text: Text to find (may be split across elements).
|
|
176
|
+
new_text: Replacement text.
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
Modified XML content.
|
|
180
|
+
"""
|
|
181
|
+
import re
|
|
182
|
+
|
|
183
|
+
# First try simple replacement
|
|
184
|
+
if old_text in content:
|
|
185
|
+
return content.replace(old_text, new_text)
|
|
186
|
+
|
|
187
|
+
# For variable patterns like {{var_name}}, build a more flexible regex
|
|
188
|
+
# that allows ANY XML content between the text characters
|
|
189
|
+
chars = list(old_text)
|
|
190
|
+
pattern_parts = []
|
|
191
|
+
for char in chars:
|
|
192
|
+
# Escape regex special characters
|
|
193
|
+
escaped_char = re.escape(char)
|
|
194
|
+
pattern_parts.append(escaped_char)
|
|
195
|
+
|
|
196
|
+
# Allow any XML tags/content between characters (including proofErr, formatting, etc.)
|
|
197
|
+
# This pattern allows: </w:t>, any number of tags, then <w:t...>
|
|
198
|
+
# The key is to be very permissive about what can appear between text characters
|
|
199
|
+
xml_between = r'(?:</w:t>(?:[^<]*<[^>]*>)*[^<]*<w:t[^>]*>)?'
|
|
200
|
+
pattern = xml_between.join(pattern_parts)
|
|
201
|
+
|
|
202
|
+
# Find all matches
|
|
203
|
+
matches = list(re.finditer(pattern, content, re.DOTALL))
|
|
204
|
+
|
|
205
|
+
if not matches:
|
|
206
|
+
# Try an even more aggressive approach for {{variable}} patterns
|
|
207
|
+
# Match the opening {{ and closing }} with the variable name in between
|
|
208
|
+
if old_text.startswith('{{') and old_text.endswith('}}'):
|
|
209
|
+
var_name = old_text[2:-2].strip()
|
|
210
|
+
# Build pattern: {{ ... var_name ... }}
|
|
211
|
+
# Allow XML between {{ and var_name, and between var_name and }}
|
|
212
|
+
aggressive_pattern = (
|
|
213
|
+
r'\{\{\s*' # Opening {{ with optional space
|
|
214
|
+
r'(?:</w:t>(?:[^<]*<[^>]*>)*[^<]*<w:t[^>]*>)?' # Allow XML breaks
|
|
215
|
+
r'\s*' + re.escape(var_name.replace('_', '')) + # var name without underscores
|
|
216
|
+
r'|' + re.escape(var_name) + # or exact var name
|
|
217
|
+
r'(?:</w:t>(?:[^<]*<[^>]*>)*[^<]*<w:t[^>]*>)?' # Allow XML breaks
|
|
218
|
+
r'\s*\}\}' # Closing }} with optional space
|
|
219
|
+
)
|
|
220
|
+
# This is too complex, let's try a different approach
|
|
221
|
+
pass
|
|
222
|
+
return content
|
|
223
|
+
|
|
224
|
+
# Replace from end to start to maintain positions
|
|
225
|
+
result = content
|
|
226
|
+
for match in reversed(matches):
|
|
227
|
+
result = result[:match.start()] + new_text + result[match.end():]
|
|
228
|
+
|
|
229
|
+
return result
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def replace_fragmented_variable(content: str, var_name: str, new_value: str) -> str:
|
|
233
|
+
"""Replace a {{variable}} pattern that may be fragmented across XML elements.
|
|
234
|
+
|
|
235
|
+
This is specialized for handling Word's tendency to split variable placeholders
|
|
236
|
+
like {{document_type}} into multiple <w:t> elements with proofErr tags.
|
|
237
|
+
|
|
238
|
+
Strategy: Find runs of <w:t> elements that together contain the variable pattern,
|
|
239
|
+
then replace the text content while preserving XML structure.
|
|
240
|
+
|
|
241
|
+
Args:
|
|
242
|
+
content: XML content.
|
|
243
|
+
var_name: Variable name (without {{ }}).
|
|
244
|
+
new_value: Replacement value.
|
|
245
|
+
|
|
246
|
+
Returns:
|
|
247
|
+
Modified XML content.
|
|
248
|
+
"""
|
|
249
|
+
import re
|
|
250
|
+
|
|
251
|
+
# First try simple replacement (variable is in a single <w:t> element)
|
|
252
|
+
simple_pattern = '{{' + var_name + '}}'
|
|
253
|
+
if simple_pattern in content:
|
|
254
|
+
return content.replace(simple_pattern, new_value)
|
|
255
|
+
|
|
256
|
+
# Also try with spaces around the variable name (Word sometimes adds spaces)
|
|
257
|
+
spaced_pattern = '{{ ' + var_name + ' }}'
|
|
258
|
+
if spaced_pattern in content:
|
|
259
|
+
return content.replace(spaced_pattern, new_value)
|
|
260
|
+
|
|
261
|
+
# For fragmented patterns, we need to find <w:t> elements that together
|
|
262
|
+
# contain {{ var_name }}. The approach:
|
|
263
|
+
# 1. Find all <w:t>...</w:t> elements
|
|
264
|
+
# 2. Look for sequences where the combined text matches our pattern
|
|
265
|
+
# 3. Replace the text in the first element, clear the others
|
|
266
|
+
|
|
267
|
+
# Pattern to find <w:t> elements with their content
|
|
268
|
+
wt_pattern = r'(<w:t[^>]*>)([^<]*)(</w:t>)'
|
|
269
|
+
|
|
270
|
+
# Find all matches with positions
|
|
271
|
+
matches = list(re.finditer(wt_pattern, content))
|
|
272
|
+
|
|
273
|
+
if not matches:
|
|
274
|
+
return content
|
|
275
|
+
|
|
276
|
+
# Build a map of text content and positions
|
|
277
|
+
# Look for sequences that form {{ var_name }}
|
|
278
|
+
target = '{{ ' + var_name + ' }}' # With spaces
|
|
279
|
+
target_no_space = '{{' + var_name + '}}' # Without spaces
|
|
280
|
+
|
|
281
|
+
result = content
|
|
282
|
+
replaced = True
|
|
283
|
+
max_iterations = 100 # Safety limit
|
|
284
|
+
iteration = 0
|
|
285
|
+
|
|
286
|
+
while replaced and iteration < max_iterations:
|
|
287
|
+
replaced = False
|
|
288
|
+
iteration += 1
|
|
289
|
+
matches = list(re.finditer(wt_pattern, result))
|
|
290
|
+
|
|
291
|
+
for i in range(len(matches)):
|
|
292
|
+
# Try to build the target string from consecutive matches
|
|
293
|
+
combined_text = ''
|
|
294
|
+
match_indices = []
|
|
295
|
+
|
|
296
|
+
for j in range(i, min(i + 20, len(matches))): # Look ahead up to 20 elements
|
|
297
|
+
combined_text += matches[j].group(2) # Add text content
|
|
298
|
+
match_indices.append(j)
|
|
299
|
+
|
|
300
|
+
# Check if we found our target
|
|
301
|
+
found_target = None
|
|
302
|
+
if target in combined_text:
|
|
303
|
+
found_target = target
|
|
304
|
+
elif target_no_space in combined_text:
|
|
305
|
+
found_target = target_no_space
|
|
306
|
+
|
|
307
|
+
if found_target:
|
|
308
|
+
# Found the pattern! Now replace carefully
|
|
309
|
+
pattern_start = combined_text.find(found_target)
|
|
310
|
+
pattern_end = pattern_start + len(found_target)
|
|
311
|
+
|
|
312
|
+
# Calculate which <w:t> elements contain parts of the pattern
|
|
313
|
+
char_pos = 0
|
|
314
|
+
elements_to_modify = []
|
|
315
|
+
for idx in match_indices:
|
|
316
|
+
elem_text = matches[idx].group(2)
|
|
317
|
+
elem_start = char_pos
|
|
318
|
+
elem_end = char_pos + len(elem_text)
|
|
319
|
+
|
|
320
|
+
# Check if this element overlaps with the pattern
|
|
321
|
+
if elem_end > pattern_start and elem_start < pattern_end:
|
|
322
|
+
elements_to_modify.append((idx, elem_start, elem_end))
|
|
323
|
+
|
|
324
|
+
char_pos = elem_end
|
|
325
|
+
|
|
326
|
+
if elements_to_modify:
|
|
327
|
+
# Build replacement: put new value in first element, empty others
|
|
328
|
+
# But we need to preserve any text before/after the pattern
|
|
329
|
+
first_idx = elements_to_modify[0][0]
|
|
330
|
+
last_idx = elements_to_modify[-1][0]
|
|
331
|
+
|
|
332
|
+
first_match = matches[first_idx]
|
|
333
|
+
last_match = matches[last_idx]
|
|
334
|
+
|
|
335
|
+
# Text before pattern in first element
|
|
336
|
+
first_elem_text = first_match.group(2)
|
|
337
|
+
first_elem_start_in_combined = sum(len(matches[k].group(2)) for k in match_indices if k < first_idx)
|
|
338
|
+
before_text = combined_text[first_elem_start_in_combined:pattern_start] if pattern_start > first_elem_start_in_combined else ''
|
|
339
|
+
|
|
340
|
+
# Text after pattern in last element
|
|
341
|
+
after_text = combined_text[pattern_end:]
|
|
342
|
+
|
|
343
|
+
# Build the new content for the range
|
|
344
|
+
# Keep XML structure intact - only modify text within <w:t> elements
|
|
345
|
+
new_content_parts = []
|
|
346
|
+
for idx in range(first_idx, last_idx + 1):
|
|
347
|
+
m = matches[idx]
|
|
348
|
+
if idx == first_idx:
|
|
349
|
+
# First element: before_text + new_value (+ after if same element)
|
|
350
|
+
if idx == last_idx:
|
|
351
|
+
new_content_parts.append(m.group(1) + before_text + new_value + after_text + m.group(3))
|
|
352
|
+
else:
|
|
353
|
+
new_content_parts.append(m.group(1) + before_text + new_value + m.group(3))
|
|
354
|
+
elif idx == last_idx:
|
|
355
|
+
# Last element: just after_text
|
|
356
|
+
new_content_parts.append(m.group(1) + after_text + m.group(3))
|
|
357
|
+
else:
|
|
358
|
+
# Middle elements: empty
|
|
359
|
+
new_content_parts.append(m.group(1) + m.group(3))
|
|
360
|
+
|
|
361
|
+
# Replace the range
|
|
362
|
+
start_pos = first_match.start()
|
|
363
|
+
end_pos = last_match.end()
|
|
364
|
+
|
|
365
|
+
# Get content between elements (XML tags, etc.)
|
|
366
|
+
inter_element_content = []
|
|
367
|
+
for idx in range(first_idx, last_idx):
|
|
368
|
+
inter_element_content.append(result[matches[idx].end():matches[idx+1].start()])
|
|
369
|
+
|
|
370
|
+
# Rebuild with new text but same structure
|
|
371
|
+
replacement = ''
|
|
372
|
+
for k, part in enumerate(new_content_parts):
|
|
373
|
+
replacement += part
|
|
374
|
+
if k < len(inter_element_content):
|
|
375
|
+
replacement += inter_element_content[k]
|
|
376
|
+
|
|
377
|
+
result = result[:start_pos] + replacement + result[end_pos:]
|
|
378
|
+
replaced = True
|
|
379
|
+
break
|
|
380
|
+
|
|
381
|
+
break # Found pattern, move to next search
|
|
382
|
+
|
|
383
|
+
if replaced:
|
|
384
|
+
break # Restart search from beginning
|
|
385
|
+
|
|
386
|
+
return result
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def replace_text_in_textbox(
|
|
390
|
+
doc_path: Path,
|
|
391
|
+
output_path: Path,
|
|
392
|
+
replacements: Dict[str, str]
|
|
393
|
+
) -> None:
|
|
394
|
+
"""Replace text in text boxes within a DOCX file.
|
|
395
|
+
|
|
396
|
+
Handles XML escaping for placeholder syntax like <variable>.
|
|
397
|
+
Also handles text that is fragmented across multiple <w:t> elements.
|
|
398
|
+
|
|
399
|
+
Args:
|
|
400
|
+
doc_path: Path to the source DOCX file.
|
|
401
|
+
output_path: Path to save the modified DOCX.
|
|
402
|
+
replacements: Dictionary mapping old text to new text (e.g., placeholders).
|
|
403
|
+
"""
|
|
404
|
+
import tempfile
|
|
405
|
+
import os
|
|
406
|
+
|
|
407
|
+
# Create a temporary directory
|
|
408
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
409
|
+
# Extract the DOCX
|
|
410
|
+
with zipfile.ZipFile(doc_path, 'r') as zf:
|
|
411
|
+
zf.extractall(tmpdir)
|
|
412
|
+
|
|
413
|
+
# Modify document.xml and all header/footer files
|
|
414
|
+
word_dir = Path(tmpdir) / 'word'
|
|
415
|
+
xml_files = [word_dir / 'document.xml']
|
|
416
|
+
|
|
417
|
+
# Dynamically find all header and footer files
|
|
418
|
+
if word_dir.exists():
|
|
419
|
+
for xml_file in word_dir.glob('header*.xml'):
|
|
420
|
+
xml_files.append(xml_file)
|
|
421
|
+
for xml_file in word_dir.glob('footer*.xml'):
|
|
422
|
+
xml_files.append(xml_file)
|
|
423
|
+
|
|
424
|
+
for xml_path in xml_files:
|
|
425
|
+
if not xml_path.exists():
|
|
426
|
+
continue
|
|
427
|
+
|
|
428
|
+
with open(xml_path, 'r', encoding='utf-8') as f:
|
|
429
|
+
content = f.read()
|
|
430
|
+
|
|
431
|
+
# Perform replacements with XML escaping
|
|
432
|
+
for old_text, new_text in replacements.items():
|
|
433
|
+
# Escape both old and new text for XML matching
|
|
434
|
+
# e.g., <var> in search becomes <var> to match the XML content
|
|
435
|
+
escaped_new = escape_xml(new_text)
|
|
436
|
+
|
|
437
|
+
# Check if this is a {{variable}} pattern
|
|
438
|
+
if old_text.startswith('{{') and old_text.endswith('}}'):
|
|
439
|
+
var_name = old_text[2:-2] # Extract variable name
|
|
440
|
+
# Use specialized variable replacement for fragmented patterns
|
|
441
|
+
content = replace_fragmented_variable(content, var_name, escaped_new)
|
|
442
|
+
else:
|
|
443
|
+
# Use general fragmented text replacement
|
|
444
|
+
escaped_old = escape_xml(old_text)
|
|
445
|
+
content = replace_fragmented_text(content, escaped_old, escaped_new)
|
|
446
|
+
|
|
447
|
+
with open(xml_path, 'w', encoding='utf-8') as f:
|
|
448
|
+
f.write(content)
|
|
449
|
+
|
|
450
|
+
# Repack the DOCX
|
|
451
|
+
with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
|
452
|
+
for root_dir, dirs, files in os.walk(tmpdir):
|
|
453
|
+
for file in files:
|
|
454
|
+
file_path = Path(root_dir) / file
|
|
455
|
+
arcname = file_path.relative_to(tmpdir)
|
|
456
|
+
zf.write(file_path, arcname)
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def extract_textbox_variables(
|
|
460
|
+
doc_path: Path,
|
|
461
|
+
interactive: bool = True
|
|
462
|
+
) -> Tuple[List[TextBoxElement], Dict[str, str]]:
|
|
463
|
+
"""Extract text boxes and optionally prompt for variable selection.
|
|
464
|
+
|
|
465
|
+
Args:
|
|
466
|
+
doc_path: Path to the DOCX file.
|
|
467
|
+
interactive: Whether to prompt for user input.
|
|
468
|
+
|
|
469
|
+
Returns:
|
|
470
|
+
Tuple of (selected textboxes, replacements dict).
|
|
471
|
+
"""
|
|
472
|
+
textboxes = extract_textboxes_from_docx(doc_path)
|
|
473
|
+
|
|
474
|
+
if not textboxes:
|
|
475
|
+
return [], {}
|
|
476
|
+
|
|
477
|
+
if not interactive:
|
|
478
|
+
return textboxes, {}
|
|
479
|
+
|
|
480
|
+
display_textboxes(textboxes)
|
|
481
|
+
|
|
482
|
+
print("\nWhich text box elements should be variables?")
|
|
483
|
+
print("Enter as: textbox_index.line_index (e.g., '1.1,1.2,1.3' for lines 1-3 of textbox 1)")
|
|
484
|
+
print("Or 'none' to skip: ", end='')
|
|
485
|
+
|
|
486
|
+
try:
|
|
487
|
+
response = input().strip().lower()
|
|
488
|
+
except EOFError:
|
|
489
|
+
return [], {}
|
|
490
|
+
|
|
491
|
+
if response == 'none' or response == '':
|
|
492
|
+
return [], {}
|
|
493
|
+
|
|
494
|
+
selected = []
|
|
495
|
+
replacements = {}
|
|
496
|
+
|
|
497
|
+
# Parse selection like "1.1,1.2,1.3"
|
|
498
|
+
for item in response.split(','):
|
|
499
|
+
item = item.strip()
|
|
500
|
+
if '.' in item:
|
|
501
|
+
try:
|
|
502
|
+
tb_idx, line_idx = item.split('.')
|
|
503
|
+
tb_idx = int(tb_idx)
|
|
504
|
+
line_idx = int(line_idx)
|
|
505
|
+
|
|
506
|
+
# Find the textbox
|
|
507
|
+
for tb in textboxes:
|
|
508
|
+
if tb.index == tb_idx and line_idx <= len(tb.paragraphs):
|
|
509
|
+
para_text = tb.paragraphs[line_idx - 1]
|
|
510
|
+
|
|
511
|
+
print(f"\nEnter variable name for \"{para_text[:50]}{'...' if len(para_text) > 50 else ''}\": ", end='')
|
|
512
|
+
try:
|
|
513
|
+
var_name = input().strip()
|
|
514
|
+
except EOFError:
|
|
515
|
+
var_name = f"var_{tb_idx}_{line_idx}"
|
|
516
|
+
|
|
517
|
+
if not var_name:
|
|
518
|
+
var_name = f"var_{tb_idx}_{line_idx}"
|
|
519
|
+
|
|
520
|
+
# Sanitize variable name
|
|
521
|
+
var_name = re.sub(r'[^a-zA-Z0-9_]', '_', var_name)
|
|
522
|
+
|
|
523
|
+
replacements[para_text] = f"{{{{{var_name}}}}}"
|
|
524
|
+
selected.append((tb, line_idx, var_name, para_text))
|
|
525
|
+
break
|
|
526
|
+
except ValueError:
|
|
527
|
+
continue
|
|
528
|
+
|
|
529
|
+
return textboxes, replacements
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def find_textbox_text(doc_path: Path, search_text: str) -> Optional[TextBoxElement]:
|
|
533
|
+
"""Find a text box containing specific text.
|
|
534
|
+
|
|
535
|
+
Args:
|
|
536
|
+
doc_path: Path to the DOCX file.
|
|
537
|
+
search_text: Text to search for.
|
|
538
|
+
|
|
539
|
+
Returns:
|
|
540
|
+
TextBoxElement if found, None otherwise.
|
|
541
|
+
"""
|
|
542
|
+
textboxes = extract_textboxes_from_docx(doc_path)
|
|
543
|
+
|
|
544
|
+
for tb in textboxes:
|
|
545
|
+
if search_text in tb.full_text:
|
|
546
|
+
return tb
|
|
547
|
+
for para in tb.paragraphs:
|
|
548
|
+
if search_text in para:
|
|
549
|
+
return tb
|
|
550
|
+
|
|
551
|
+
return None
|