1
0

generate_pdfs.py 7.5 KB

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