@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,354 @@
|
|
|
1
|
+
"""Graphviz DOT diagram extraction and rendering."""
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Dict, List, Optional, Tuple
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
# Supported Graphviz layout engines
|
|
14
|
+
LAYOUT_ENGINES = ['dot', 'neato', 'fdp', 'circo', 'twopi', 'sfdp']
|
|
15
|
+
DEFAULT_LAYOUT = 'dot'
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def inject_graphviz_styling(
|
|
19
|
+
dot_code: str,
|
|
20
|
+
font_size: int = 14,
|
|
21
|
+
font_family: str = "Source Sans Pro"
|
|
22
|
+
) -> str:
|
|
23
|
+
"""Inject consistent styling into Graphviz DOT code.
|
|
24
|
+
|
|
25
|
+
Adds graph, node, and edge font attributes for consistent sizing.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
dot_code: Original DOT code.
|
|
29
|
+
font_size: Font size in points (default: 14).
|
|
30
|
+
font_family: Font family name (default: "Source Sans Pro").
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
DOT code with styling injected.
|
|
34
|
+
"""
|
|
35
|
+
# Build style attributes
|
|
36
|
+
style_attrs = f'''
|
|
37
|
+
graph [fontsize={font_size}, fontname="{font_family}"];
|
|
38
|
+
node [fontsize={font_size}, fontname="{font_family}"];
|
|
39
|
+
edge [fontsize={font_size - 2}, fontname="{font_family}"];
|
|
40
|
+
'''
|
|
41
|
+
|
|
42
|
+
# Find the opening brace of the graph/digraph
|
|
43
|
+
brace_match = re.search(r'((?:di)?graph\s+\w*\s*)\{', dot_code, re.IGNORECASE)
|
|
44
|
+
if brace_match:
|
|
45
|
+
# Insert after the opening brace
|
|
46
|
+
insert_pos = brace_match.end()
|
|
47
|
+
return dot_code[:insert_pos] + style_attrs + dot_code[insert_pos:]
|
|
48
|
+
else:
|
|
49
|
+
# No graph declaration found, return as-is
|
|
50
|
+
logger.warning("Could not find graph declaration in DOT code for style injection")
|
|
51
|
+
return dot_code
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class GraphvizDiagramInfo:
|
|
56
|
+
"""Information about a rendered Graphviz diagram.
|
|
57
|
+
|
|
58
|
+
Attributes:
|
|
59
|
+
path: Path to the rendered image file.
|
|
60
|
+
code: Original DOT code.
|
|
61
|
+
logical_width: Logical width in points (1/72 inch).
|
|
62
|
+
logical_height: Logical height in points.
|
|
63
|
+
units_per_inch: Conversion factor (72 for Graphviz points).
|
|
64
|
+
layout_engine: Layout engine used for rendering.
|
|
65
|
+
"""
|
|
66
|
+
path: Path
|
|
67
|
+
code: str = ""
|
|
68
|
+
logical_width: Optional[float] = None
|
|
69
|
+
logical_height: Optional[float] = None
|
|
70
|
+
units_per_inch: float = 72.0 # Graphviz uses points
|
|
71
|
+
layout_engine: str = DEFAULT_LAYOUT
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def is_graphviz_available() -> bool:
|
|
75
|
+
"""Check if Graphviz (dot command) is available.
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
True if Graphviz is installed and accessible.
|
|
79
|
+
"""
|
|
80
|
+
return shutil.which('dot') is not None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def extract_graphviz_blocks(markdown_content: str) -> List[str]:
|
|
84
|
+
"""Extract Graphviz DOT code blocks from markdown content.
|
|
85
|
+
|
|
86
|
+
Supports both ```dot and ```graphviz fenced code blocks.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
markdown_content: Markdown text containing Graphviz diagrams.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
List of DOT diagram code strings.
|
|
93
|
+
"""
|
|
94
|
+
# Match ```dot or ```graphviz code blocks
|
|
95
|
+
pattern = r'```(?:dot|graphviz)\n(.*?)```'
|
|
96
|
+
blocks = re.findall(pattern, markdown_content, re.DOTALL)
|
|
97
|
+
return [block.strip() for block in blocks]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def extract_layout_engine(dot_code: str) -> str:
|
|
101
|
+
"""Extract layout engine from DOT code if specified.
|
|
102
|
+
|
|
103
|
+
Looks for layout attribute in graph declaration:
|
|
104
|
+
- graph [layout=neato]
|
|
105
|
+
- digraph G { layout=fdp; ... }
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
dot_code: DOT diagram source code.
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
Layout engine name or 'dot' as default.
|
|
112
|
+
"""
|
|
113
|
+
# Look for layout= in the code
|
|
114
|
+
layout_match = re.search(r'layout\s*=\s*"?(\w+)"?', dot_code, re.IGNORECASE)
|
|
115
|
+
if layout_match:
|
|
116
|
+
engine = layout_match.group(1).lower()
|
|
117
|
+
if engine in LAYOUT_ENGINES:
|
|
118
|
+
return engine
|
|
119
|
+
return DEFAULT_LAYOUT
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def extract_graphviz_dimensions(dot_code: str, layout: str = DEFAULT_LAYOUT) -> Tuple[Optional[float], Optional[float]]:
|
|
123
|
+
"""Extract logical dimensions from Graphviz DOT source using JSON output.
|
|
124
|
+
|
|
125
|
+
Uses the -Tjson output which provides precise bounding boxes after
|
|
126
|
+
layout calculation but before rasterization.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
dot_code: DOT diagram source code.
|
|
130
|
+
layout: Layout engine to use (dot, neato, fdp, etc.).
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
Tuple of (width, height) in points (1/72 inch), or (None, None) if extraction fails.
|
|
134
|
+
"""
|
|
135
|
+
if not is_graphviz_available():
|
|
136
|
+
return None, None
|
|
137
|
+
|
|
138
|
+
try:
|
|
139
|
+
result = subprocess.run(
|
|
140
|
+
[layout, '-Tjson'],
|
|
141
|
+
input=dot_code,
|
|
142
|
+
capture_output=True,
|
|
143
|
+
text=True,
|
|
144
|
+
timeout=30
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
if result.returncode != 0:
|
|
148
|
+
logger.warning(f"Graphviz JSON extraction failed: {result.stderr}")
|
|
149
|
+
return None, None
|
|
150
|
+
|
|
151
|
+
data = json.loads(result.stdout)
|
|
152
|
+
bb = data.get('bb', '0,0,0,0')
|
|
153
|
+
|
|
154
|
+
# bb format is "minx,miny,maxx,maxy"
|
|
155
|
+
parts = bb.split(',')
|
|
156
|
+
if len(parts) >= 4:
|
|
157
|
+
width = float(parts[2]) - float(parts[0])
|
|
158
|
+
height = float(parts[3]) - float(parts[1])
|
|
159
|
+
return width, height
|
|
160
|
+
|
|
161
|
+
except subprocess.TimeoutExpired:
|
|
162
|
+
logger.warning("Graphviz JSON extraction timed out")
|
|
163
|
+
except json.JSONDecodeError as e:
|
|
164
|
+
logger.warning(f"Failed to parse Graphviz JSON output: {e}")
|
|
165
|
+
except Exception as e:
|
|
166
|
+
logger.warning(f"Graphviz dimension extraction error: {e}")
|
|
167
|
+
|
|
168
|
+
return None, None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def render_graphviz_diagram(
|
|
172
|
+
dot_code: str,
|
|
173
|
+
output_path: Path,
|
|
174
|
+
format: str = "png",
|
|
175
|
+
dpi: int = 96,
|
|
176
|
+
layout: Optional[str] = None,
|
|
177
|
+
extract_dimensions: bool = False
|
|
178
|
+
) -> Tuple[Path, Optional[float], Optional[float]]:
|
|
179
|
+
"""Render a single Graphviz DOT diagram to image.
|
|
180
|
+
|
|
181
|
+
Args:
|
|
182
|
+
dot_code: DOT diagram source code.
|
|
183
|
+
output_path: Path where image should be saved (extension will be adjusted).
|
|
184
|
+
format: Output format - 'png' or 'svg' (default: 'png').
|
|
185
|
+
dpi: Resolution for PNG output (default: 96).
|
|
186
|
+
layout: Layout engine to use (auto-detected from code if not specified).
|
|
187
|
+
extract_dimensions: Whether to extract logical dimensions.
|
|
188
|
+
|
|
189
|
+
Returns:
|
|
190
|
+
Tuple of (path to generated image, logical_width, logical_height).
|
|
191
|
+
Dimensions are in points (1/72 inch), None if extraction fails.
|
|
192
|
+
|
|
193
|
+
Raises:
|
|
194
|
+
RuntimeError: If Graphviz is not available or rendering fails.
|
|
195
|
+
"""
|
|
196
|
+
if not is_graphviz_available():
|
|
197
|
+
raise RuntimeError(
|
|
198
|
+
"Graphviz is not installed. "
|
|
199
|
+
"Please install it: brew install graphviz (macOS) or apt install graphviz (Linux)"
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
# Determine layout engine
|
|
203
|
+
if layout is None:
|
|
204
|
+
layout = extract_layout_engine(dot_code)
|
|
205
|
+
|
|
206
|
+
# Adjust output path extension based on format
|
|
207
|
+
if format == "svg":
|
|
208
|
+
output_path = output_path.with_suffix('.svg')
|
|
209
|
+
else:
|
|
210
|
+
output_path = output_path.with_suffix('.png')
|
|
211
|
+
|
|
212
|
+
# Extract dimensions if requested
|
|
213
|
+
logical_width, logical_height = None, None
|
|
214
|
+
if extract_dimensions:
|
|
215
|
+
logical_width, logical_height = extract_graphviz_dimensions(dot_code, layout)
|
|
216
|
+
|
|
217
|
+
# Build rendering command
|
|
218
|
+
cmd = [layout, f'-T{format}', '-o', str(output_path)]
|
|
219
|
+
|
|
220
|
+
if format == "png":
|
|
221
|
+
cmd.extend([f'-Gdpi={dpi}'])
|
|
222
|
+
|
|
223
|
+
# Run Graphviz
|
|
224
|
+
result = subprocess.run(
|
|
225
|
+
cmd,
|
|
226
|
+
input=dot_code,
|
|
227
|
+
capture_output=True,
|
|
228
|
+
text=True,
|
|
229
|
+
timeout=60
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
if result.returncode != 0:
|
|
233
|
+
raise RuntimeError(f"Failed to render Graphviz diagram: {result.stderr}")
|
|
234
|
+
|
|
235
|
+
if not output_path.exists():
|
|
236
|
+
raise RuntimeError(f"Graphviz output file not created: {output_path}")
|
|
237
|
+
|
|
238
|
+
return output_path, logical_width, logical_height
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def render_all_graphviz_diagrams(
|
|
242
|
+
markdown_content: str,
|
|
243
|
+
temp_dir: Path,
|
|
244
|
+
format: str = "png",
|
|
245
|
+
dpi: int = 96,
|
|
246
|
+
extract_dimensions: bool = False
|
|
247
|
+
) -> Dict[str, GraphvizDiagramInfo]:
|
|
248
|
+
"""Extract and render all Graphviz diagrams from markdown.
|
|
249
|
+
|
|
250
|
+
Args:
|
|
251
|
+
markdown_content: Markdown text containing Graphviz diagrams.
|
|
252
|
+
temp_dir: Directory to store rendered images.
|
|
253
|
+
format: Output format - 'png' or 'svg' (default: 'png').
|
|
254
|
+
dpi: Resolution for PNG output (default: 96).
|
|
255
|
+
extract_dimensions: Whether to extract logical dimensions for consistent sizing.
|
|
256
|
+
|
|
257
|
+
Returns:
|
|
258
|
+
Dictionary mapping original DOT code to GraphvizDiagramInfo objects.
|
|
259
|
+
"""
|
|
260
|
+
if not is_graphviz_available():
|
|
261
|
+
logger.warning("Graphviz is not installed. Skipping Graphviz diagrams.")
|
|
262
|
+
return {}
|
|
263
|
+
|
|
264
|
+
blocks = extract_graphviz_blocks(markdown_content)
|
|
265
|
+
diagram_map = {}
|
|
266
|
+
|
|
267
|
+
ext = 'svg' if format == 'svg' else 'png'
|
|
268
|
+
for idx, dot_code in enumerate(blocks):
|
|
269
|
+
try:
|
|
270
|
+
layout = extract_layout_engine(dot_code)
|
|
271
|
+
output_path = temp_dir / f"graphviz_{idx}.{ext}"
|
|
272
|
+
|
|
273
|
+
rendered_path, logical_width, logical_height = render_graphviz_diagram(
|
|
274
|
+
dot_code, output_path, format=format, dpi=dpi,
|
|
275
|
+
layout=layout, extract_dimensions=extract_dimensions
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
diagram_map[dot_code] = GraphvizDiagramInfo(
|
|
279
|
+
path=rendered_path,
|
|
280
|
+
code=dot_code,
|
|
281
|
+
logical_width=logical_width,
|
|
282
|
+
logical_height=logical_height,
|
|
283
|
+
units_per_inch=72.0, # Graphviz uses points
|
|
284
|
+
layout_engine=layout
|
|
285
|
+
)
|
|
286
|
+
except Exception as e:
|
|
287
|
+
logger.error(f"Failed to render Graphviz diagram {idx}: {e}")
|
|
288
|
+
# Continue with other diagrams
|
|
289
|
+
|
|
290
|
+
return diagram_map
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def replace_graphviz_with_images(
|
|
294
|
+
markdown_content: str,
|
|
295
|
+
diagram_map: Dict[str, GraphvizDiagramInfo],
|
|
296
|
+
relative_to: Optional[Path] = None
|
|
297
|
+
) -> str:
|
|
298
|
+
"""Replace Graphviz code blocks with image references.
|
|
299
|
+
|
|
300
|
+
Args:
|
|
301
|
+
markdown_content: Original markdown content.
|
|
302
|
+
diagram_map: Mapping of DOT code to GraphvizDiagramInfo objects.
|
|
303
|
+
relative_to: Optional path to make image references relative to.
|
|
304
|
+
|
|
305
|
+
Returns:
|
|
306
|
+
Modified markdown with image references instead of Graphviz blocks.
|
|
307
|
+
"""
|
|
308
|
+
# Build list of image references in order
|
|
309
|
+
image_refs = []
|
|
310
|
+
for dot_code, diagram_info in diagram_map.items():
|
|
311
|
+
if relative_to:
|
|
312
|
+
try:
|
|
313
|
+
rel_path = diagram_info.path.relative_to(relative_to)
|
|
314
|
+
image_ref = f""
|
|
315
|
+
except ValueError:
|
|
316
|
+
image_ref = f""
|
|
317
|
+
else:
|
|
318
|
+
image_ref = f""
|
|
319
|
+
|
|
320
|
+
image_refs.append(image_ref)
|
|
321
|
+
|
|
322
|
+
# Replace all graphviz blocks in order
|
|
323
|
+
idx = 0
|
|
324
|
+
|
|
325
|
+
def replacer(match):
|
|
326
|
+
nonlocal idx
|
|
327
|
+
if idx < len(image_refs):
|
|
328
|
+
result = image_refs[idx]
|
|
329
|
+
idx += 1
|
|
330
|
+
return result
|
|
331
|
+
return match.group(0)
|
|
332
|
+
|
|
333
|
+
# Pattern to match any graphviz block
|
|
334
|
+
pattern = r'```(?:dot|graphviz)\s*\n.*?```'
|
|
335
|
+
modified = re.sub(pattern, replacer, markdown_content, flags=re.DOTALL)
|
|
336
|
+
|
|
337
|
+
return modified
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def has_graphviz_blocks(content: str, format: str = 'markdown') -> bool:
|
|
341
|
+
"""Check if content contains Graphviz diagram blocks.
|
|
342
|
+
|
|
343
|
+
Args:
|
|
344
|
+
content: Document content to check.
|
|
345
|
+
format: Content format - 'markdown' or 'asciidoc'.
|
|
346
|
+
|
|
347
|
+
Returns:
|
|
348
|
+
True if Graphviz blocks are found.
|
|
349
|
+
"""
|
|
350
|
+
if format == 'markdown':
|
|
351
|
+
return bool(re.search(r'```(?:dot|graphviz)\n', content))
|
|
352
|
+
elif format == 'asciidoc':
|
|
353
|
+
return bool(re.search(r'\[(?:source,)?(?:dot|graphviz)\]', content, re.IGNORECASE))
|
|
354
|
+
return False
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""Image extraction module for DOCX files."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Dict, List, Any, TYPE_CHECKING
|
|
4
|
+
from docx import Document
|
|
5
|
+
from docx.oxml.ns import qn
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
from .docx_reader import ExtractionResult
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# Mapping of content types to file extensions
|
|
13
|
+
CONTENT_TYPE_EXTENSIONS = {
|
|
14
|
+
'image/png': '.png',
|
|
15
|
+
'image/jpeg': '.jpg',
|
|
16
|
+
'image/jpg': '.jpg',
|
|
17
|
+
'image/gif': '.gif',
|
|
18
|
+
'image/bmp': '.bmp',
|
|
19
|
+
'image/tiff': '.tiff',
|
|
20
|
+
'image/x-emf': '.emf',
|
|
21
|
+
'image/x-wmf': '.wmf',
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def get_image_extension(content_type: str) -> str:
|
|
26
|
+
"""Get file extension for a given content type.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
content_type: The MIME content type.
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
File extension including the dot.
|
|
33
|
+
"""
|
|
34
|
+
return CONTENT_TYPE_EXTENSIONS.get(content_type, '.png')
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def extract_images_from_docx(doc_path: Path) -> Dict[str, bytes]:
|
|
38
|
+
"""Extract all images from a DOCX file.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
doc_path: Path to the DOCX file.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
Dictionary mapping embed IDs to image data.
|
|
45
|
+
"""
|
|
46
|
+
doc = Document(doc_path)
|
|
47
|
+
images = {}
|
|
48
|
+
|
|
49
|
+
# Access the document's relationships to find images
|
|
50
|
+
for rel_id, rel in doc.part.rels.items():
|
|
51
|
+
if "image" in rel.reltype:
|
|
52
|
+
try:
|
|
53
|
+
image_part = rel.target_part
|
|
54
|
+
images[rel_id] = {
|
|
55
|
+
'data': image_part.blob,
|
|
56
|
+
'content_type': image_part.content_type,
|
|
57
|
+
'filename': Path(image_part.partname).name
|
|
58
|
+
}
|
|
59
|
+
except Exception:
|
|
60
|
+
# Skip images that can't be accessed
|
|
61
|
+
pass
|
|
62
|
+
|
|
63
|
+
return images
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def save_image(image_data: bytes, output_path: Path) -> None:
|
|
67
|
+
"""Save image data to a file.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
image_data: Raw image bytes.
|
|
71
|
+
output_path: Path to save the image.
|
|
72
|
+
"""
|
|
73
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
74
|
+
output_path.write_bytes(image_data)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def create_images_directory(document_path: Path) -> Path:
|
|
78
|
+
"""Create the images directory for a document.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
document_path: Path to the document file (MD or DOCX).
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
Path to the images directory.
|
|
85
|
+
"""
|
|
86
|
+
images_dir = document_path.parent / f"{document_path.stem}_images"
|
|
87
|
+
images_dir.mkdir(parents=True, exist_ok=True)
|
|
88
|
+
return images_dir
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def create_images_directories(
|
|
92
|
+
source_path: Path,
|
|
93
|
+
output_path: Path
|
|
94
|
+
) -> tuple[Path, Path]:
|
|
95
|
+
"""Create images directories for both source and output locations.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
source_path: Path to the source file (DOCX).
|
|
99
|
+
output_path: Path to the output file (MD).
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
Tuple of (source_images_dir, output_images_dir).
|
|
103
|
+
If locations are the same, both paths will be identical.
|
|
104
|
+
"""
|
|
105
|
+
source_images_dir = create_images_directory(source_path)
|
|
106
|
+
output_images_dir = create_images_directory(output_path)
|
|
107
|
+
|
|
108
|
+
return source_images_dir, output_images_dir
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def save_images_to_both_locations(
|
|
112
|
+
image_data: bytes,
|
|
113
|
+
filename: str,
|
|
114
|
+
source_images_dir: Path,
|
|
115
|
+
output_images_dir: Path
|
|
116
|
+
) -> None:
|
|
117
|
+
"""Save image data to both source and output directories.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
image_data: Raw image bytes.
|
|
121
|
+
filename: Name of the image file.
|
|
122
|
+
source_images_dir: Directory for source location images.
|
|
123
|
+
output_images_dir: Directory for output location images.
|
|
124
|
+
"""
|
|
125
|
+
# Save to source location
|
|
126
|
+
source_path = source_images_dir / filename
|
|
127
|
+
save_image(image_data, source_path)
|
|
128
|
+
|
|
129
|
+
# Save to output location if different
|
|
130
|
+
if source_images_dir != output_images_dir:
|
|
131
|
+
output_path = output_images_dir / filename
|
|
132
|
+
save_image(image_data, output_path)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def extract_images(
|
|
136
|
+
doc_path: Path,
|
|
137
|
+
output_md_path: Path,
|
|
138
|
+
extraction_result: 'ExtractionResult'
|
|
139
|
+
) -> 'ExtractionResult':
|
|
140
|
+
"""Extract images from DOCX and update the extraction result.
|
|
141
|
+
|
|
142
|
+
Images are saved to both the source DOCX location and the output
|
|
143
|
+
Markdown location (if different directories).
|
|
144
|
+
|
|
145
|
+
Args:
|
|
146
|
+
doc_path: Path to the source DOCX file.
|
|
147
|
+
output_md_path: Path to the output markdown file.
|
|
148
|
+
extraction_result: The extraction result to update.
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
Updated ExtractionResult with image references in markdown.
|
|
152
|
+
"""
|
|
153
|
+
from .docx_reader import ExtractionResult, ExtractedElement
|
|
154
|
+
|
|
155
|
+
# Get images from the document
|
|
156
|
+
doc_images = extract_images_from_docx(doc_path)
|
|
157
|
+
|
|
158
|
+
if not doc_images:
|
|
159
|
+
return extraction_result
|
|
160
|
+
|
|
161
|
+
# Create images directories in both locations
|
|
162
|
+
source_images_dir, output_images_dir = create_images_directories(
|
|
163
|
+
doc_path, output_md_path
|
|
164
|
+
)
|
|
165
|
+
relative_images_dir = f"{output_md_path.stem}_images"
|
|
166
|
+
|
|
167
|
+
# Track image file mappings
|
|
168
|
+
image_files: Dict[str, str] = {} # embed_id -> relative path
|
|
169
|
+
image_counter = 1
|
|
170
|
+
|
|
171
|
+
# Save each image to both locations and track its path
|
|
172
|
+
for embed_id, image_info in doc_images.items():
|
|
173
|
+
ext = get_image_extension(image_info['content_type'])
|
|
174
|
+
filename = f"image_{image_counter:03d}{ext}"
|
|
175
|
+
|
|
176
|
+
# Save to both source and output locations
|
|
177
|
+
save_images_to_both_locations(
|
|
178
|
+
image_info['data'],
|
|
179
|
+
filename,
|
|
180
|
+
source_images_dir,
|
|
181
|
+
output_images_dir
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
# Store relative path for markdown reference
|
|
185
|
+
image_files[embed_id] = f"{relative_images_dir}/{filename}"
|
|
186
|
+
image_counter += 1
|
|
187
|
+
|
|
188
|
+
# Update markdown with image references
|
|
189
|
+
# Find positions where images should be inserted
|
|
190
|
+
updated_markdown = extraction_result.markdown
|
|
191
|
+
image_elements = []
|
|
192
|
+
|
|
193
|
+
# Match each image in extraction_result.images to its file
|
|
194
|
+
for img_info in extraction_result.images:
|
|
195
|
+
embed_id = img_info.get('embed_id')
|
|
196
|
+
if embed_id and embed_id in image_files:
|
|
197
|
+
relative_path = image_files[embed_id]
|
|
198
|
+
# Create image markdown
|
|
199
|
+
img_md = f""
|
|
200
|
+
|
|
201
|
+
# Create element for tracking
|
|
202
|
+
image_elements.append(ExtractedElement(
|
|
203
|
+
type='image',
|
|
204
|
+
content=img_md,
|
|
205
|
+
docx_path=img_info.get('docx_path', ''),
|
|
206
|
+
metadata={
|
|
207
|
+
'embed_id': embed_id,
|
|
208
|
+
'file_path': relative_path,
|
|
209
|
+
'original_path': img_info.get('docx_path', '')
|
|
210
|
+
}
|
|
211
|
+
))
|
|
212
|
+
|
|
213
|
+
# Insert image references into markdown
|
|
214
|
+
# For now, append at the end of paragraphs where they were found
|
|
215
|
+
if image_elements:
|
|
216
|
+
lines = updated_markdown.split('\n')
|
|
217
|
+
insertions = [] # (line_index, image_md)
|
|
218
|
+
|
|
219
|
+
for img_info, img_element in zip(extraction_result.images, image_elements):
|
|
220
|
+
para_index = img_info.get('paragraph_index', 0)
|
|
221
|
+
# Find the corresponding line in markdown
|
|
222
|
+
# This is approximate - we insert after the paragraph
|
|
223
|
+
line_count = 0
|
|
224
|
+
for i, element in enumerate(extraction_result.elements):
|
|
225
|
+
if element.docx_path == f"/w:body/w:p[{para_index + 1}]":
|
|
226
|
+
insertions.append((element.line_end, img_element.content))
|
|
227
|
+
break
|
|
228
|
+
|
|
229
|
+
# Sort insertions in reverse order to maintain line numbers
|
|
230
|
+
insertions.sort(key=lambda x: x[0], reverse=True)
|
|
231
|
+
|
|
232
|
+
for line_idx, img_md in insertions:
|
|
233
|
+
if line_idx < len(lines):
|
|
234
|
+
lines.insert(line_idx + 1, '')
|
|
235
|
+
lines.insert(line_idx + 2, img_md)
|
|
236
|
+
|
|
237
|
+
updated_markdown = '\n'.join(lines)
|
|
238
|
+
|
|
239
|
+
# Create updated result
|
|
240
|
+
updated_elements = extraction_result.elements + image_elements
|
|
241
|
+
updated_images = []
|
|
242
|
+
for img_info in extraction_result.images:
|
|
243
|
+
embed_id = img_info.get('embed_id')
|
|
244
|
+
if embed_id and embed_id in image_files:
|
|
245
|
+
img_info['extracted_path'] = image_files[embed_id]
|
|
246
|
+
updated_images.append(img_info)
|
|
247
|
+
|
|
248
|
+
return ExtractionResult(
|
|
249
|
+
markdown=updated_markdown,
|
|
250
|
+
elements=updated_elements,
|
|
251
|
+
preserved_elements=extraction_result.preserved_elements,
|
|
252
|
+
images=updated_images
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def get_image_info_from_docx(doc_path: Path) -> List[Dict[str, Any]]:
|
|
257
|
+
"""Get information about all images in a DOCX file without extracting them.
|
|
258
|
+
|
|
259
|
+
Args:
|
|
260
|
+
doc_path: Path to the DOCX file.
|
|
261
|
+
|
|
262
|
+
Returns:
|
|
263
|
+
List of image information dictionaries.
|
|
264
|
+
"""
|
|
265
|
+
doc = Document(doc_path)
|
|
266
|
+
images = []
|
|
267
|
+
|
|
268
|
+
for rel_id, rel in doc.part.rels.items():
|
|
269
|
+
if "image" in rel.reltype:
|
|
270
|
+
try:
|
|
271
|
+
image_part = rel.target_part
|
|
272
|
+
images.append({
|
|
273
|
+
'embed_id': rel_id,
|
|
274
|
+
'content_type': image_part.content_type,
|
|
275
|
+
'original_filename': Path(image_part.partname).name,
|
|
276
|
+
'size': len(image_part.blob)
|
|
277
|
+
})
|
|
278
|
+
except Exception:
|
|
279
|
+
pass
|
|
280
|
+
|
|
281
|
+
return images
|