Download backend/docx_export.py from localailb/assistant: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/spaces/localailb/assistant/resolve/main/backend/docx_export.py
- Command line
-
hf download hf://spaces/localailb/assistant/backend/docx_export.py
-
curl -L -o docx_export.py https://huggingface.co/spaces/localailb/assistant/resolve/main/backend/docx_export.py
12 kB
| """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) | |