File size: 8,073 Bytes
7c956fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Export pipeline for Humanizer System

Handles Markdown to HTML, PDF, and DOCX conversion

"""

import io
import markdown
from typing import Optional
import config

try:
    from docx import Document
    HAS_DOCX = True
except ImportError:
    HAS_DOCX = False

try:
    from weasyprint import HTML
    HAS_WEASYPRINT = True
except (ImportError, OSError) as e:
    # OSError can occur on Windows if GTK3 is not installed
    HAS_WEASYPRINT = False
    WEAZYPRINT_ERROR = str(e)


class ExportPipeline:
    """Export pipeline for converting humanized text to various formats"""
    
    def __init__(self):
        self.settings = config.settings
    
    def to_html(self, markdown_text: str) -> str:
        """

        Convert Markdown to HTML

        Preserves formatting as specified in requirements

        """
        # Use markdown library with extensions for better formatting
        html = markdown.markdown(
            markdown_text,
            extensions=[
                'extra',  # Adds tables, footnotes, etc.
                'codehilite',  # Syntax highlighting for code blocks
                'toc',  # Table of contents
                'nl2br',  # Convert newlines to <br>
                'sane_lists',  # Better list handling
            ],
            output_format='html5'
        )
        
        # Wrap in basic HTML structure for better rendering
        html_template = f"""

        <!DOCTYPE html>

        <html>

        <head>

            <meta charset="UTF-8">

            <meta name="viewport" content="width=device-width, initial-scale=1.0">

            <title>Humanized Text</title>

            <style>

                body {{

                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;

                    line-height: 1.6;

                    color: #333;

                    max-width: 800px;

                    margin: 0 auto;

                    padding: 20px;

                }}

                h1, h2, h3, h4, h5, h6 {{

                    margin-top: 1.5em;

                    margin-bottom: 0.5em;

                    font-weight: 600;

                    line-height: 1.25;

                }}

                p {{

                    margin-top: 0;

                    margin-bottom: 1em;

                }}

                ul, ol {{

                    margin-top: 0;

                    margin-bottom: 1em;

                    padding-left: 2em;

                }}

                li {{

                    margin-bottom: 0.5em;

                }}

                code {{

                    background-color: #f6f8fa;

                    padding: 0.2em 0.4em;

                    border-radius: 3px;

                    font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;

                    font-size: 0.9em;

                }}

                pre {{

                    background-color: #f6f8fa;

                    padding: 1em;

                    border-radius: 5px;

                    overflow: auto;

                }}

                blockquote {{

                    margin: 0;

                    padding-left: 1em;

                    border-left: 3px solid #ddd;

                    color: #666;

                }}

                hr {{

                    border: 0;

                    height: 1px;

                    background-color: #ddd;

                    margin: 2em 0;

                }}

                table {{

                    border-collapse: collapse;

                    width: 100%;

                    margin-bottom: 1em;

                }}

                th, td {{

                    border: 1px solid #ddd;

                    padding: 0.5em;

                    text-align: left;

                }}

                th {{

                    background-color: #f6f8fa;

                    font-weight: 600;

                }}

            </style>

        </head>

        <body>

            {html}

        </body>

        </html>

        """
        
        return html_template
    
    def to_pdf(self, markdown_text: str, filename: Optional[str] = None) -> bytes:
        """

        Convert Markdown to PDF using WeasyPrint

        Returns PDF bytes

        """
        if not HAS_WEASYPRINT:
            error_msg = "WeasyPrint is not available. "
            if 'WEAZYPRINT_ERROR' in globals():
                error_msg += f"Error: {WEAZYPRINT_ERROR}. "
            error_msg += "On Windows, you may need to install GTK3. Alternatively, use DOCX or TXT export."
            raise ImportError(error_msg)
        
        # Convert Markdown to HTML
        html = self.to_html(markdown_text)
        
        # Generate PDF
        pdf_bytes = HTML(string=html).write_pdf()
        
        return pdf_bytes
    
    def to_docx(self, markdown_text: str, filename: Optional[str] = None) -> bytes:
        """

        Convert Markdown to DOCX using python-docx

        Returns DOCX bytes

        """
        if not HAS_DOCX:
            raise ImportError("python-docx is not installed. Install with: pip install python-docx")
        
        # Create a new Document
        doc = Document()
        
        # Split text into paragraphs (using double newlines as paragraph separators)
        paragraphs = markdown_text.split('\n\n')
        
        for paragraph in paragraphs:
            if paragraph.strip():
                # Clean up the paragraph (remove single newlines within paragraphs)
                clean_paragraph = ' '.join(paragraph.split('\n'))
                
                # Check if it's a heading
                if clean_paragraph.startswith('# '):
                    doc.add_heading(clean_paragraph[2:], level=1)
                elif clean_paragraph.startswith('## '):
                    doc.add_heading(clean_paragraph[3:], level=2)
                elif clean_paragraph.startswith('### '):
                    doc.add_heading(clean_paragraph[4:], level=3)
                elif clean_paragraph.startswith('#### '):
                    doc.add_heading(clean_paragraph[5:], level=4)
                elif clean_paragraph.startswith('##### '):
                    doc.add_heading(clean_paragraph[6:], level=5)
                elif clean_paragraph.startswith('###### '):
                    doc.add_heading(clean_paragraph[7:], level=6)
                # Check if it's a list item
                elif clean_paragraph.startswith('- ') or clean_paragraph.startswith('* ') or clean_paragraph.startswith('+ '):
                    doc.add_paragraph(clean_paragraph[2:], style='List Bullet')
                elif clean_paragraph[0].isdigit() and clean_paragraph[1] == '.' and clean_paragraph[2] == ' ':
                    doc.add_paragraph(clean_paragraph[3:], style='List Number')
                # Regular paragraph
                else:
                    doc.add_paragraph(clean_paragraph)
        
        # Save to bytes
        docx_io = io.BytesIO()
        doc.save(docx_io)
        docx_io.seek(0)
        
        return docx_io.getvalue()
    
    def export(self, markdown_text: str, format_type: str, filename: Optional[str] = None) -> bytes:
        """

        Main export method

        Returns file bytes based on format type

        """
        format_type = format_type.lower()
        
        if format_type == 'pdf':
            return self.to_pdf(markdown_text, filename)
        elif format_type == 'docx':
            return self.to_docx(markdown_text, filename)
        elif format_type == 'html':
            return self.to_html(markdown_text).encode('utf-8')
        elif format_type == 'txt':
            return markdown_text.encode('utf-8')
        else:
            raise ValueError(f"Unsupported format: {format_type}. Use: pdf, docx, html, txt")


# Create global instance
export_pipeline = ExportPipeline()