Spaces:
Paused

File size: 12,029 Bytes
bc9f3e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""backend/docx_export.py β€” Shared Markdown β†’ Word (.docx) exporter.



Single source of truth for converting Markdown reports/answers into Word

(.docx) documents via python-docx. The Data Analysis tab converts its

agent-written `report.md` with markdown_to_docx(); any other tab (RAG,

Deep Research, …) can offer Word export of an answer by handing the raw

text to markdown_text_to_docx().



Self-contained on purpose: only the stdlib plus a lazy python-docx import

(the same lazy-import convention as knowledge_base.index_docx_file), so

importing this module never drags in the heavy model stack. Both public

functions are total β€” bad markup, missing files, or a missing python-docx

degrade to a plain-text Word document or None, and never raise into a

chat handler.



Public API

----------

markdown_to_docx(md_path, image_search_dirs=None, max_chars=200_000)

    Read a Markdown file and write a .docx beside it (md_path with a

    .docx suffix). Returns the .docx path, or None (unreadable/missing

    source, no python-docx).



markdown_text_to_docx(markdown_text, docx_path, image_search_dirs=None,

                      max_chars=200_000)

    Convert Markdown TEXT directly into a Word document at docx_path β€”

    the building block the file version delegates to. Use this when the

    markdown lives in memory (e.g. a chat answer) rather than on disk.



Supported Markdown (best effort, everything else β†’ plain text): headings,

bullet/numbered lists, blockquotes, fenced code blocks, tables,

horizontal rules, standalone images (embedded when the file exists), and

inline **bold** / *italic* / `code` / [links].

"""

import re
from pathlib import Path
from typing import Optional


def _strip_inline(text: str) -> str:
    """Plain-text version of a markdown line (for headings): drop **bold**,

    *italic*, `code`, and [text](url) markup."""
    text = re.sub(r'`([^`]+)`', r'\1', text)
    text = re.sub(r'\*\*([^*]+)\*\*', r'\1', text)
    text = re.sub(r'\*([^*]+)\*', r'\1', text)
    return re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)


def _add_hr(document) -> None:
    """Thin bottom-bordered separator paragraph for a markdown `---` rule."""
    from docx.oxml import OxmlElement
    from docx.oxml.ns import qn
    p = document.add_paragraph()
    pPr = p._p.get_or_add_pPr()
    pBdr = OxmlElement('w:pBdr')
    bottom = OxmlElement('w:bottom')
    bottom.set(qn('w:val'), 'single')
    bottom.set(qn('w:sz'), '6')
    bottom.set(qn('w:space'), '1')
    bottom.set(qn('w:color'), '999999')
    pBdr.append(bottom)
    pPr.append(pBdr)


def _add_rich_text(paragraph, text: str) -> None:
    """Best-effort inline markdown β†’ docx runs: **bold**, *italic*,

    `code`, and [text](url) links (rendered as text + URL)."""
    from docx.shared import Pt
    token_re = re.compile(r'(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*|\[[^\]]+\]\([^)]+\))')
    for tok in token_re.split(text):
        if not tok:
            continue
        if len(tok) > 4 and tok.startswith('**') and tok.endswith('**'):
            r = paragraph.add_run(tok[2:-2])
            r.bold = True
        elif len(tok) > 2 and tok.startswith('`') and tok.endswith('`'):
            r = paragraph.add_run(tok[1:-1])
            r.font.name = 'Consolas'
            r.font.size = Pt(9.5)
        else:
            m = re.match(r'\[([^\]]+)\]\(([^)]+)\)', tok)
            if m:
                r = paragraph.add_run(m.group(1))
                r.bold = True
                r2 = paragraph.add_run(f' ({m.group(2)})')
                r2.font.size = Pt(8.5)
            elif len(tok) > 2 and tok.startswith('*') and tok.endswith('*'):
                r = paragraph.add_run(tok[1:-1])
                r.italic = True
            else:
                paragraph.add_run(tok)


def _resolve_image(ref: str, base_dir: Path,

                   search_dirs: Optional[list] = None) -> Optional[Path]:
    """Resolve a markdown image reference to a real file: absolute path,

    relative to the document's own directory, or relative to any of the

    caller-provided image search directories (e.g. the data-analysis

    output dir where matplotlib charts land)."""
    p = Path(ref)
    if not p.is_absolute():
        candidates = [base_dir / p]
        if search_dirs:
            candidates += [Path(d) / p for d in search_dirs]
        for c in candidates:
            if c.is_file():
                return c
        return None
    return p if p.is_file() else None


def markdown_text_to_docx(markdown_text: str, docx_path: str,

                          image_search_dirs: Optional[list] = None,

                          max_chars: int = 200_000) -> Optional[str]:
    """Convert Markdown TEXT into a Word (.docx) document at `docx_path`.



    Best-effort markdown β†’ OOXML (see the module docstring for the

    supported constructs). Anything that fails to map cleanly falls back

    to plain text, and on any unexpected error the raw text is written as

    plain paragraphs so a Word export is still produced. Returns

    `docx_path` on success, or None only if python-docx is unavailable

    and even the fallback fails. Never raises.

    """
    try:
        import docx
        from docx.enum.text import WD_ALIGN_PARAGRAPH
        from docx.shared import Inches, Pt
    except Exception:
        return None
    try:
        out = Path(docx_path)
        out.parent.mkdir(parents=True, exist_ok=True)
        text = (markdown_text or '')[:max_chars]
        document = docx.Document()
        lines = text.split('\n')
        i = 0
        while i < len(lines):
            line = lines[i].rstrip('\r')
            stripped = line.strip()

            # Fenced code block
            if stripped.startswith('```'):
                i += 1
                while i < len(lines) and not lines[i].strip().startswith('```'):
                    p = document.add_paragraph()
                    r = p.add_run(lines[i])
                    r.font.name = 'Consolas'
                    r.font.size = Pt(9)
                    i += 1
                i += 1  # skip the closing fence
                continue

            # Markdown table: consecutive | ... | rows, skipping |---|---|
            # separators. Guarded against indented-code lines whose stripped
            # form starts with '|' (only non-indented pipe lines are tables).
            if (stripped.startswith('|') and stripped.endswith('|')
                    and '|' in stripped[1:-1]
                    and line and line[0] not in (' ', '\t')):
                j = i
                table_rows = []
                while (j < len(lines)
                       and (not lines[j] or lines[j][0] not in (' ', '\t'))
                       and lines[j].strip().startswith('|')
                       and lines[j].strip().endswith('|')):
                    table_rows.append(lines[j].strip())
                    j += 1
                rows = []
                for tr in table_rows:
                    cells = [c.strip() for c in tr.strip('|').split('|')]
                    if all(re.fullmatch(r':?-{2,}:?', c) for c in cells if c):
                        continue  # separator row
                    rows.append(cells)
                if len(rows) >= 2:
                    ncols = max(len(r) for r in rows)
                    table = document.add_table(rows=len(rows), cols=ncols)
                    try:
                        table.style = 'Table Grid'
                    except Exception:
                        pass
                    for ri, cells in enumerate(rows):
                        for ci in range(ncols):
                            table.rows[ri].cells[ci].text = (
                                cells[ci] if ci < len(cells) else '')
                    document.add_paragraph()
                    i = j
                    continue

            # Heading
            m = re.match(r'^(#{1,6})\s+(.*)$', stripped)
            if m:
                document.add_heading(_strip_inline(m.group(2)),
                                     level=min(len(m.group(1)), 6))
                i += 1
                continue

            # Horizontal rule
            if re.fullmatch(r'([-*_])\1{2,}', stripped):
                _add_hr(document)
                i += 1
                continue

            # Blockquote
            if stripped.startswith('>'):
                p = document.add_paragraph()
                p.paragraph_format.left_indent = Inches(0.3)
                r = p.add_run(stripped.lstrip('> ').strip())
                r.italic = True
                i += 1
                continue

            # Bullet list
            m = re.match(r'^[-*+]\s+(.*)$', stripped)
            if m:
                p = document.add_paragraph(style='List Bullet')
                _add_rich_text(p, m.group(1))
                i += 1
                continue

            # Numbered list
            m = re.match(r'^\d+[.)]\s+(.*)$', stripped)
            if m:
                p = document.add_paragraph(style='List Number')
                _add_rich_text(p, m.group(1))
                i += 1
                continue

            # Image on its own line
            m = re.match(r'^!\[([^\]]*)\]\(([^)]+)\)$', stripped)
            if m:
                img = _resolve_image(m.group(2), out.parent, image_search_dirs)
                if img:
                    p = document.add_paragraph()
                    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
                    try:
                        p.add_run().add_picture(str(img), width=Inches(6))
                        cap = m.group(1).strip()
                        if cap:
                            cp = document.add_paragraph()
                            cp.alignment = WD_ALIGN_PARAGRAPH.CENTER
                            cr = cp.add_run(cap)
                            cr.italic = True
                            cr.font.size = Pt(8.5)
                        i += 1
                        continue
                    except Exception:
                        pass  # image load failed β†’ fall through to alt text
                p = document.add_paragraph()
                _add_rich_text(p, m.group(1) or m.group(2))
                i += 1
                continue

            if not stripped:
                i += 1
                continue

            # Plain paragraph
            p = document.add_paragraph()
            _add_rich_text(p, stripped)
            i += 1

        document.save(str(out))
        return str(out)
    except Exception:
        # Absolute fallback: dump the raw text as plain paragraphs so a
        # Word export is still available even if a construct mis-parsed.
        try:
            document = docx.Document()
            for ln in text.split('\n'):
                document.add_paragraph(ln)
            document.save(str(out))
            return str(out)
        except Exception:
            return None


def markdown_to_docx(md_path: str,

                     image_search_dirs: Optional[list] = None,

                     max_chars: int = 200_000) -> Optional[str]:
    """Read a Markdown file and write a .docx beside it (same name with a

    .docx suffix). Returns the .docx path, or None if the source is

    missing/unreadable or python-docx is unavailable. Never raises."""
    try:
        md = Path(md_path)
        if not md.is_file():
            return None
        text = md.read_text(encoding='utf-8', errors='replace')
    except Exception:
        # Unreadable source (locked/permission) β†’ no Word export at all;
        # never raise into the chat handler.
        return None
    return markdown_text_to_docx(
        text, str(md.with_suffix('.docx')),
        image_search_dirs=image_search_dirs, max_chars=max_chars)