File size: 7,228 Bytes
eabce02 | 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 | """Export utilities for research reports"""
import os
import tempfile
from typing import Optional
from datetime import datetime
import markdown
from weasyprint import HTML, CSS
from docx import Document
from docx.shared import Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
import base64
import io
class ReportExporter:
"""Handles exporting research reports to different formats"""
def __init__(self):
self.temp_dir = tempfile.gettempdir()
def export_markdown(self, content: str, query: str, metadata: dict = None) -> tuple[str, str]:
"""Export report as markdown file"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"research_report_{timestamp}.md"
# Add metadata header if provided
if metadata:
header = self._create_metadata_header(query, metadata)
content = f"{header}\n\n{content}"
filepath = os.path.join(self.temp_dir, filename)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
return filepath, filename
def export_pdf(self, content: str, query: str, metadata: dict = None) -> tuple[str, str]:
"""Export report as PDF file"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"research_report_{timestamp}.pdf"
# Convert markdown to HTML
html_content = self._markdown_to_html(content, query, metadata)
# Create PDF
filepath = os.path.join(self.temp_dir, filename)
HTML(string=html_content).write_pdf(filepath, stylesheets=[self._get_pdf_css()])
return filepath, filename
def export_docx(self, content: str, query: str, metadata: dict = None) -> tuple[str, str]:
"""Export report as Word document"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"research_report_{timestamp}.docx"
doc = Document()
# Add title
title = doc.add_heading(f"Research Report: {query}", 0)
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
# Add metadata if provided
if metadata:
doc.add_heading("Report Information", level=2)
for key, value in metadata.items():
doc.add_paragraph(f"{key}: {value}")
doc.add_page_break()
# Parse markdown content and add to document
self._add_markdown_to_docx(doc, content)
filepath = os.path.join(self.temp_dir, filename)
doc.save(filepath)
return filepath, filename
def _create_metadata_header(self, query: str, metadata: dict) -> str:
"""Create metadata header for markdown"""
header = f"# Research Report: {query}\n\n"
header += "## Report Information\n\n"
for key, value in metadata.items():
header += f"- **{key}**: {value}\n"
header += "\n---\n"
return header
def _markdown_to_html(self, content: str, query: str, metadata: dict = None) -> str:
"""Convert markdown content to HTML"""
if metadata:
header = self._create_metadata_header(query, metadata)
content = f"{header}\n\n{content}"
html_content = markdown.markdown(content, extensions=['tables', 'fenced_code'])
# Wrap in full HTML document
return f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Research Report: {query}</title>
</head>
<body>
{html_content}
</body>
</html>
"""
def _get_pdf_css(self) -> CSS:
"""Get CSS styling for PDF export"""
css_content = """
@page {
margin: 1in;
size: letter;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
line-height: 1.6;
color: #333;
max-width: none;
}
h1, h2, h3, h4, h5, h6 {
color: #2c3e50;
margin-top: 1.5em;
margin-bottom: 0.5em;
}
h1 {
border-bottom: 2px solid #3498db;
padding-bottom: 0.3em;
}
h2 {
border-bottom: 1px solid #bdc3c7;
padding-bottom: 0.2em;
}
code {
background-color: #f8f9fa;
padding: 0.2em 0.4em;
border-radius: 3px;
font-family: 'Courier New', monospace;
}
pre {
background-color: #f8f9fa;
padding: 1em;
border-radius: 5px;
overflow-x: auto;
}
blockquote {
border-left: 4px solid #3498db;
margin: 1em 0;
padding-left: 1em;
color: #7f8c8d;
}
table {
border-collapse: collapse;
width: 100%;
margin: 1em 0;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
"""
return CSS(string=css_content)
def _add_markdown_to_docx(self, doc, content: str):
"""Add markdown content to Word document (simplified parsing)"""
lines = content.split('\n')
current_list = None
for line in lines:
line = line.strip()
if not line:
continue
# Headers
if line.startswith('#'):
level = len(line) - len(line.lstrip('#'))
text = line.lstrip('# ')
doc.add_heading(text, level=min(level, 3))
# Lists
elif line.startswith('- ') or line.startswith('* '):
text = line[2:]
doc.add_paragraph(text, style='List Bullet')
elif line.startswith(('1. ', '2. ', '3. ', '4. ', '5. ', '6. ', '7. ', '8. ', '9. ')):
text = line[3:] if line[1] == '.' else line[4:]
doc.add_paragraph(text, style='List Number')
# Regular paragraphs
else:
doc.add_paragraph(line)
def get_file_download_link(filepath: str, filename: str) -> str:
"""Create a download link for a file"""
with open(filepath, 'rb') as f:
file_data = f.read()
b64_data = base64.b64encode(file_data).decode()
# Determine MIME type
if filename.endswith('.pdf'):
mime_type = 'application/pdf'
elif filename.endswith('.docx'):
mime_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
else:
mime_type = 'text/markdown'
return f"data:{mime_type};base64,{b64_data}"
|