Commit 2fb276c1 authored by Jonas Schüppen's avatar Jonas Schüppen
Browse files

Merge remote-tracking branch 'origin/master' into format_update_EQ_in_NO

# Conflicts:
#	generateBaseline/postprocessing.py
parents 9f1d8b23 fb654d56
Loading
Loading
Loading
Loading
Loading
+2
Changes for .gitlab-ci.yml: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -71,6 +71,8 @@ Build generateSpecWebSite docker image:
        - generateSpecWebSite/toMkdocs.py
        - generateSpecWebSite/create_frontmatter_table.py
        - generateSpecWebSite/stylesheets/extra.css
        - generateSpecWebSite/stylesheets/palettes/**/*
        - generateSpecWebSite/md_to_docx_converter/**/*
        - markdownTools/dockerfile
        - markdownTools/setup.py
        - markdownTools/requirements.txt
+117 −3
Changes for generateBaseline/pandocFilter.py: 117 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -10,6 +10,62 @@
import argparse, os, re, sys
from rich import print, inspect
from rich.progress import Progress, TextColumn, TimeElapsedColumn
from PIL import Image

#from resizeImage import MAX_HEIGHT_IN, MAX_WIDTH_IN, figure_display_limit, format_inches

figureImageRegex = re.compile(r'!\[([^\]]*)\]\(([^)]+)\)(\{[^}]*\})?')
rasterImageExtensions = ('.png', '.jpg', '.jpeg', '.gif', '.webp', '.tif', '.tiff')
DPI = 96
MAX_WIDTH_IN = 6.75
MAX_HEIGHT_IN = 9.5

def format_inches(value: float) -> str:
    """Format inch values for pandoc attributes without spurious rounding."""
    return f"{value:.4f}".rstrip("0").rstrip(".")

def resolve_image_path(document: str, image_path: str) -> str:
	if os.path.isabs(image_path):
		return image_path
	doc_dir = os.path.dirname(os.path.abspath(document))
	return os.path.normpath(os.path.join(doc_dir, image_path))


def fitted_figure_limit(width_px, height_px, max_width_in_inches, max_height_in_inches):
    """Compute the limiting display dimension from pixel size.

    Returns:
        (limiting_dimension, limit_inches, scale) or (None, None, None)
    """
    width_in = width_px / DPI
    height_in = height_px / DPI

    scale_w = max_width_in_inches / width_in if width_in > max_width_in_inches else 1.0
    scale_h = max_height_in_inches / height_in if height_in > max_height_in_inches else 1.0
    scale = min(scale_w, scale_h)

    if scale >= 1.0:
        return None, None, None

    if scale_h < scale_w:
        return "height", max_height_in_inches, scale
    return "width", max_width_in_inches, scale

	
def figure_display_limit(image_path, max_width_in_inches, max_height_in_inches):
    """Read image pixels and return pandoc limit info without modifying the file."""
    with Image.open(image_path) as image:
        image.load()
        width_px, height_px = image.size

    limiting_dimension, limit_inches, scale = fitted_figure_limit(
        width_px, height_px, max_width_in_inches, max_height_in_inches
    )
    if limiting_dimension is None:
        return None, width_px / DPI, width_px, height_px, 1.0

    return limiting_dimension, limit_inches, width_px, height_px, scale


def readMDFile(progress:Progress, document:str) -> list[str]:
	"""	Read the markdown file and return a list of lines.
@@ -145,6 +201,60 @@ def replaceFigureCaptions(progress:Progress, mdLines:list[str]) -> list[str]:
	return _lines


def addFigureDimensions(progress: Progress, mdLines: list[str], document: str) -> list[str]:
	"""Add a pandoc width or height attribute; default to natural width when within limits."""
	_taskID = progress.add_task('[blue]Adding figure dimensions', total=0)

	_lines: list[str] = []
	for line in mdLines:
		if checkInCodeBlock(line):
			_lines.append(line)
			continue

		match = figureImageRegex.search(line)
		if not match:
			_lines.append(line)
			continue

		image_path = match.group(2).strip()
		existing_attrs = match.group(3) or ''
		if 'width=' in existing_attrs or 'height=' in existing_attrs:
			_lines.append(line)
			continue

		if not image_path.lower().endswith(rasterImageExtensions):
			_lines.append(line)
			continue

		full_path = resolve_image_path(document, image_path)
		if not os.path.isfile(full_path):
			_lines.append(line)
			continue

		limiting_dimension, limit_in_inches, width_px, height_px, scale = figure_display_limit(
			full_path, MAX_WIDTH_IN, MAX_HEIGHT_IN
		)
		if limiting_dimension is None:
			attrs = f'{{width={format_inches(limit_in_inches)}in}}'
		else:
			attrs = f'{{{limiting_dimension}={format_inches(limit_in_inches)}in}}'
		
		new_line = figureImageRegex.sub(
			rf'![\1](\2){attrs}',
			line.rstrip('\n'),
			count=1,
		)
		_lines.append(f'{new_line}\n')
		print(
			f'Figure dimensions added for {image_path}: {attrs} '
			f'(from {width_px}x{height_px} px, scale {scale:.6f}, '
			f'max {MAX_WIDTH_IN}" x {MAX_HEIGHT_IN}")'
		)

	progress.stop_task(_taskID)
	return _lines


def replaceFiguresPathSvgToPng(progress: Progress, mdLines: list[str]) -> list[str]:
	"""	Replace figure extensions from svg to png.
	"""
@@ -176,12 +286,15 @@ def replaceLineBreaks(progress: Progress, mdLines: list[str]) -> list[str]:
	_taskID = progress.add_task('[blue]Replacing linebreaks', total=0)
	# progress.update()
	linebreaksregex = re.compile('<\s*br\s*/?\s*>')
	# Blockquote code boundary: > then optional spaces, then ``` or 4-space indent (do not strip the line first).
	blockquotecoderegex = re.compile(r'^\s*>\s*(?:```|    )')

	_lines: list[str] = []
	_inCodeBlock = False
	for line in mdLines:
		# Check if we are in a code block
		if line.strip().startswith('```'):
		# 1- fenced ``` (leading whitespace allowed), 2- 4-space indent on raw line,
		# 3- same inside a blockquote (> optional spaces before ``` or indent)
		if line.lstrip().startswith('```') or line.startswith('    ') or blockquotecoderegex.match(line):
			_inCodeBlock = not _inCodeBlock
		if _inCodeBlock:
			_lines.append(line)
@@ -388,7 +501,7 @@ def replaceBulletedLettersLists(progress:Progress, mdLines:list[str]) -> list[st
	# progress.update()
	
	# Match "- " only when followed by a letter and ")" (e.g. "- a) text").
	bulletedLettersListRegex = re.compile(r'^([ \t]*)- (?=[A-Za-z]+\))')
	bulletedLettersListRegex = re.compile(r'^([ \t]*)- (?=[A-Za-z]+[).-]?)')
	_lines:list[str] = []
	for line in mdLines:
		# If we are in a code block, we are not in a list
@@ -437,6 +550,7 @@ def process(args) -> None:
		mdLines = replaceFigureCaptions(progress, mdLines)
		if args.figure_paths:
			mdLines = replaceFiguresPathSvgToPng(progress, mdLines)
		mdLines = addFigureDimensions(progress, mdLines, args.document)
		if args.table_separators:
			mdLines = correctTableSeparators(progress, mdLines)
		mdLines = instertLineBeforeStartOfList(progress, mdLines)
+92 −30
Changes for generateBaseline/postprocessing.py: 92 added lines, 30 removed lines.
Original line number Diff line number Diff line
@@ -664,6 +664,57 @@ def table_widths_adjustment(config):
                cell.width = width
    doc.save(docx_path)

def _paragraph_text(elem):
    """
    Returns the text of a paragraph, respecting how headings are created in update_heading_styles:
    number + <w:tab/> + title in separate run parts.
    """
    ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
    if elem is None or elem.tag != f"{{{ns['w']}}}p":
        return ""
    # Build text from runs to respect how headings are created in update_heading_styles:
    # number + <w:tab/> + title in separate run parts.
    parts = []
    for run in elem.xpath('./w:r', namespaces=ns):
        for child in run:
            if child.tag == f"{{{ns['w']}}}t" and child.text:
                parts.append(child.text)
            elif child.tag in (f"{{{ns['w']}}}tab", f"{{{ns['w']}}}br"):
                parts.append(" ")
    # Fallback for paragraphs containing text in non-direct run descendants.
    if not parts:
        parts = elem.xpath('.//w:t/text()', namespaces=ns)
    return ''.join(parts).strip()


def _paragraph_style_val(para, ns):
    w = ns['w']
    p_pr = para.find(f'{{{w}}}pPr')
    if p_pr is None:
        return None
    p_style = p_pr.find(f'{{{w}}}pStyle')
    if p_style is None:
        return None
    return p_style.get(f'{{{w}}}val')


def _normalize_ws(text):
    return re.sub(r'\s+', ' ', text.replace('\u00A0', ' ')).strip()


def _is_in_abbreviations_clause(para, ns):
    """True when the nearest preceding Heading2 section is Abbreviations."""
    w = ns['w']
    previous = para.getprevious()
    while previous is not None:
        if previous.tag != f'{{{w}}}p':
            previous = previous.getprevious()
            continue
        if _paragraph_style_val(previous, ns).startswith('Heading'): # It can be Heading1, Heading2 or Heading3
            heading_text = _normalize_ws(_paragraph_text(previous))
            return bool(re.search(r'\babbreviations\b', heading_text, flags=re.IGNORECASE))
        previous = previous.getprevious()
    return False


def update_figure_captions(docx_input, docx_output):
@@ -1990,7 +2041,7 @@ def update_notes(docx_input, docx_output):
            pStyle_elem.set(f"{{{ns['w']}}}val", example_style)
            counter_ew += 1
            
            # Get the matched text (e.g., "EXAMPLE:", "EXAMPLE 1:", "EXAMPLE :")
            # Get the matched text (e.g., "EXAMPLE:", "EXAMPLE 1:", "EXAMPLE :", "EXAMPLES:")
            matched_example = example_match.group(0)
            
             # Find and remove the matched EXAMPLE pattern from the first run that contains it (EXAMPLE won't be in hyperlinks)
@@ -2053,6 +2104,8 @@ def update_notes(docx_input, docx_output):

                prev_pStyle_val = prev_pStyle[0].get(f"{{{ns['w']}}}val")
                if prev_pStyle_val == example_style:
                    # EW in the Abbreviations clause is an abbreviation entry, not an example.
                    if not _is_in_abbreviations_clause(para, ns):
                        pStyle_elem.set(f"{{{ns['w']}}}val", "PL")
                        print(f'Changed style "BlockText" to "PL" because it is preceded by a paragraph with style "EX" (line {prev_para.sourceline})')
                break
@@ -2118,6 +2171,9 @@ def update_abbreviations(docx_input, docx_output):
        if not verbatim_runs:
            continue

        if not _is_in_abbreviations_clause(para, ns):
            continue

        # Get the parent element to insert new paragraphs
        parent = para.getparent()
        if parent is None:
@@ -2128,20 +2184,30 @@ def update_abbreviations(docx_input, docx_output):
        
        # Process each verbatim run separately
        new_paragraphs = []
        option2_definition = False
        for verbatim_run in verbatim_runs:
            # Extract text from this specific verbatim run
            full_text = ""
            full_text_in_verbatim_run = ""
            text_elems = verbatim_run.xpath('.//w:t', namespaces=ns)
            for text_elem in text_elems:
                if text_elem.text:
                    full_text += text_elem.text
            
                    full_text_in_verbatim_run += text_elem.text
            # Two options for abbreviations:
            # 1. `ABBR        Abbreviation`
            #    - abbreviation followed by 2+ spaces followed by definition (usually all in a verbatim run)
            # 2. `ABBR` Abbreviation
            #    - abbreviation (in a verbatim run) followed by definition (in the remaining runs of the paragraph) separated by one or more spaces
            # Check if text contains multiple spaces (2 or more) separating two parts
            # Pattern: abbreviation followed by 2+ spaces followed by definition
            match = re.match(r'^(.+?)\s{2,}(.+)$', full_text.strip())
            match = re.match(r'^(.+?)\s{2,}(.+)$', full_text_in_verbatim_run.strip())
            if not match:
                continue
            
                # Option 2: abbreviation (in a verbatim run) followed by definition (in the remaining runs of the paragraph) separated by one or more spaces
                # Take all remaining runs of the paragraph as they are, except the verbatim run
                remaining_runs = [run for run in para.xpath('./w:r', namespaces=ns) if run != verbatim_run]
                abbreviation = full_text_in_verbatim_run.strip()
                option2_definition = True
                #definition = ''.join([run.xpath('.//w:t/text()', namespaces=ns)[0].text for run in remaining_runs]).strip()
            else:
                abbreviation = match.group(1).strip()
                definition = match.group(2).strip()
            
@@ -2168,13 +2234,17 @@ def update_abbreviations(docx_input, docx_output):
            run_tab.append(tab)
            new_para.append(run_tab)
            
            if not option2_definition:
                # Create second run with definition
                run2 = OxmlElement('w:r')
                t2 = OxmlElement('w:t')
                t2.text = definition
                run2.append(t2)
                new_para.append(run2)
            
            else:
                # Create second run with definition, append all remaining runs of the paragraph
                for run in remaining_runs:
                    new_para.append(run)
            new_paragraphs.append(new_para)
            counter += 1
        
@@ -2885,14 +2955,11 @@ def add_break_after_code_blocks_and_tables(docx_input, docx_output):

def update_equation_style(docx_input, docx_output):
    """
    Updates equation styles from 'Equation' to 'EQ' in a DOCX file.
    Apply EQ paragraph style to display equations only.

    Parameters
    ----------
    docx_input : str
        Path to the input DOCX file.
    docx_output : str
        Path to the output DOCX file.
    Equation-only paragraphs (no surrounding body text) get w:pStyle EQ.
    Inline equations within text are left unchanged (paragraph keeps Normal
    or whatever body style it already has; EQ is a paragraph style only).
    """
    ns = {
        "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
@@ -2906,32 +2973,27 @@ def update_equation_style(docx_input, docx_output):
    root = etree.fromstring(xml_data)
    new_style = "EQ"
    counter = 0

    EQUATION_ELEMENT_WRAPPED_IN_RUN = False
    # Loop over all elements to find "Equation" and change to "EQ"
    for equation in root.xpath('.//m:oMath', namespaces=ns):
        p = equation.getparent()

        # Surrounding paragraph
        p = equation
        if p.tag == f"{{{ns['w']}}}r":
            # Equation element wrapped in a run
            EQUATION_ELEMENT_WRAPPED_IN_RUN = True
        else:
            EQUATION_ELEMENT_WRAPPED_IN_RUN = False
        while p is not None and p.tag != f"{{{ns['w']}}}p":
            p = p.getparent()

        if p is None:
            continue

        pStyle = p.xpath('./w:pPr/w:pStyle', namespaces=ns)

        if pStyle:
            current_style = pStyle[0].get(f"{{{ns['w']}}}val")

            # Do not overwrite Example/Note Styles
            if current_style in ["EX", "EW", "NO", "TAN"]:
                continue

            # Check whether the equation element is the only element in the paragraph. The equation element may be not wrapped in a run.
            if (EQUATION_ELEMENT_WRAPPED_IN_RUN and len(p.xpath('.//w:r', namespaces=ns)) == 1) or (not EQUATION_ELEMENT_WRAPPED_IN_RUN and len(p.xpath('.//w:r', namespaces=ns)) == 0):
                pStyle[0].set(f"{{{ns['w']}}}val", new_style)

                counter += 1

            # If other runs are present, meaning it is inline equation, no need to modify anything.
            continue
    print(f'Changed style "Equation" to "EQ" {counter} times')

    xml_data = etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone="yes")
+24 −1
Changes for generateSpecWebSite/dockerfile: 24 added lines, 1 removed line.
Original line number Diff line number Diff line
FROM python:3.9-slim-bullseye
FROM python:3.10-slim-bullseye

# Build argument for architecture (amd64 or arm64)
ARG TARGETARCH=amd64

# Install system dependencies
RUN apt-get update && apt-get install -y \
    wget \
    curl \
    git \
    libreoffice \
    imagemagick \
    && rm -rf /var/lib/apt/lists/*

# Install Pandoc 3.7.0.2 based on architecture
RUN if [ "$TARGETARCH" = "arm64" ]; then \
        wget https://github.com/jgm/pandoc/releases/download/3.7.0.2/pandoc-3.7.0.2-1-arm64.deb \
        && dpkg -i pandoc-3.7.0.2-1-arm64.deb \
        && rm pandoc-3.7.0.2-1-arm64.deb; \
    else \
        wget https://github.com/jgm/pandoc/releases/download/3.7.0.2/pandoc-3.7.0.2-1-amd64.deb \
        && dpkg -i pandoc-3.7.0.2-1-amd64.deb \
        && rm pandoc-3.7.0.2-1-amd64.deb; \
    fi

ADD /generateSpecWebSite/ /generateSpecWebSite/
RUN chmod +x generateSpecWebSite/spec_on_pages.sh
+7 −2
Changes for generateSpecWebSite/gridTableTools.py: 7 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -202,12 +202,17 @@ def parseGridTableWithSpans(gridTable:str) -> tuple[GridTableRowList, GridTableR
					cell.content += _c + _nextListElementMark
				else: # Multiline content is concatenated to the last line with a space
					cell.content += ' ' +  _c + _nextListElementMark #add list element end mark
			elif len(_c) == 0:  # separation between list and other paragraph
			elif len(_c) == 0 or _c.endswith('>'):  # separation between list and other paragraph
				if cell.listFlag:
					cell.listFlag = False
					cell.content += '\n\n' #end list by \n
				#content = re.sub(r'\\\s*$', "\n", content.strip())
				cell.content += '\n' if not cell.content.endswith('\n') else ''
				if len(_c) == 0:
					cell.content += '\n'
				else:
					_c = re.sub(r'\\\s*$', '\n', _c)
					cell.content += _c + '\n'
				#cell.content += '\n' if not cell.content.endswith('\n') else ''
			else:
				if cell.content.endswith('\n'): # a force linebreak is present
					cell.content += re.sub(r'\\\s*$', '\n', _c)
Loading