Handles table tags.
(self, element: Tag, idx: int, doc: DoclingDocument)
| 305 | _log.warn("list-item has no text: ", element) |
| 306 | |
| 307 | def handle_table(self, element: Tag, idx: int, doc: DoclingDocument): |
| 308 | """Handles table tags.""" |
| 309 | |
| 310 | nested_tables = element.find("table") |
| 311 | if nested_tables is not None: |
| 312 | _log.warn("detected nested tables: skipping for now") |
| 313 | return |
| 314 | |
| 315 | # Count the number of rows (number of <tr> elements) |
| 316 | num_rows = len(element.find_all("tr")) |
| 317 | |
| 318 | # Find the number of columns (taking into account colspan) |
| 319 | num_cols = 0 |
| 320 | for row in element.find_all("tr"): |
| 321 | col_count = 0 |
| 322 | for cell in row.find_all(["td", "th"]): |
| 323 | colspan = int(cell.get("colspan", 1)) |
| 324 | col_count += colspan |
| 325 | num_cols = max(num_cols, col_count) |
| 326 | |
| 327 | grid = [[None for _ in range(num_cols)] for _ in range(num_rows)] |
| 328 | |
| 329 | data = TableData(num_rows=num_rows, num_cols=num_cols, table_cells=[]) |
| 330 | |
| 331 | # Iterate over the rows in the table |
| 332 | for row_idx, row in enumerate(element.find_all("tr")): |
| 333 | |
| 334 | # For each row, find all the column cells (both <td> and <th>) |
| 335 | cells = row.find_all(["td", "th"]) |
| 336 | |
| 337 | # Check if each cell in the row is a header -> means it is a column header |
| 338 | col_header = True |
| 339 | for j, html_cell in enumerate(cells): |
| 340 | if html_cell.name == "td": |
| 341 | col_header = False |
| 342 | |
| 343 | col_idx = 0 |
| 344 | # Extract and print the text content of each cell |
| 345 | for _, html_cell in enumerate(cells): |
| 346 | |
| 347 | text = html_cell.text |
| 348 | try: |
| 349 | text = self.extract_table_cell_text(html_cell) |
| 350 | except Exception as exc: |
| 351 | _log.warn("exception: ", exc) |
| 352 | exit(-1) |
| 353 | |
| 354 | # label = html_cell.name |
| 355 | |
| 356 | col_span = int(html_cell.get("colspan", 1)) |
| 357 | row_span = int(html_cell.get("rowspan", 1)) |
| 358 | |
| 359 | while grid[row_idx][col_idx] is not None: |
| 360 | col_idx += 1 |
| 361 | for r in range(row_span): |
| 362 | for c in range(col_span): |
| 363 | grid[row_idx + r][col_idx + c] = text |
| 364 |
no test coverage detected