File size: 8,437 Bytes
3913f6f
 
 
 
 
9c60e2c
 
 
 
 
939527c
3913f6f
6ce52dc
 
 
 
 
b15f880
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3913f6f
 
 
 
 
67cd891
3913f6f
 
939527c
 
e0a8d80
 
3913f6f
 
e0a8d80
 
 
3913f6f
 
e0a8d80
 
 
 
 
 
3913f6f
 
939527c
 
e0a8d80
 
3913f6f
 
 
 
b15f880
939527c
b15f880
3913f6f
b15f880
e0a8d80
 
3913f6f
 
 
e0a8d80
 
 
2e3717c
 
69fee5e
e0a8d80
 
 
3913f6f
e0a8d80
 
 
67cd891
3913f6f
e0a8d80
3913f6f
 
 
 
e0a8d80
 
3913f6f
 
 
67cd891
939527c
 
3913f6f
 
 
 
 
e0a8d80
 
 
 
3913f6f
 
e0a8d80
 
3913f6f
 
 
e0a8d80
 
3913f6f
 
 
 
 
 
9c60e2c
e0a8d80
9c60e2c
3913f6f
9c60e2c
e0a8d80
9c60e2c
 
 
 
 
 
 
 
 
 
 
 
 
 
e0a8d80
9c60e2c
e0a8d80
9c60e2c
e0a8d80
9c60e2c
 
 
 
 
 
 
 
3913f6f
67cd891
9c60e2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3913f6f
9c60e2c
 
 
 
 
3913f6f
 
 
e0a8d80
 
3913f6f
 
e0a8d80
 
3913f6f
 
6ce52dc
3913f6f
 
6ce52dc
3913f6f
6ce52dc
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
import io
import mistune
from bs4 import BeautifulSoup
from docx import Document
from docx.shared import Pt, Inches
from docx.enum.section import WD_SECTION, WD_ORIENT
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from config import APP_CONFIG


class DocxBuildError(RuntimeError):
    """Raised when markdown cannot be rendered into a valid DOCX document."""


_UNNUMBERED_REFERENCE_HEADINGS = frozenset({
    "references",
    "参考文献",
    "литература",
    "список литературы",
    "пайдаланылған әдебиеттер",
})


def _normalize_heading_label(text):
    """Normalize a heading for exact front/back-matter label matching."""
    value = " ".join(str(text or "").replace("\u00a0", " ").split()).casefold()
    return value.rstrip(" ::")


class DocxRenderer(mistune.HTMLRenderer):
    def __init__(self):
        super().__init__()
        self.doc = Document()
        self.h_counters = [0] * 6
        self.is_first_h1 = True
        try:
            style = self.doc.styles['Normal']
            style.font.name = APP_CONFIG["docx_styles"]["font_name"]
            style.font.size = Pt(APP_CONFIG["docx_styles"]["font_size_pt"])
        except: 
            pass

    def _render_rich_text(self, p, html_text):
        if not html_text.strip(): 
            return
            
        soup = BeautifulSoup(html_text, 'html.parser')
        for element in soup.children:
            if isinstance(element, str): 
                p.add_run(element)
            elif element.name in ['strong', 'b']: 
                p.add_run(element.get_text()).bold = True
            elif element.name in ['em', 'i']: 
                p.add_run(element.get_text()).italic = True
            elif element.name == 'code':
                run = p.add_run(element.get_text())
                run.font.name = APP_CONFIG["docx_styles"]["code_font"]
                run.font.size = Pt(APP_CONFIG["docx_styles"]["code_size_pt"])
            else: 
                p.add_run(element.get_text())

    def heading(self, text, level):
        clean_text = BeautifulSoup(text, 'html.parser').get_text().strip()
        lower_text = clean_text.lower()
        normalized_text = _normalize_heading_label(clean_text)
        skip_keywords = APP_CONFIG["blacklists"]["meta_sections"]
        exact_reference_heading = normalized_text in _UNNUMBERED_REFERENCE_HEADINGS
        
        if exact_reference_heading or any(kw in lower_text for kw in skip_keywords) or (level == 1 and self.is_first_h1):
            if level == 1: 
                self.is_first_h1 = False
            self.doc.add_heading(clean_text, level=1)
            return ''

        if level == 1: 
            self.is_first_h1 = False
            
        idx = level - 1
        if 0 <= idx < 6:
            for j in range(idx):
                if self.h_counters[j] == 0: 
                    self.h_counters[j] = 1
                    
            self.h_counters[idx] += 1
            for i in range(idx + 1, 6): 
                self.h_counters[i] = 0
                
            num_str = ".".join(map(str, self.h_counters[0:idx+1]))
            self.doc.add_heading(f"{num_str} {clean_text}", level=level)
        else: 
            self.doc.add_heading(clean_text, level=level)
        return ''

    def paragraph(self, text):
        if text.strip(): 
            self._render_rich_text(self.doc.add_paragraph(), text)
        return ''

    def block_code(self, code, info=None):
        run = self.doc.add_paragraph().add_run(code)
        run.font.name = APP_CONFIG["docx_styles"]["code_font"]
        run.font.size = Pt(APP_CONFIG["docx_styles"]["code_size_pt"])
        return ''

    def block_quote(self, text):
        p = self.doc.add_paragraph()
        self._render_rich_text(p, text)
        try: 
            p.style = 'Intense Quote' if 'Intense Quote' in self.doc.styles else 'Normal'
        except: 
            pass
        return ''

    def list(self, text, ordered, **attrs): 
        return text

    def list_item(self, text):
        if text.strip():
            p = self.doc.add_paragraph()
            p.style = 'List Bullet'
            self._render_rich_text(p, text)
        return ''

    def table(self, text):
        soup = BeautifulSoup(text, 'html.parser')
        rows = soup.find_all('tr')
        if not rows:
            return ''

        max_cols = max(len(row.find_all(['td', 'th'])) for row in rows)
        if max_cols == 0:
            return ''

        header_labels = [cell.get_text(strip=True) for cell in rows[0].find_all(['td', 'th'])]
        qualitative_headers = [
            'Higher-order Theme', 'Empirical Concept', 'Process Stage',
            'Case/Actor', 'Evidence Role', 'Representative Quote',
        ]
        qualitative_evidence_table = header_labels == qualitative_headers

        if qualitative_evidence_table:
            previous = self.doc.sections[-1]
            landscape = self.doc.add_section(WD_SECTION.NEW_PAGE)
            landscape.orientation = WD_ORIENT.LANDSCAPE
            landscape.page_width, landscape.page_height = previous.page_height, previous.page_width

        table = self.doc.add_table(rows=len(rows), cols=max_cols)
        try:
            table.style = 'Table Grid'
        except:
            pass

        if qualitative_evidence_table:
            table.autofit = False
        widths = [1.15, 1.10, 0.85, 0.85, 0.75, 3.80] if qualitative_evidence_table else []
        if qualitative_evidence_table:
            for grid_col, width in zip(table._tbl.tblGrid.gridCol_lst, widths):
                grid_col.set(qn('w:w'), str(int(width * 1440)))

        for i, row in enumerate(rows):
            for j, cell in enumerate(row.find_all(['td', 'th'])):
                if j >= max_cols:
                    continue
                target = table.cell(i, j)
                target.text = cell.get_text(strip=True)
                if qualitative_evidence_table:
                    target.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.TOP
                    target.width = Inches(widths[j])
                    tc_pr = target._tc.get_or_add_tcPr()
                    tc_w = tc_pr.first_child_found_in('w:tcW')
                    if tc_w is not None:
                        tc_w.set(qn('w:type'), 'dxa')
                        tc_w.set(qn('w:w'), str(int(widths[j] * 1440)))
                    for paragraph in target.paragraphs:
                        paragraph.paragraph_format.space_before = Pt(0)
                        paragraph.paragraph_format.space_after = Pt(0)
                        for run in paragraph.runs:
                            run.font.size = Pt(9)

        if qualitative_evidence_table and table.rows:
            header_pr = table.rows[0]._tr.get_or_add_trPr()
            header = OxmlElement('w:tblHeader')
            header.set(qn('w:val'), 'true')
            header_pr.append(header)
            for row in table.rows:
                tr_pr = row._tr.get_or_add_trPr()
                cant_split = OxmlElement('w:cantSplit')
                tr_pr.append(cant_split)

        self.doc.add_paragraph()
        if qualitative_evidence_table:
            current = self.doc.sections[-1]
            portrait = self.doc.add_section(WD_SECTION.NEW_PAGE)
            portrait.orientation = WD_ORIENT.PORTRAIT
            portrait.page_width, portrait.page_height = current.page_height, current.page_width
        return ''

    def thematic_break(self):
        self.doc.add_paragraph('_' * 50)
        return ''

    def image(self, src, alt="", title=None):
        self.doc.add_paragraph(f"[Image: {alt or src}]")
        return ''

def text_to_docx(markdown_content):
    """Render markdown strictly; never disguise renderer failures as success."""
    try:
        renderer = DocxRenderer()
        mistune.create_markdown(renderer=renderer, plugins=['table'])(str(markdown_content or ''))
        doc = renderer.doc
        if not doc.paragraphs and not doc.tables:
            raise DocxBuildError("DOCX renderer produced no document content.")
        stream = io.BytesIO()
        doc.save(stream)
        stream.seek(0)
        return stream
    except DocxBuildError:
        raise
    except Exception as exc:
        raise DocxBuildError(f"DOCX rendering failed: {exc}") from exc