generate_pdfs.py 7.6 KB

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