Spaces:
Sleeping
Sleeping
Download export_pipeline.py from devilseye2004/tester: direct link, hf CLI and curl.
- Browser
- Download file 8.07 kB
-
https://huggingface.co/spaces/devilseye2004/tester/resolve/main/export_pipeline.py
- Command line
-
hf download hf://spaces/devilseye2004/tester/export_pipeline.py
-
curl -L -o export_pipeline.py https://huggingface.co/spaces/devilseye2004/tester/resolve/main/export_pipeline.py
8.07 kB
| """ | |
| 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() |