Deep_research_assistant / export_utils.py
DakshGoyal1506's picture
Upload 13 files
eabce02 verified
Raw History Blame Contribute Delete
7.23 kB
"""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}"