Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 34 additions & 35 deletions backend/utils.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
import aiofiles
import os
import re
import urllib
import uuid
from md2pdf.core import md2pdf
import mistune
from docx import Document
from htmldocx import HtmlToDocx

def sanitize_filename(filename: str) -> str:
"""Sanitize filename to prevent directory traversal and remove invalid characters."""
base = os.path.basename(filename)
sanitized = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', base)
sanitized = re.sub(r'\.+', '.', sanitized).strip('._-')
return sanitized or f"report_{uuid.uuid4().hex[:8]}"

async def write_to_file(filename: str, text: str) -> None:
"""Asynchronously write text to a file in UTF-8 encoding.
"""Asynchronously write text to a file in UTF-8 encoding ensuring directory exists.

Args:
filename (str): The filename to write to.
text (str): The text to write.
"""
# Convert text to UTF-8, replacing any problematic characters
dirname = os.path.dirname(filename)
if dirname:
os.makedirs(dirname, exist_ok=True)
text_utf8 = text.encode('utf-8', errors='replace').decode('utf-8')

async with aiofiles.open(filename, "w", encoding='utf-8') as file:
Expand All @@ -24,32 +31,31 @@ async def write_text_to_md(text: str, filename: str = "") -> str:

Args:
text (str): Text to write to the Markdown file.
filename (str): Base file name.

Returns:
str: The file path of the generated Markdown file.
"""
file_path = f"outputs/{filename}.md"
safe_name = sanitize_filename(filename) if filename else f"report_{uuid.uuid4().hex[:8]}"
file_path = f"outputs/{safe_name}.md"
await write_to_file(file_path, text)
return file_path

async def write_md_to_pdf(text: str, filename: str = "") -> str:
"""Converts Markdown text to a PDF file and returns the file path.

Args:
text (str): Markdown text to convert.

Returns:
str: The encoded file path of the generated PDF.
"""
file_path = f"outputs/{filename}.pdf"
"""Converts Markdown text to a PDF file and returns the file path."""
safe_name = sanitize_filename(filename) if filename else f"report_{uuid.uuid4().hex[:8]}"
file_path = f"outputs/{safe_name}.pdf"

try:
from md2pdf.core import md2pdf
dirname = os.path.dirname(file_path)
if dirname:
os.makedirs(dirname, exist_ok=True)
md2pdf(file_path,
md_content=text,
#md_file_path=f"{file_path}.md",
css_file_path="./frontend/pdf_styles.css",
base_url=None)
print(f"Report written to {file_path}.pdf")
print(f"Report written to {file_path}")
except Exception as e:
print(f"Error in converting Markdown to PDF: {e}")
return ""
Expand All @@ -58,32 +64,25 @@ async def write_md_to_pdf(text: str, filename: str = "") -> str:
return encoded_file_path

async def write_md_to_word(text: str, filename: str = "") -> str:
"""Converts Markdown text to a DOCX file and returns the file path.

Args:
text (str): Markdown text to convert.

Returns:
str: The encoded file path of the generated DOCX.
"""
file_path = f"outputs/{filename}.docx"
"""Converts Markdown text to a DOCX file and returns the file path."""
safe_name = sanitize_filename(filename) if filename else f"report_{uuid.uuid4().hex[:8]}"
file_path = f"outputs/{safe_name}.docx"

try:
# Convert report markdown to HTML
import mistune
from docx import Document
from htmldocx import HtmlToDocx

dirname = os.path.dirname(file_path)
if dirname:
os.makedirs(dirname, exist_ok=True)
html = mistune.html(text)
# Create a document object
doc = Document()
# Convert the html generated from the report to document format
HtmlToDocx().add_html_to_document(html, doc)

# Saving the docx document to file_path
doc.save(file_path)

print(f"Report written to {file_path}")

encoded_file_path = urllib.parse.quote(file_path)
return encoded_file_path

except Exception as e:
print(f"Error in converting Markdown to DOCX: {e}")
return ""
23 changes: 23 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import os
import pytest
from backend.utils import sanitize_filename, write_to_file, write_text_to_md


def test_sanitize_filename_traversal():
"""Verify directory traversal tokens are stripped to safe basename."""
assert sanitize_filename("../../../etc/passwd") == "passwd"
assert sanitize_filename("test file (1) & 2.md") == "test_file_1_2.md" or "test_file" in sanitize_filename("test file (1) & 2.md")
assert len(sanitize_filename("")) > 0


@pytest.mark.asyncio
async def test_write_to_file_and_markdown(tmp_path):
"""Verify asynchronous file writer creates directories and files cleanly."""
target = tmp_path / "nested" / "test_report.md"
content = "# Financial Summary\n\n- Revenue: $10M"
await write_to_file(str(target), content)

assert os.path.exists(str(target))
with open(str(target), "r", encoding="utf-8") as f:
read_back = f.read()
assert read_back == content
Loading