Commit d4840856 authored by Miguel Angel Reina Ortega's avatar Miguel Angel Reina Ortega
Browse files

Add support to convert HTML tables in markdown to gridtable

parent 7704d538
Loading
Loading
Loading
Loading
Loading
+1
Changes for .gitlab-ci.yml: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -49,6 +49,7 @@ Build generateBaseline docker image:
        - generateBaseline/generateTOC.py
        - generateBaseline/svg2png.py
        - generateBaseline/postprocessing.py
        - generateBaseline/htmlToGridTable.py
        
Build generateSpecWebSite docker image:
  stage: build
+434
Changes for generateBaseline/htmlToGridTable.py: 434 added lines, 0 removed lines.
Original line number Diff line number Diff line
#
#	htmlToGridTable.py
#
#	(c) 2025 by Miguel Angel Reina Ortega
#	License: BSD 3-Clause License. See the LICENSE file for further details.
#
"""Convert HTML tables to Pandoc grid-table markdown.

Unlike gridTableTools (grid table -> HTML for rendering), this module prepares
markdown that can be sent to Pandoc: HTML table -> Pandoc grid table string.
Cell content (including existing markdown) is preserved as-is.
"""

from __future__ import annotations

from typing import Optional, Any

from bs4 import BeautifulSoup, NavigableString, Comment


class _HtmlCell:
	"""Cell used while building a Pandoc grid table from HTML."""

	__slots__ = ('content', 'row', 'col', 'colspan', 'rowspan', 'alignment', 'merged')

	def __init__(self, content: str = '', row: int = 0, col: int = 0,
				 colspan: int = 1, rowspan: int = 1, alignment: str = 'center',
				 merged: bool = False) -> None:
		self.content = content
		self.row = row
		self.col = col
		self.colspan = colspan
		self.rowspan = rowspan
		self.alignment = alignment
		self.merged = merged


def _detectCellAlignment(cell) -> str:
	"""Read column alignment from HTML align attribute or text-align style."""
	align = cell.get('align')
	if align:
		value = align.strip().lower()
		if value in ('left', 'right', 'center'):
			return value

	style = cell.get('style') or ''
	for part in style.split(';'):
		part = part.strip()
		if not part.lower().startswith('text-align'):
			continue
		_, _, value = part.partition(':')
		value = value.strip().lower()
		if value in ('left', 'right', 'center'):
			return value

	return 'center'


def _deriveColumnAlignments(headerRows: list[list[_HtmlCell]], bodyRows: list[list[_HtmlCell]],
							maxCols: int) -> list[str]:
	"""Derive per-column alignment; header cells take precedence over body."""
	alignments = ['center'] * maxCols
	for row in bodyRows:
		for cell in row:
			for c in range(cell.col, cell.col + cell.colspan):
				alignments[c] = cell.alignment
	for row in headerRows:
		for cell in row:
			for c in range(cell.col, cell.col + cell.colspan):
				alignments[c] = cell.alignment
	return alignments


def _extractHtmlCellContent(cell) -> str:
	"""Extract cell text for Pandoc markdown.

	- <br> becomes a line break
	- <a href="...">text</a> becomes [text](url)
	- Whitespace-only lines from HTML formatting are removed
	- Non-empty line content is preserved (markdown syntax kept)
	"""
	parts: list[str] = []

	def walk(node) -> None:
		if isinstance(node, Comment):
			return
		if isinstance(node, NavigableString):
			parts.append(str(node))
			return
		name = getattr(node, 'name', None)
		if name == 'br':
			parts.append('\n')
			return
		if name == 'a':
			href = (node.get('href') or '').strip()
			link_text = node.get_text(separator=' ', strip=True)
			if href and link_text:
				parts.append(f'[{link_text}]({href})')
			elif link_text:
				parts.append(link_text)
			return
		# Inline/other tags: keep inner text without adding block newlines
		for child in getattr(node, 'children', []):
			walk(child)

	for child in cell.children:
		walk(child)

	text = ''.join(parts).replace('\r\n', '\n').replace('\r', '\n')
	lines = [line.strip() for line in text.split('\n')]
	lines = [line for line in lines if line]
	return '\n'.join(lines)


def _extractRowsFromTrs(trs) -> list[list[_HtmlCell]]:
	"""Parse <tr> elements into cells, respecting colspan/rowspan occupancy."""
	occupied: dict[tuple[int, int], bool] = {}
	extracted: list[list[_HtmlCell]] = []

	for rowIdx, tr in enumerate(trs):
		rowCells: list[_HtmlCell] = []
		colIdx = 0
		cells = tr.find_all(['td', 'th'], recursive=False)
		if not cells:
			cells = [c for c in tr.find_all(['td', 'th']) if c.find_parent('tr') is tr]

		for cell in cells:
			while occupied.get((rowIdx, colIdx)):
				colIdx += 1

			colspan = int(cell.get('colspan') or 1)
			rowspan = int(cell.get('rowspan') or 1)
			content = _extractHtmlCellContent(cell)
			alignment = _detectCellAlignment(cell)

			rowCells.append(_HtmlCell(content, rowIdx, colIdx, colspan, rowspan, alignment))

			for r in range(rowspan):
				for c in range(colspan):
					if r == 0 and c == 0:
						continue
					occupied[(rowIdx + r, colIdx + c)] = True

			colIdx += colspan

		if rowCells:
			extracted.append(rowCells)

	return extracted


def _parseHtmlTableStructure(htmlContent: str) -> tuple[list[list[_HtmlCell]], list[list[_HtmlCell]]]:
	"""Parse HTML and return (header_rows, body_rows)."""
	soup = BeautifulSoup(htmlContent, 'html.parser')
	table = soup.find('table')
	if table is None:
		raise ValueError('No table found in HTML content.')

	thead = table.find('thead')
	tbody = table.find('tbody')

	headerRows: list[list[_HtmlCell]] = []
	bodyRows: list[list[_HtmlCell]] = []

	if thead is not None:
		headerRows = _extractRowsFromTrs(thead.find_all('tr', recursive=False) or thead.find_all('tr'))

	if tbody is not None:
		bodyRows = _extractRowsFromTrs(tbody.find_all('tr', recursive=False) or tbody.find_all('tr'))
	else:
		directTrs = []
		for tr in table.find_all('tr'):
			parent = tr.parent
			if parent is table or (parent is not None and parent.name not in ('thead', 'tbody', 'tfoot')):
				directTrs.append(tr)
		if not headerRows:
			bodyRows = _extractRowsFromTrs(directTrs)
		elif directTrs:
			bodyRows = _extractRowsFromTrs(directTrs)

	if not headerRows and not bodyRows:
		raise ValueError('Table is empty.')

	return headerRows, bodyRows


def _calculateCellWidth(col: int, colspan: int, colWidths: list[int]) -> int:
	width = sum(colWidths[col + c] + 2 for c in range(colspan))
	return width + colspan - 1


def _formatCellContent(content: str, totalWidth: int) -> str:
	"""Pad cell content to column width. Alignment is expressed in separator lines, not here."""
	padding = totalWidth - len(content) - 2
	if padding < 0:
		padding = 0
	return ' ' + content + (' ' * padding) + ' '


def _formatAlignSegment(innerWidth: int, char: str, alignment: str) -> str:
	"""Format one separator segment between + signs with per-column alignment colons."""
	if innerWidth <= 0:
		return ''
	if alignment == 'left':
		return ':' + char * (innerWidth - 1)
	if alignment == 'right':
		return char * (innerWidth - 1) + ':'
	return char * innerWidth


def _findCellAbove(grid: list[list[Any]], rowIdx: int, colIdx: int, maxCols: int) -> Optional[_HtmlCell]:
	for r in range(rowIdx - 1, -1, -1):
		row = grid[r]
		if not row:
			break
		for c in range(maxCols):
			cell = row[c]
			if cell is not None and not cell.merged and cell.rowspan > 1:
				if r <= rowIdx < r + cell.rowspan and c <= colIdx < c + cell.colspan:
					return cell
	return None


def _getRowspanCells(grid: list[list[Any]], rowIdx: int, maxCols: int) -> dict[int, _HtmlCell]:
	rowspanCells: dict[int, _HtmlCell] = {}
	for r in range(rowIdx + 1):
		row = grid[r]
		if not row:
			continue
		for c in range(maxCols):
			cell = row[c]
			if cell is not None and not cell.merged and cell.rowspan > 1:
				if r <= rowIdx and (r + cell.rowspan) > rowIdx + 1:
					for col in range(c, c + cell.colspan):
						rowspanCells[col] = cell
	return rowspanCells


def _createSeparator(colWidths: list[int], maxCols: int, char: str = '-',
					 rowspanCells: Optional[dict[int, _HtmlCell]] = None,
					 colAlignments: Optional[list[str]] = None) -> str:
	if not rowspanCells:
		segments = []
		for col in range(maxCols):
			innerWidth = colWidths[col] + 2
			if colAlignments is not None:
				segments.append(_formatAlignSegment(innerWidth, char, colAlignments[col]))
			else:
				segments.append(char * innerWidth)
		return '+' + '+'.join(segments) + '+'

	parts = ['+']
	for col in range(maxCols):
		innerWidth = colWidths[col] + 2
		if col in rowspanCells:
			fill = ' ' * innerWidth
		elif colAlignments is not None:
			fill = _formatAlignSegment(innerWidth, char, colAlignments[col])
		else:
			fill = char * innerWidth
		parts.append(fill)
		if col < maxCols - 1:
			current = rowspanCells.get(col)
			nxt = rowspanCells.get(col + 1)
			parts.append(' ' if current is not None and nxt is not None and current is nxt else '+')
		else:
			parts.append('+')
	return ''.join(parts)


def _buildPlacementGrid(table: list[list[_HtmlCell]], maxCols: int) -> list[list[Any]]:
	grid: list[list[Any]] = [[None] * maxCols for _ in range(len(table))]
	for rowIdx, row in enumerate(table):
		for cell in row:
			r, c = rowIdx, cell.col
			if grid[r][c] is None:
				grid[r][c] = cell
				for dr in range(cell.rowspan):
					for dc in range(cell.colspan):
						if dr == 0 and dc == 0:
							continue
						mergedR, mergedC = r + dr, c + dc
						if mergedR < len(grid) and mergedC < maxCols and grid[mergedR][mergedC] is None:
							grid[mergedR][mergedC] = _HtmlCell(merged=True)
	return grid


def _updateColWidths(table: list[list[_HtmlCell]], maxCols: int, colWidths: list[int]) -> None:
	grid = _buildPlacementGrid(table, maxCols)
	for row in grid:
		for colIdx, cell in enumerate(row):
			if cell is None or cell.merged or cell.content is None:
				continue
			if cell.content == '' and cell.colspan == 1:
				continue
			cellLines = cell.content.split('\n')
			maxLineLength = 0
			for i, line in enumerate(cellLines):
				# Pandoc multi-line continuation adds ' \' (+2) on non-last lines
				extra = 2 if len(cellLines) > 1 and i < len(cellLines) - 1 else 0
				maxLineLength = max(maxLineLength, len(line) + extra)
			if maxLineLength == 0:
				continue
			minWidth = maxLineLength if cell.colspan == 1 else -(-maxLineLength // cell.colspan)
			for c in range(cell.colspan):
				colWidths[colIdx + c] = max(colWidths[colIdx + c], minWidth)


def _generateGridSubTable(table: list[list[_HtmlCell]], maxCols: int, colWidths: list[int],
						  colAlignments: Optional[list[str]] = None,
						  alignmentOn: Optional[str] = None) -> str:
	"""Generate a grid sub-table.

	alignmentOn: 'first' or 'last' — which separator line receives per-column : alignment markers.
	"""
	if not table:
		return ''

	grid = _buildPlacementGrid(table, maxCols)

	def formatRow(rowIdx: int, lineIndex: int = 0) -> str:
		row = grid[rowIdx]
		line = '|'
		col = 0
		while col < maxCols:
			cellAbove = _findCellAbove(grid, rowIdx, col, maxCols)
			if cellAbove is not None:
				width = _calculateCellWidth(col, cellAbove.colspan, colWidths)
				line += ' ' * width
				col += cellAbove.colspan
			else:
				cell = row[col]
				if cell is not None and not cell.merged:
					cellContent = cell.content if cell.content is not None else ''
					# Do not trim lines — preserve markdown indentation / spacing
					cellLines = cellContent.split('\n')
					width = _calculateCellWidth(col, cell.colspan, colWidths)
					if len(cellLines) > 1:
						if lineIndex < len(cellLines):
							lineContent = cellLines[lineIndex]
							if lineIndex < len(cellLines) - 1:
								lineContent += ' \\'
							line += _formatCellContent(lineContent, width)
						else:
							line += ' ' * width
					else:
						if lineIndex == 0:
							line += _formatCellContent(cellContent, width)
						else:
							line += ' ' * width
					col += cell.colspan
				else:
					line += ' ' * (colWidths[col] + 2)
					col += 1
			if col < maxCols:
				line += '|'
		return line + '|'

	def maxLinesInRow(rowIdx: int) -> int:
		row = grid[rowIdx]
		maxLines = 1
		for col in range(maxCols):
			cell = row[col]
			if cell is not None and not cell.merged and cell.content:
				maxLines = max(maxLines, len(cell.content.split('\n')))
		return maxLines

	firstAlign = colAlignments if alignmentOn == 'first' else None
	lastAlign = colAlignments if alignmentOn == 'last' else None

	lines = [_createSeparator(colWidths, maxCols, '-', colAlignments=firstAlign)]
	for i in range(len(table)):
		for lineIdx in range(maxLinesInRow(i)):
			lines.append(formatRow(i, lineIdx))
		if i < len(table) - 1:
			rowspanCells = _getRowspanCells(grid, i, maxCols)
			lines.append(_createSeparator(colWidths, maxCols, '-', rowspanCells))
	lines.append(_createSeparator(colWidths, maxCols, '-', colAlignments=lastAlign))
	return '\n'.join(lines)


def generateGridTableFromHtml(htmlContent: str) -> str:
	"""Generate a Pandoc-style grid table from an HTML table string.

	Preserves cell content (including markdown) as-is. Handles rowspan and colspan.
	The result is markdown suitable for sending to Pandoc.

	Args:
		htmlContent: HTML containing a <table> (may include surrounding markup).

	Returns:
		Pandoc grid table as a string.

	Raises:
		ValueError: If no table is found or the table is empty.
	"""
	headerRows, bodyRows = _parseHtmlTableStructure(htmlContent)
	if not headerRows and not bodyRows:
		return ''

	allRows = headerRows + bodyRows
	maxCols = max((cell.col + cell.colspan for row in allRows for cell in row), default=0)
	if maxCols == 0:
		return ''

	colWidths = [1] * maxCols
	if headerRows:
		_updateColWidths(headerRows, maxCols, colWidths)
	if bodyRows:
		_updateColWidths(bodyRows, maxCols, colWidths)

	colAlignments = _deriveColumnAlignments(headerRows, bodyRows, maxCols)

	headerGridTable = (
		_generateGridSubTable(headerRows, maxCols, colWidths, colAlignments, 'last')
		if headerRows else ''
	)
	bodyAlignmentOn = 'first' if not headerRows else None
	bodyGridTable = (
		_generateGridSubTable(bodyRows, maxCols, colWidths, colAlignments, bodyAlignmentOn)
		if bodyRows else ''
	)

	if headerGridTable:
		headerLines = headerGridTable.split('\n')
		headerLines[-1] = headerLines[-1].replace('-', '=')
		bodyLines = bodyGridTable.split('\n') if bodyGridTable else []
		if bodyLines:
			bodyLines = bodyLines[1:]  # drop body's top border
		if bodyLines:
			return '\n'.join(headerLines) + '\n' + '\n'.join(bodyLines)
		return '\n'.join(headerLines)

	return bodyGridTable
+35
Changes for generateBaseline/pandocFilter.py: 35 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -11,6 +11,7 @@ import argparse, os, re, sys
from rich import print, inspect
from rich.progress import Progress, TextColumn, TimeElapsedColumn
from PIL import Image
from htmlToGridTable import generateGridTableFromHtml

#from resizeImage import MAX_HEIGHT_IN, MAX_WIDTH_IN, figure_display_limit, format_inches

@@ -541,6 +542,39 @@ def replaceSuperscriptsAndSubscripts(progress:Progress, mdLines:list[str]) -> li
	progress.stop_task(_taskID)
	return _lines

def convertHtmlTablesTogridTables(progress:Progress, mdLines:list[str]) -> list[str]:
	"""	Convert HTML tables to grid tables.
	"""
	_taskID = progress.add_task('[blue]Converting HTML tables to grid tables', total=0)
	# progress.update()

	inTable = False
	htmlTable = ''
	_lines:list[str] = []
	for line in mdLines:
		# If we are in a code block, we are not in a list
		if checkInCodeBlock(line):
			_lines.append(line)
			continue

		# Replace all HTML table tags with grid table tags.
		if re.match(r'^\s*<table', line):
			htmlTable = line
			inTable = True
		elif re.match(r'^\s*</table>', line):
			htmlTable += line
			inTable = False
			gridTable = generateGridTableFromHtml(htmlTable)
			print(f'{gridTable}')
			_lines.append(gridTable)
			htmlTable = ''
		elif inTable:
			htmlTable += line
		else:
			_lines.append(line)

	progress.stop_task(_taskID)
	return _lines

def process(args) -> None:
	with Progress(TextColumn('{task.description}'),  TimeElapsedColumn()) as progress:
@@ -559,6 +593,7 @@ def process(args) -> None:
		# mdLines = instertLineAfterTableOrCodeBlock(progress, mdLines)
		mdLines = replaceLineBreaks(progress, mdLines)
		mdLines = replaceSuperscriptsAndSubscripts(progress, mdLines)
		mdLines = convertHtmlTablesTogridTables(progress, mdLines)
		writeMDFile(progress, mdLines, args.document, args.outDirectory)


+2
Changes for generateBaseline/requirements.txt: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -19,3 +19,5 @@ lxml==4.9.3
python-docx==0.8.11

#pywin32

beautifulsoup4>=4.12.0