table_extraction.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. import logging
  2. from pdfplumber.page import Page
  3. import pdfplumber
  4. from config import CLASS_PDF_TABLE_SETTINGS, ALLOWED_TIMESLOTS
  5. from .models import (
  6. Weekday,
  7. TimeSlot,
  8. YLevel,
  9. RawExtractedModule,
  10. UnmergedTimeEntries,
  11. Area,
  12. HorizontalLine,
  13. ClassPdfExtractionPageData,
  14. PageMetadata,
  15. )
  16. from .above_table_text import parse_above_table_text
  17. from .geometry import (
  18. get_timeslot_for_area,
  19. is_line_at_bottom,
  20. is_area_below,
  21. is_vertical_match,
  22. )
  23. from .img import is_mostly_white_area
  24. allowed_time_slots: list[TimeSlot] = [
  25. TimeSlot(*timeslot_tuple) for timeslot_tuple in ALLOWED_TIMESLOTS
  26. ]
  27. def get_weekday_from_text(text: str) -> Weekday | None:
  28. """
  29. Helper function that tries to get a Weekday from a string.
  30. Only accepts exact display name matches.
  31. """
  32. for weekday in Weekday:
  33. if weekday.display_name == text:
  34. return weekday
  35. return None
  36. def get_modules_from_weekday(
  37. weekday: Weekday,
  38. unmerged_time_entries: UnmergedTimeEntries,
  39. page: Page,
  40. timeslot_y_levels: dict[TimeSlot, YLevel],
  41. page_number: int,
  42. ) -> list[RawExtractedModule]:
  43. """
  44. Extracts the modules (raw text and start/end) of a weekday on a single pdf page
  45. """
  46. highest_y_level = timeslot_y_levels[allowed_time_slots[-1]].y2
  47. modules = []
  48. while len(unmerged_time_entries.cells) > 0:
  49. area = unmerged_time_entries.cells.pop(0)
  50. if is_mostly_white_area(page, area):
  51. logging.debug("mostly white cell skipped")
  52. continue
  53. timeslot = get_timeslot_for_area(area, timeslot_y_levels)
  54. if timeslot is None:
  55. raise RuntimeError("Could not match TimeSlot to Cell Area")
  56. start_seconds = timeslot.start_seconds()
  57. line_at_bottom_found = False
  58. while not line_at_bottom_found:
  59. logging.debug("searching for line at bottom of: %s", area)
  60. logging.debug("line candidates:")
  61. for line in unmerged_time_entries.horizontal_lines:
  62. logging.debug("testing horizontal line: %s", line)
  63. if is_line_at_bottom(area, line, tolerance=20):
  64. line_at_bottom_found = True
  65. logging.debug("candidate line found")
  66. break
  67. else:
  68. if is_vertical_match(area.y2, highest_y_level):
  69. logging.debug("highest y level matched")
  70. break
  71. found_matching_next_cell_index = -1
  72. for index, potential_cell_below in enumerate(
  73. unmerged_time_entries.cells
  74. ):
  75. if is_area_below(potential_cell_below, area):
  76. found_matching_next_cell_index = index
  77. break
  78. else:
  79. raise RuntimeError(
  80. f"No matching cell below found to merge with on {weekday}"
  81. )
  82. logging.debug("vertically merging cells for %s", weekday)
  83. matched_area = unmerged_time_entries.cells.pop(
  84. found_matching_next_cell_index
  85. )
  86. logging.debug("matched cell area: %s", matched_area)
  87. area = Area(area.x1, area.y1, matched_area.x2, matched_area.y2)
  88. text = page.crop((area.x1, area.y1, area.x2, area.y2)).extract_text()
  89. timeslot = get_timeslot_for_area(area, timeslot_y_levels)
  90. if timeslot is None:
  91. raise RuntimeError("Could not match TimeSlot to Cell Area")
  92. end_seconds = timeslot.end_seconds()
  93. modules.append(
  94. RawExtractedModule(weekday, start_seconds, end_seconds, text, page_number)
  95. )
  96. return modules
  97. def extract_data_from_class_pdf(
  98. input_filename: str, lecturers_file=None
  99. ) -> list[ClassPdfExtractionPageData]:
  100. """
  101. Extracts all data from class timetable pdf's
  102. """
  103. extraction_data: list[ClassPdfExtractionPageData] = []
  104. previous_page_metadata: list[PageMetadata] = []
  105. unmerged_time_entries_by_weekday: dict[Weekday, UnmergedTimeEntries] = {}
  106. with pdfplumber.open(input_filename) as pdf:
  107. for page_index, page in enumerate(pdf.pages):
  108. weekday_areas: dict[Weekday, Area] = {}
  109. timeslot_y_levels: dict[TimeSlot, YLevel] = {}
  110. for day in Weekday:
  111. weekday_areas[day] = Area(0, 0, 0, 0)
  112. found_tables = page.find_tables(CLASS_PDF_TABLE_SETTINGS)
  113. logging.debug(
  114. "amount of tables found on page %d: %d",
  115. page_index + 1,
  116. len(found_tables),
  117. )
  118. table = found_tables[0]
  119. table_y1 = table.bbox[1]
  120. text_above_table = get_above_table_text(page, table_y1)
  121. empty_start_found = False
  122. # get weekday and timeslot areas
  123. expected_timeslot_index = 0
  124. for row_index, row in enumerate(table.rows):
  125. if row_index == 0:
  126. for column_index, cell in enumerate(row.cells):
  127. logging.debug("row: %d, col: %d", row_index, column_index)
  128. logging.debug(cell)
  129. if cell is None:
  130. logging.debug("None Table Cell Found")
  131. else:
  132. cell_text = page.crop(
  133. (cell[0], cell[1], cell[2], cell[3])
  134. ).extract_text()
  135. if not empty_start_found and len(cell_text) == 0:
  136. logging.debug("empty start found")
  137. empty_start_found = True
  138. weekday_enum = get_weekday_from_text(cell_text)
  139. if weekday_enum:
  140. logging.debug("Weekday %s found", cell_text)
  141. weekday_areas[weekday_enum] = Area(
  142. cell[0], cell[3], cell[2], 0
  143. )
  144. else:
  145. logging.debug("row: %d, col: %d", row_index, 0)
  146. cell = row.cells[0]
  147. if cell is None:
  148. logging.warning("Unexpected None Table Cell Found")
  149. else:
  150. cell_text = page.crop(
  151. (cell[0], cell[1], cell[2], cell[3])
  152. ).extract_text()
  153. target_timeslot = allowed_time_slots[expected_timeslot_index]
  154. if not (
  155. target_timeslot.start_time in cell_text
  156. and target_timeslot.end_time in cell_text
  157. ):
  158. logging.warning(
  159. "Unexpected Timeslot found: '%s'", cell_text
  160. )
  161. else:
  162. # assumes this is the last timeslot ever
  163. if target_timeslot == TimeSlot("20:30", "21:15"):
  164. for weekday in Weekday:
  165. new_area = Area(
  166. weekday_areas[weekday].x1,
  167. weekday_areas[weekday].y1,
  168. weekday_areas[weekday].x2,
  169. cell[3],
  170. )
  171. weekday_areas[weekday] = new_area
  172. timeslot_y_levels[target_timeslot] = YLevel(
  173. cell[1], cell[3]
  174. )
  175. expected_timeslot_index += 1
  176. for weekday in Weekday:
  177. unmerged_time_entries_by_weekday[weekday] = UnmergedTimeEntries([], [])
  178. target_area = weekday_areas[weekday]
  179. logging.debug("target_area: %s", target_area)
  180. for row_index, row in enumerate(table.rows):
  181. for column_index, cell in enumerate(row.cells):
  182. if cell is None:
  183. logging.debug("None table cell found")
  184. continue
  185. logging.debug("row: %d, col: %d", row_index, column_index)
  186. logging.debug("cell: %s", cell)
  187. if (
  188. target_area.x1 <= cell[0]
  189. and target_area.y1 <= cell[1]
  190. and target_area.x2 >= cell[2]
  191. and target_area.y2 >= cell[3]
  192. ):
  193. cell_dimensions = cell[0], cell[1], cell[2], cell[3]
  194. unmerged_time_entries_by_weekday[weekday].cells.append(
  195. Area(*cell_dimensions)
  196. )
  197. logging.debug("%s cell found", weekday)
  198. for line_found in page.lines:
  199. line_x1 = line_found["x0"]
  200. line_x2 = line_found["x1"]
  201. line_y1 = line_found["y0"]
  202. line_y2 = line_found["y1"]
  203. line_bottom = line_found["bottom"]
  204. # ignore non horizontal lines
  205. if line_y1 != line_y2:
  206. continue
  207. if target_area.x1 <= line_x1 and target_area.x2 >= line_x2:
  208. logging.debug("%s timeslot seperator line found", weekday)
  209. unmerged_time_entries_by_weekday[
  210. weekday
  211. ].horizontal_lines.append(
  212. HorizontalLine(line_x1, line_x2, line_bottom)
  213. )
  214. all_modules: list[RawExtractedModule] = []
  215. for weekday in Weekday:
  216. all_modules.extend(
  217. get_modules_from_weekday(
  218. weekday,
  219. unmerged_time_entries_by_weekday[weekday],
  220. page,
  221. timeslot_y_levels,
  222. page_index + 1,
  223. )
  224. )
  225. page_metadata = parse_above_table_text(
  226. text_above_table, previous_page_metadata
  227. )
  228. previous_page_metadata.append(page_metadata)
  229. extraction_data.append(
  230. ClassPdfExtractionPageData(all_modules, page_metadata)
  231. )
  232. return extraction_data
  233. def get_above_table_text(page: Page, table_y1: float) -> str:
  234. """
  235. Get the text above the timetable for metadata parsing
  236. """
  237. upper_region = page.crop((0, 0, page.width, table_y1))
  238. text_above_table = upper_region.extract_text()
  239. logging.debug("Text found above the table:")
  240. logging.debug(text_above_table)
  241. return text_above_table