generate_pdfs.py 7.6 KB

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