generate_pdfs.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. #ident "@(#)$Format:LocalFoodAI_lanfr144:generate_pdfs.py:%an:%ae:%ad:%cn:%ce:%cd:%H:%D:%N$"
  2. import os
  3. import glob
  4. import re
  5. from markdown_pdf import MarkdownPdf
  6. from markdown_pdf import Section
  7. def main():
  8. docs_dir = os.path.join(os.path.dirname(__file__), '..', 'docs')
  9. md_files = glob.glob(os.path.join(docs_dir, '*.md'))
  10. if not md_files:
  11. print("No markdown files found in docs/")
  12. return
  13. # Use relative paths for fonts to ensure portability of PDF generation
  14. root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')).replace('\\', '/')
  15. user_css = """
  16. * {
  17. color: #1a1a1a !important;
  18. }
  19. body {
  20. font-family: 'Helvetica', 'Arial', sans-serif !important;
  21. color: #1a1a1a !important;
  22. background-color: #ffffff !important;
  23. }
  24. h1, h2, h3, h4, h5, h6, h1 *, h2 *, h3 *, h4 *, h5 *, h6 * {
  25. color: #000000 !important;
  26. }
  27. pre {
  28. background-color: #212529 !important;
  29. border: 1px solid #343a40 !important;
  30. padding: 2px !important;
  31. border-radius: 3px !important;
  32. font-family: 'Courier New', 'Courier', monospace !important;
  33. font-size: 10pt !important;
  34. white-space: pre-wrap !important;
  35. word-break: break-all !important;
  36. }
  37. pre code, pre * {
  38. font-family: 'Courier New', 'Courier', monospace !important;
  39. font-size: 10pt !important;
  40. color: #f8f9fa !important;
  41. background-color: #212529 !important;
  42. white-space: pre-wrap !important;
  43. word-break: break-all !important;
  44. }
  45. code {
  46. font-family: 'Courier New', 'Courier', monospace !important;
  47. font-size: 10pt !important;
  48. color: #b02a37 !important;
  49. background-color: #f8f9fa !important;
  50. padding: 2px 4px !important;
  51. border-radius: 3px !important;
  52. white-space: pre-wrap !important;
  53. word-break: break-all !important;
  54. }
  55. a, a * {
  56. color: #0d6efd !important;
  57. }
  58. blockquote, blockquote * {
  59. color: #555555 !important;
  60. border-left: 4px solid #ccc !important;
  61. padding-left: 10px !important;
  62. }
  63. table, tr, td, th, table * {
  64. color: #1a1a1a !important;
  65. border-color: #cccccc !important;
  66. }
  67. th {
  68. background-color: #f2f2f2 !important;
  69. }
  70. ul, li {
  71. list-style-type: disc !important;
  72. }
  73. """
  74. for md_file in md_files:
  75. pdf_file = md_file.replace('.md', '.pdf')
  76. print(f"Converting {os.path.basename(md_file)} to PDF...")
  77. with open(md_file, 'r', encoding='utf-8') as f:
  78. md_content = f.read()
  79. import subprocess
  80. def sanitize_name(name):
  81. if not name:
  82. return "Francois Lange"
  83. name_lower = name.lower()
  84. if "fran" in name_lower or "lange" in name_lower or "lanfr" in name_lower:
  85. return "Francois Lange"
  86. return name
  87. def get_git_info_for_file(file_path):
  88. try:
  89. cmd = [
  90. "git", "log", "-1",
  91. "--date=format:%Y/%m/%d %H:%M:%S",
  92. "--format=%an|%ae|%ad|%cn|%ce|%cd|%H|%D|%N",
  93. "--", file_path
  94. ]
  95. out = subprocess.check_output(cmd, stderr=subprocess.DEVNULL).decode('utf-8', errors='ignore').strip()
  96. if out:
  97. parts = out.split('|')
  98. if len(parts) == 9:
  99. parts[0] = sanitize_name(parts[0])
  100. parts[3] = sanitize_name(parts[3])
  101. return parts
  102. except Exception:
  103. pass
  104. author_name = "Francois Lange"
  105. try:
  106. author_email = subprocess.check_output(["git", "config", "user.email"], stderr=subprocess.DEVNULL).decode('utf-8', errors='ignore').strip() or "lanfr144@school.lu"
  107. except Exception:
  108. author_email = "lanfr144@school.lu"
  109. from datetime import datetime
  110. now_str = datetime.now().strftime("%Y/%m/%d %H:%M:%S")
  111. return [author_name, author_email, now_str, author_name, author_email, now_str, "Not Committed Yet", "local", "none"]
  112. # Dynamic smudging of the Format placeholder for this specific file
  113. base_name = os.path.basename(md_file)
  114. info = get_git_info_for_file(md_file)
  115. replacement = f"$Format:LocalFoodAI_lanfr144:generate_pdfs.py:%an:%ae:%ad:%cn:%ce:%cd:%H:%D:%N$"
  116. # Replace the raw format template if present
  117. pattern = r'\$Format:LocalFoodAI_lanfr144:generate_pdfs.py:%an:%ae:%ad:%cn:%ce:%cd:%H:%D:%N$'
  118. md_content = re.sub(pattern, replacement, md_content)
  119. # Clean up absolute file:/// paths to relative paths
  120. md_content = re.sub(r'file:///.*?/docs/([a-zA-Z0-9_-]+)\.md', r'\1.pdf', md_content, flags=re.IGNORECASE)
  121. md_content = re.sub(r'file:///.*?/Food/([a-zA-Z0-9_.-]+)', r'../\1', md_content, flags=re.IGNORECASE)
  122. # Add <br/> after code blocks to force copy-paste blank line
  123. md_content = re.sub(r'(```[a-zA-Z0-9_-]*\n[\s\S]*?\n```)', r'\1\n<br/>', md_content)
  124. try:
  125. pdf = MarkdownPdf(toc_level=2, optimize=True, plugins={"mermaid": {}})
  126. if base_name == 'project_report.md':
  127. print("Splitting project_report.md into Portrait/Landscape/Portrait sections...")
  128. parts = md_content.split('## 2. Project File Catalog & Documentation')
  129. if len(parts) == 2:
  130. portrait_part1 = parts[0]
  131. remaining = parts[1]
  132. parts2 = remaining.split('## 3. Directory Structure Map')
  133. if len(parts2) == 2:
  134. landscape_part = '## 2. Project File Catalog & Documentation' + parts2[0]
  135. portrait_part2 = '## 3. Directory Structure Map' + parts2[1]
  136. pdf.add_section(Section(portrait_part1, paper_size="A4", root=root_dir), user_css=user_css)
  137. pdf.add_section(Section(landscape_part, paper_size="A4-L", root=root_dir), user_css=user_css)
  138. pdf.add_section(Section(portrait_part2, paper_size="A4", root=root_dir), user_css=user_css)
  139. else:
  140. print("WARNING: Could not find Directory Structure Map heading. Defaulting to full portrait.")
  141. pdf.add_section(Section(md_content, paper_size="A4", root=root_dir), user_css=user_css)
  142. else:
  143. print("WARNING: Could not find Project File Catalog heading. Defaulting to full portrait.")
  144. pdf.add_section(Section(md_content, paper_size="A4", root=root_dir), user_css=user_css)
  145. else:
  146. pdf.add_section(Section(md_content, paper_size="A4", root=root_dir), user_css=user_css)
  147. pdf.save(pdf_file)
  148. print(f"Saved {os.path.basename(pdf_file)}")
  149. # Copy to workspace root if applicable
  150. import shutil
  151. if base_name == 'project_report.md':
  152. dest = os.path.join(root_dir, 'Project.pdf')
  153. try:
  154. if os.path.exists(dest):
  155. os.remove(dest)
  156. shutil.copy2(pdf_file, dest)
  157. print("Successfully updated root Project.pdf")
  158. except Exception as copy_err:
  159. print(f"WARNING: Could not copy to root Project.pdf: {copy_err}")
  160. elif base_name == 'retro_planning.md':
  161. dest = os.path.join(root_dir, 'Retro Planning.pdf')
  162. try:
  163. if os.path.exists(dest):
  164. os.remove(dest)
  165. shutil.copy2(pdf_file, dest)
  166. print("Successfully updated root Retro Planning.pdf")
  167. except Exception as copy_err:
  168. print(f"WARNING: Could not copy to root Retro Planning.pdf: {copy_err}")
  169. except Exception as e:
  170. print(f"WARNING: Could not save {os.path.basename(pdf_file)}. File might be locked or open in a viewer. Error: {e}")
  171. if __name__ == "__main__":
  172. main()