-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmd_export.py
More file actions
430 lines (359 loc) · 14.4 KB
/
md_export.py
File metadata and controls
430 lines (359 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
"""
Markdown → DOCX / PPTX / PDF export logic.
A small, dependency-light Markdown parser turns a .md file into a list of
blocks (headings, paragraphs, bullets, tables, code) which are then rendered
into each target format.
"""
import re
from pathlib import Path
EXPORT_FORMATS = {
"docx": ".docx",
"pptx": ".pptx",
"pdf": ".pdf",
}
def export_file(input_path: Path, output_dir: Path, target_format: str) -> Path:
"""Convert a Markdown file to the given format. Returns the output path."""
fmt = target_format.lower().lstrip(".")
if fmt not in EXPORT_FORMATS:
raise ValueError(f"Unsupported export format: {target_format}")
text = Path(input_path).read_text(encoding="utf-8")
blocks = parse_markdown(text)
output_path = output_dir / (input_path.stem + EXPORT_FORMATS[fmt])
if fmt == "docx":
_export_docx(blocks, output_path)
elif fmt == "pptx":
_export_pptx(blocks, input_path.stem, output_path)
elif fmt == "pdf":
_export_pdf(blocks, output_path)
return output_path
# ---------------------------------------------------------------------------
# Markdown parsing → blocks
# ---------------------------------------------------------------------------
# Block tuples:
# ("heading", level:int, text:str)
# ("para", text:str)
# ("bullet", level:int, text:str)
# ("table", rows:list[list[str]])
# ("code", text:str)
_HEADING_RE = re.compile(r"^(#{1,6})\s+(.*)$")
_BULLET_RE = re.compile(r"^(\s*)([-*+]|\d+\.)\s+(.*)$")
def parse_markdown(text: str) -> list[tuple]:
lines = text.replace("\r\n", "\n").replace("\r", "\n").split("\n")
blocks: list[tuple] = []
para_buf: list[str] = []
i = 0
def flush_para():
if para_buf:
blocks.append(("para", " ".join(para_buf).strip()))
para_buf.clear()
n = len(lines)
while i < n:
line = lines[i]
stripped = line.strip()
# Fenced code block
if stripped.startswith("```"):
flush_para()
i += 1
code_lines = []
while i < n and not lines[i].strip().startswith("```"):
code_lines.append(lines[i])
i += 1
i += 1 # skip closing fence
blocks.append(("code", "\n".join(code_lines)))
continue
# Blank line ends a paragraph
if not stripped:
flush_para()
i += 1
continue
# Table: consecutive lines starting with '|'
if stripped.startswith("|"):
flush_para()
table_lines = []
while i < n and lines[i].strip().startswith("|"):
table_lines.append(lines[i].strip())
i += 1
rows = _parse_table(table_lines)
if rows:
blocks.append(("table", rows))
continue
# Heading
m = _HEADING_RE.match(stripped)
if m:
flush_para()
level = len(m.group(1))
blocks.append(("heading", level, _strip_inline(m.group(2).strip())))
i += 1
continue
# Bullet / ordered list item
m = _BULLET_RE.match(line)
if m:
flush_para()
indent = len(m.group(1).replace("\t", " "))
level = indent // 2
blocks.append(("bullet", level, _strip_inline(m.group(3).strip())))
i += 1
continue
# Horizontal rule — ignore
if re.fullmatch(r"(-{3,}|\*{3,}|_{3,})", stripped):
flush_para()
i += 1
continue
# Plain paragraph text
para_buf.append(stripped)
i += 1
flush_para()
return blocks
def _parse_table(table_lines: list[str]) -> list[list[str]]:
rows = []
for ln in table_lines:
cells = [c.strip() for c in ln.strip().strip("|").split("|")]
# Skip the separator row (---, :---: etc.)
if cells and all(re.fullmatch(r":?-{1,}:?", c.strip()) for c in cells if c.strip()):
if any(c.strip() for c in cells):
continue
rows.append([_strip_inline(c) for c in cells])
return rows
# ---------------------------------------------------------------------------
# Inline formatting helpers
# ---------------------------------------------------------------------------
def _strip_inline(text: str) -> str:
"""Remove Markdown emphasis/link/code syntax, keeping the visible text."""
text = re.sub(r"!\[([^\]]*)\]\([^)]*\)", r"\1", text) # images
text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text) # links
text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text) # bold
text = re.sub(r"__([^_]+)__", r"\1", text)
text = re.sub(r"\*([^*]+)\*", r"\1", text) # italic
text = re.sub(r"_([^_]+)_", r"\1", text)
text = re.sub(r"`([^`]+)`", r"\1", text) # inline code
return text.strip()
def _inline_runs(text: str) -> list[tuple[str, bool, bool]]:
"""Split text into (chunk, bold, italic) runs for rich rendering."""
# First strip links/images/code to their visible text.
text = re.sub(r"!\[([^\]]*)\]\([^)]*\)", r"\1", text)
text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text)
text = re.sub(r"`([^`]+)`", r"\1", text)
runs: list[tuple[str, bool, bool]] = []
pattern = re.compile(r"(\*\*[^*]+\*\*|__[^_]+__|\*[^*]+\*|_[^_]+_)")
pos = 0
for m in pattern.finditer(text):
if m.start() > pos:
runs.append((text[pos:m.start()], False, False))
token = m.group(0)
if token.startswith("**") or token.startswith("__"):
runs.append((token[2:-2], True, False))
else:
runs.append((token[1:-1], False, True))
pos = m.end()
if pos < len(text):
runs.append((text[pos:], False, False))
return runs or [(text, False, False)]
# ---------------------------------------------------------------------------
# DOCX renderer
# ---------------------------------------------------------------------------
def _export_docx(blocks: list[tuple], output_path: Path) -> None:
from docx import Document
from docx.shared import Pt
doc = Document()
for block in blocks:
kind = block[0]
if kind == "heading":
_, level, text = block
doc.add_heading(text, level=min(level, 9))
elif kind == "para":
p = doc.add_paragraph()
for chunk, bold, italic in _inline_runs(block[1]):
run = p.add_run(chunk)
run.bold = bold
run.italic = italic
elif kind == "bullet":
_, level, text = block
style = "List Bullet" if level == 0 else f"List Bullet {min(level + 1, 3)}"
try:
p = doc.add_paragraph(style=style)
except KeyError:
p = doc.add_paragraph(style="List Bullet")
for chunk, bold, italic in _inline_runs(text):
run = p.add_run(chunk)
run.bold = bold
run.italic = italic
elif kind == "code":
p = doc.add_paragraph()
run = p.add_run(block[1])
run.font.name = "Courier New"
run.font.size = Pt(9)
elif kind == "table":
rows = block[1]
if not rows:
continue
cols = max(len(r) for r in rows)
table = doc.add_table(rows=0, cols=cols)
table.style = "Light Grid Accent 1"
for r_idx, row in enumerate(rows):
cells = table.add_row().cells
for c_idx in range(cols):
cells[c_idx].text = row[c_idx] if c_idx < len(row) else ""
if r_idx == 0:
for cell in cells:
for para in cell.paragraphs:
for run in para.runs:
run.bold = True
doc.save(str(output_path))
# ---------------------------------------------------------------------------
# PPTX renderer
# ---------------------------------------------------------------------------
def _export_pptx(blocks: list[tuple], deck_title: str, output_path: Path) -> None:
from pptx import Presentation
from pptx.util import Inches, Pt
prs = Presentation()
blank = prs.slide_layouts[6] # fully blank layout
title_only = prs.slide_layouts[5]
slides: list[dict] = []
current: dict | None = None
def new_slide(title: str):
nonlocal current
current = {"title": title, "body": [], "tables": []}
slides.append(current)
for block in blocks:
kind = block[0]
if kind == "heading" and block[1] <= 2:
new_slide(block[2])
else:
if current is None:
new_slide(deck_title)
if kind == "heading":
current["body"].append((0, block[2], True))
elif kind == "bullet":
current["body"].append((block[1], block[2], False))
elif kind == "para":
current["body"].append((0, _strip_inline(block[1]), False))
elif kind == "code":
for ln in block[1].split("\n"):
current["body"].append((1, ln, False))
elif kind == "table":
current["tables"].append(block[1])
if not slides:
new_slide(deck_title)
for sl in slides:
layout = title_only if not sl["body"] and not sl["tables"] else blank
slide = prs.slides.add_slide(layout)
# Title
title_box = slide.shapes.add_textbox(
Inches(0.6), Inches(0.4), Inches(9), Inches(1))
tf = title_box.text_frame
tf.word_wrap = True
p = tf.paragraphs[0]
p.text = sl["title"]
p.font.size = Pt(32)
p.font.bold = True
# Body bullets
if sl["body"]:
body_box = slide.shapes.add_textbox(
Inches(0.7), Inches(1.5), Inches(8.6), Inches(5))
btf = body_box.text_frame
btf.word_wrap = True
first = True
for level, text, is_heading in sl["body"]:
p = btf.paragraphs[0] if first else btf.add_paragraph()
first = False
p.text = text
p.level = min(level, 4)
p.font.size = Pt(20 if is_heading else 16)
p.font.bold = is_heading
# Tables
top = Inches(1.5 if not sl["body"] else 5.0)
for rows in sl["tables"]:
if not rows:
continue
n_rows = len(rows)
n_cols = max(len(r) for r in rows)
gtable = slide.shapes.add_table(
n_rows, n_cols, Inches(0.7), top,
Inches(8.6), Inches(0.4 * n_rows)).table
for r_idx, row in enumerate(rows):
for c_idx in range(n_cols):
cell = gtable.cell(r_idx, c_idx)
cell.text = row[c_idx] if c_idx < len(row) else ""
for para in cell.text_frame.paragraphs:
para.font.size = Pt(12)
if r_idx == 0:
para.font.bold = True
top = Inches(top.inches + 0.4 * n_rows + 0.3)
prs.save(str(output_path))
# ---------------------------------------------------------------------------
# PDF renderer
# ---------------------------------------------------------------------------
def _export_pdf(blocks: list[tuple], output_path: Path) -> None:
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.lib import colors
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Preformatted,
ListFlowable, ListItem)
styles = getSampleStyleSheet()
code_style = ParagraphStyle(
"CodeBlock", parent=styles["Code"], fontSize=8, leading=10,
backColor=colors.whitesmoke, leftIndent=6, borderPadding=4)
def esc(t: str) -> str:
return (t.replace("&", "&").replace("<", "<").replace(">", ">"))
def rich(t: str) -> str:
out = ""
for chunk, bold, italic in _inline_runs(t):
c = esc(chunk)
if bold:
c = f"<b>{c}</b>"
if italic:
c = f"<i>{c}</i>"
out += c
return out
story = []
doc = SimpleDocTemplate(
str(output_path), pagesize=letter,
leftMargin=0.9 * inch, rightMargin=0.9 * inch,
topMargin=0.9 * inch, bottomMargin=0.9 * inch)
for block in blocks:
kind = block[0]
if kind == "heading":
_, level, text = block
style_name = f"Heading{min(level, 4)}"
story.append(Paragraph(esc(text), styles[style_name]))
story.append(Spacer(1, 4))
elif kind == "para":
story.append(Paragraph(rich(block[1]), styles["BodyText"]))
story.append(Spacer(1, 6))
elif kind == "bullet":
_, level, text = block
bullet_style = ParagraphStyle(
f"Bullet{level}", parent=styles["BodyText"],
leftIndent=18 * (level + 1), bulletIndent=6 * (level + 1))
story.append(Paragraph(rich(text), bullet_style, bulletText="•"))
elif kind == "code":
story.append(Preformatted(block[1], code_style))
story.append(Spacer(1, 6))
elif kind == "table":
rows = block[1]
if not rows:
continue
cols = max(len(r) for r in rows)
data = [
[Paragraph(esc(r[c]) if c < len(r) else "", styles["BodyText"])
for c in range(cols)]
for r in rows
]
tbl = Table(data, hAlign="LEFT")
tbl.setStyle(TableStyle([
("GRID", (0, 0), (-1, -1), 0.5, colors.grey),
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#f0f0f0")),
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LEFTPADDING", (0, 0), (-1, -1), 5),
("RIGHTPADDING", (0, 0), (-1, -1), 5),
("TOPPADDING", (0, 0), (-1, -1), 3),
("BOTTOMPADDING", (0, 0), (-1, -1), 3),
]))
story.append(tbl)
story.append(Spacer(1, 8))
if not story:
story.append(Paragraph("(empty document)", styles["BodyText"]))
doc.build(story)