pdf_generator.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. from datetime import datetime
  2. from io import BytesIO
  3. from pathlib import Path
  4. from typing import Dict, Any, List
  5. from markdown import markdown
  6. import site
  7. from fpdf import FPDF
  8. from open_webui.env import STATIC_DIR, FONTS_DIR
  9. from open_webui.models.chats import ChatTitleMessagesForm
  10. class PDFGenerator:
  11. """
  12. Description:
  13. The `PDFGenerator` class is designed to create PDF documents from chat messages.
  14. The process involves transforming markdown content into HTML and then into a PDF format
  15. Attributes:
  16. - `form_data`: An instance of `ChatTitleMessagesForm` containing title and messages.
  17. """
  18. def __init__(self, form_data: ChatTitleMessagesForm):
  19. self.html_body = None
  20. self.messages_html = None
  21. self.form_data = form_data
  22. self.css = Path(STATIC_DIR / "assets" / "pdf-style.css").read_text()
  23. def format_timestamp(self, timestamp: float) -> str:
  24. """Convert a UNIX timestamp to a formatted date string."""
  25. try:
  26. date_time = datetime.fromtimestamp(timestamp)
  27. return date_time.strftime("%Y-%m-%d, %H:%M:%S")
  28. except (ValueError, TypeError) as e:
  29. # Log the error if necessary
  30. return ""
  31. def _build_html_message(self, message: Dict[str, Any]) -> str:
  32. """Build HTML for a single message."""
  33. role = message.get("role", "user")
  34. content = message.get("content", "")
  35. timestamp = message.get("timestamp")
  36. model = message.get("model") if role == "assistant" else ""
  37. date_str = self.format_timestamp(timestamp) if timestamp else ""
  38. # extends pymdownx extension to convert markdown to html.
  39. # - https://facelessuser.github.io/pymdown-extensions/usage_notes/
  40. # html_content = markdown(content, extensions=["pymdownx.extra"])
  41. content = content.replace("\n", "<br/>")
  42. html_message = f"""
  43. <div>
  44. <div>
  45. <h4>
  46. <strong>{role.title()}</strong>
  47. <span style="font-size: 12px;">{model}</span>
  48. </h4>
  49. <div> {date_str} </div>
  50. </div>
  51. <br/>
  52. <br/>
  53. <div>
  54. {content}
  55. </div>
  56. </div>
  57. <br/>
  58. """
  59. return html_message
  60. def _generate_html_body(self) -> str:
  61. """Generate the full HTML body for the PDF."""
  62. return f"""
  63. <html>
  64. <head>
  65. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  66. </head>
  67. <body>
  68. <div>
  69. <div>
  70. <h2>{self.form_data.title}</h2>
  71. {self.messages_html}
  72. </div>
  73. </div>
  74. </body>
  75. </html>
  76. """
  77. def generate_chat_pdf(self) -> bytes:
  78. """
  79. Generate a PDF from chat messages.
  80. """
  81. try:
  82. global FONTS_DIR
  83. pdf = FPDF()
  84. pdf.add_page()
  85. # When running using `pip install` the static directory is in the site packages.
  86. if not FONTS_DIR.exists():
  87. FONTS_DIR = Path(site.getsitepackages()[0]) / "static/fonts"
  88. # When running using `pip install -e .` the static directory is in the site packages.
  89. # This path only works if `open-webui serve` is run from the root of this project.
  90. if not FONTS_DIR.exists():
  91. FONTS_DIR = Path("./backend/static/fonts")
  92. pdf.add_font("NotoSans", "", f"{FONTS_DIR}/NotoSans-Regular.ttf")
  93. pdf.add_font("NotoSans", "b", f"{FONTS_DIR}/NotoSans-Bold.ttf")
  94. pdf.add_font("NotoSans", "i", f"{FONTS_DIR}/NotoSans-Italic.ttf")
  95. pdf.add_font("NotoSansKR", "", f"{FONTS_DIR}/NotoSansKR-Regular.ttf")
  96. pdf.add_font("NotoSansJP", "", f"{FONTS_DIR}/NotoSansJP-Regular.ttf")
  97. pdf.add_font("NotoSansSC", "", f"{FONTS_DIR}/NotoSansSC-Regular.ttf")
  98. pdf.add_font("Twemoji", "", f"{FONTS_DIR}/Twemoji.ttf")
  99. pdf.set_font("NotoSans", size=12)
  100. pdf.set_fallback_fonts(
  101. ["NotoSansKR", "NotoSansJP", "NotoSansSC", "Twemoji"]
  102. )
  103. pdf.set_auto_page_break(auto=True, margin=15)
  104. # Build HTML messages
  105. messages_html_list: List[str] = [
  106. self._build_html_message(msg) for msg in self.form_data.messages
  107. ]
  108. self.messages_html = "<div>" + "".join(messages_html_list) + "</div>"
  109. # Generate full HTML body
  110. self.html_body = self._generate_html_body()
  111. pdf.write_html(self.html_body)
  112. # Save the pdf with name .pdf
  113. pdf_bytes = pdf.output()
  114. return bytes(pdf_bytes)
  115. except Exception as e:
  116. raise e