generate_classes_json.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. #!/usr/bin/env python3
  2. import logging
  3. from argparse import ArgumentParser
  4. import json
  5. from pydantic import TypeAdapter
  6. from parse import (
  7. extract_data_from_class_pdf,
  8. get_modules_for_class_json,
  9. get_modules_json,
  10. get_classes,
  11. deduplicate_modules,
  12. ClassPdfExtractionPageData,
  13. ClassJsonModule,
  14. )
  15. from config import CLASS_TIMETABLE_PDF_INPUT_FILE, CLASSES_JSON_OUTPUT_FILE
  16. def get_valid_lecturers(file_path: str) -> list[str]:
  17. """
  18. Reads the lecturers JSON file and extracts a list of valid lecturer shorthands.
  19. """
  20. valid_lecturers: list[str] = []
  21. try:
  22. logging.warning("reading lecturers file: '%s'", file_path)
  23. with open(file_path, "r", encoding="utf-8") as f:
  24. data = json.load(f)
  25. if isinstance(data, list):
  26. for entry in data:
  27. if isinstance(entry, dict) and "short" in entry:
  28. valid_lecturers.append(entry["short"])
  29. logging.info(
  30. "Loaded %d valid lecturers from %s", len(valid_lecturers), file_path
  31. )
  32. except Exception as e:
  33. logging.error("Failed to load valid lecturers from '%s': %s", file_path, e)
  34. return valid_lecturers
  35. def main() -> None:
  36. parser = ArgumentParser(description="Parse Class Timetable PDF to JSON.")
  37. parser.add_argument(
  38. "-l",
  39. "--lecturers",
  40. help="Path to the lecturers.json file (Optional)",
  41. default=None,
  42. )
  43. parser.add_argument(
  44. "-i",
  45. "--input",
  46. help="Path to the input Class Timetable PDF file",
  47. default=CLASS_TIMETABLE_PDF_INPUT_FILE,
  48. )
  49. parser.add_argument(
  50. "-o",
  51. "--output",
  52. help="Path to the output JSON file",
  53. default=CLASSES_JSON_OUTPUT_FILE,
  54. )
  55. parser.add_argument(
  56. "--save-intermediate",
  57. help="Path to save the intermediate extraction data (JSON format) and exit",
  58. default=None,
  59. )
  60. parser.add_argument(
  61. "--load-intermediate",
  62. help="Path to load the intermediate extraction data from (JSON format) and skip extraction",
  63. default=None,
  64. )
  65. parser.add_argument(
  66. "-j",
  67. "--jobs",
  68. help="Number of parallel jobs to use for extraction (default: 1)",
  69. type=int,
  70. default=1,
  71. )
  72. args = parser.parse_args()
  73. lecturers_file = args.lecturers
  74. logging.basicConfig(level=logging.INFO)
  75. valid_lecturer_shorthands: list[str] | None = None
  76. if lecturers_file:
  77. valid_lecturer_shorthands = get_valid_lecturers(lecturers_file)
  78. extraction_data: list[ClassPdfExtractionPageData]
  79. if args.load_intermediate:
  80. logging.info("Loading intermediate data from %s", args.load_intermediate)
  81. with open(args.load_intermediate, "r", encoding="utf-8") as f:
  82. extraction_data = TypeAdapter(
  83. list[ClassPdfExtractionPageData]
  84. ).validate_json(f.read())
  85. else:
  86. extraction_data = extract_data_from_class_pdf(args.input, num_of_jobs=args.jobs)
  87. if args.save_intermediate:
  88. logging.info("Saving intermediate data to %s", args.save_intermediate)
  89. with open(args.save_intermediate, "w", encoding="utf-8") as f:
  90. f.write(
  91. TypeAdapter(list[ClassPdfExtractionPageData])
  92. .dump_json(extraction_data)
  93. .decode("utf-8")
  94. )
  95. return
  96. parsed_modules: list[ClassJsonModule] = [
  97. module
  98. for data in extraction_data
  99. for module in get_modules_for_class_json(
  100. data.raw_extracted_modules,
  101. data.page_metadata.class_name,
  102. data.page_metadata.degree_program,
  103. get_classes(extraction_data),
  104. valid_lecturer_shorthands,
  105. )
  106. ]
  107. parsed_modules = deduplicate_modules(parsed_modules)
  108. json_output: str = get_modules_json(parsed_modules)
  109. with open(args.output, "w", encoding="utf-8") as f:
  110. f.write(json_output)
  111. if __name__ == "__main__":
  112. main()