Loading generateBaseline/pandocFilter.py +172 −1 Changes for generateBaseline/pandocFilter.py: 172 added lines, 1 removed line. Original line number Diff line number Diff line Loading @@ -8,10 +8,16 @@ # import argparse, os, re, sys from rich import print, inspect from rich import inspect from rich.console import Console from rich.progress import Progress, TextColumn, TimeElapsedColumn # CI captures stdout with no terminal width, and Rich otherwise wraps at 80 columns. # markup is off: a lowercase "[clause 5]" is a Rich tag and would be dropped from the log. print = Console(soft_wrap=True, markup=False).print from PIL import Image from htmlToGridTable import generateGridTableFromHtml from postprocessing import _caption_bookmark_name #from resizeImage import MAX_HEIGHT_IN, MAX_WIDTH_IN, figure_display_limit, format_inches Loading Loading @@ -134,6 +140,29 @@ def checkInCodeBlock(line:str) -> bool: return _inCodeBlock _inGridTable = False def resetGridTableState() -> None: global _inGridTable _inGridTable = False def inGridTable(line:str) -> bool: """True for every line of a grid table. A pipe table is not a grid table.""" global _inGridTable body = line.lstrip(' \t') if not _inGridTable: if _MATCH_GRID_TABLE.match(body): _inGridTable = True return True return False if (_MATCH_GRID_TABLE.match(body) or _MATCH_GRID_TABLE_HEADER_SEPARATOR.match(body) or _MATCH_GRID_TABLE_BODY_SEPARATOR.match(body) or re.match(r'^\|.*\|', body)): return True _inGridTable = False return False # Patterns for skipping transforms inside code blocks and tables. _BLOCKQUOTE_CODE_REGEX = re.compile(r'^\s*>\s*(?:```| )') _INLINE_CODE_REGEX = re.compile(r'`[^`\n]+`') Loading Loading @@ -875,6 +904,145 @@ def convertHtmlTablesTogridTables(progress:Progress, mdLines:list[str]) -> list[ progress.stop_task(_taskID) return _lines def normalizeCitationReferences(progress:Progress, mdLines:list[str]) -> list[str]: """ Normalize citation references. [citation_label](#citation_reference) -> [citation_label](#field_name) [Table 1.1-1](#tbl:MYTABLE) -> [Table 1.1-1](#table_1.1-1) [Figure 6-1](#fig:MYFIGURE) -> [Figure 6-1](#figure_6-1) [Clause 7.1](#sec:CLAUSE7.1) -> [Clause 7.1](#71-my-title-clause) [Annex B](#sec:B) -> [Annex B](#b-my-title-annex) [Annex B.1](#sec:B.1) -> [Annex B.1](#b1-my-title-annex) [Annex B.1.1](#sec:B.1.1) -> [Annex B.1.1](#b11-my-title-annex) [Annex B.1.1.1](#sec:B.1.1.1) -> [Annex B.1.1.1](#b111-my-title-annex) [Annex B.1.1.1.1](#sec:B.1.1.1.1) -> [Annex B.1.1.1.1](#b1111-my-title-annex) [Annex B.1.1.1.1.1](#sec:B.1.1.1.1.1) -> [Annex B.1.1.1.1.1](#b11111-my-title-annex) """ _taskID = progress.add_task('[blue]Normalizing citation references', total=0) resetCodeBlockState() resetGridTableState() clause_pattern = re.compile(r'\[((?:clauses?|annex(?:es)?)\s+((?:[A-Z]+|\d+)(?:\.\d+)*)(?:\s+[^\]\n]*)?)\]\((#sec:[^)]*)\)', re.IGNORECASE) figure_pattern = re.compile(r'\[(figures?\s+(?:(?:[A-Z]+|\d+)(?:\.\d+)*(?:-\d+)?))\]\((#figure_[^)]*)\)', re.IGNORECASE) table_pattern = re.compile(r'\[(tables?\s+(?:(?:[A-Z]+|\d+)(?:\.\d+)*(?:-\d+)?))\]\((#tbl:[^)]*)\)', re.IGNORECASE) citation_replacements:dict[str, tuple[str, str]] = {} _lines:list[str] = [] clause_anchors:dict[str, str] = {} for idx, line in enumerate(mdLines): # Find all headings and determine the reference name. After the title, remove span and/or a tags # "10.1" + "Imports other md files" becomes "101-imports-other-md-files". Any other symbols ".", ",", ":", ";", "!", "[", "]" are removed. # The bookmark covers the number run only. Pandoc's heading bookmark is left unchanged. heading_regex = re.compile(r'^#+\s+(\d+(?:\.\d+)*)\s+(.+)$') annex_heading_regex = re.compile(r'^#+\s+Annex\s+([A-Z])(?:\s*\((?:informative|normative|informative or normative|normative or informative)\))?\s*:\s*(.+)$', re.IGNORECASE) annex_subheading_regex = re.compile(r'^#+\s+([A-Z](?:\.\d+)+)\s+(.+)$', re.IGNORECASE) if match := heading_regex.match(line): number = match.group(1) title = match.group(2) title = re.sub(r'<span[^>]*>.*?</span>', '', title) title = re.sub(r'<a[^>]*>.*?</a>', '', title) title = title.strip() title_slug = re.sub(r'\s+', '-', title.strip()).lower() title_slug = re.sub(r'[.,:;![\]<>"\\(){}]', '', title_slug) bookmark_name = f"{number.replace('.', '')}-{title_slug}" # Bookmarks are limited to 40 characters by Office 365. Office will truncate it when bookmark is longer if len(bookmark_name) >= 40: bookmark_name = bookmark_name[:39] # Save the bookmark name associated to the heading number and the line index clause_anchors[f'{number}'] = (idx, bookmark_name) elif match := (annex_heading_regex.match(line) or annex_subheading_regex.match(line)): annex_letter = match.group(1) annex_title = match.group(2) annex_title = re.sub(r'<span[^>]*>.*?</span>', '', annex_title) annex_title = re.sub(r'<a[^>]*>.*?</a>', '', annex_title) annex_title = annex_title.strip() annex_title_slug = re.sub(r'\s+', '-', annex_title.strip()).lower() annex_title_slug = re.sub(r'[.,:;![\]<>"\\(){}]', '', annex_title_slug) bookmark_name = f"{annex_letter.lower().replace('.', '')}-{annex_title_slug}" # Bookmarks are limited to 40 characters by Office 365. Office will truncate it when bookmark is longer if len(bookmark_name) > 39: bookmark_name = bookmark_name[:39] # Save the bookmark name associated to the heading number and the line index clause_anchors[f'{annex_letter}'] = (idx, bookmark_name) for line in mdLines: citations = [] if checkInCodeBlock(line) or inGridTable(line): _lines.append(line) continue # Normalize table citation references. if table_citations := table_pattern.finditer(line): citations += table_citations # Normalize figure citation references. if figure_citations := figure_pattern.finditer(line): citations += figure_citations for citation in citations: citation_label = citation.group(1) field_name = _caption_bookmark_name(citation_label) if not field_name: continue # Normalize the citation reference to the field name citation_reference = citation.group(2) # Substitute the citation reference with the field name line = line.replace(f'{citation_reference})', f'#{field_name})') # Add citation replacement to the dict if citation_label not in citation_replacements.keys(): citation_replacements[citation_label] = (citation_reference, field_name) print(f'Citation reference: {citation_reference} -> {field_name} for table/figure {citation.group(0).strip()}') # Normalize clause citation references. # Group 2 is the clause number. Group 3 is the #sec: reference. if clause_citations := clause_pattern.finditer(line): for clause_citation in clause_citations: citation_label = clause_citation.group(0).strip() citation_reference = clause_citation.group(3) citation_clause_number = clause_citation.group(2) if citation_clause_number in clause_anchors.keys(): field_name = clause_anchors[citation_clause_number][1] # Normalize the citation reference to the field name # Substitute the citation reference with the field name # Include the closing parenthesis. #sec:INT-COM must not match #sec:INT-COM-E-EndAuth. line = line.replace(f'{citation_reference})', f'#{field_name})') print(f'Citation reference: {citation_reference} -> {field_name} for clause {citation_label}') # Add citation replacement to the dict #citation_replacements[citation_label] = (citation_reference, field_name) _lines.append(line) # Substitute the anchors with the field names. Keep anchors in headings, postprocessing will add the new ones. heading_lines = {index for index, _bookmark_name in clause_anchors.values()} resetGridTableState() for idx, line in enumerate(_lines): if inGridTable(line): continue for citation_label, (citation_reference, field_name) in citation_replacements.items(): # Find any anchor in all lines of the document and replace it with the field name anchors = re.findall(r'<span id="?([^>"]*)"?></span>|<a name="?([^>"]*)"?>(?:</a>)?', line) old_id = citation_reference.lstrip('#') replaced = False for span_id, anchor_name in anchors: for anchor_id in (span_id, anchor_name): if not anchor_id or anchor_id not in (old_id, citation_reference) or anchor_id not in line: continue line = line.replace(anchor_id, f'{field_name}') print(f'Replaced table/figure anchor {anchor_id} with {field_name}') replaced = True break if replaced: break #if idx in heading_lines: # # Remove the anchor from heading line. It will be added in the postprocessing cause Pandoc does not support anchors starting with numbers. # line = re.sub(r'<span[^>]*></span>', '', line) # line = re.sub(r'<a[^>]*>(?:</a>)?', '', line) # print(f'Removed anchor from heading line {idx}: {line.strip()}') _lines[idx] = line progress.stop_task(_taskID) return _lines def process(args) -> None: with Progress(TextColumn('{task.description}'), TimeElapsedColumn()) as progress: mdLines = readMDFile(progress, args.document) Loading Loading @@ -910,6 +1078,9 @@ def process(args) -> None: mdLines = convertHtmlTablesTogridTables(progress, mdLines) print(f'Number of lines in the document after converting HTML tables to grid tables: {len(mdLines)}') writeMDFile(progress, mdLines, args.document, args.outDirectory) mdLines = normalizeCitationReferences(progress, mdLines) print(f'Number of lines in the document after normalizing citation references: {len(mdLines)}') writeMDFile(progress, mdLines, args.document, args.outDirectory) def main(args=None): Loading generateBaseline/postprocessing.py +23 −8 Changes for generateBaseline/postprocessing.py: 23 added lines, 8 removed lines. Original line number Diff line number Diff line Loading @@ -841,8 +841,11 @@ def _anchor_matches_bookmark(anchor, bookmark_name): def _caption_bookmark_name(text): """'Figure 6-1' or 'Table 7.1-1' -> figure_6-1 / table_7.1-1.""" match = re.match(r'^(figures?|tables?)\s+(\d+(?:\.\d+)*-\d+)$', text.strip(), re.IGNORECASE) """'Figure 6-1' or 'Table 7.1-1' -> figure_6-1 / table_7.1-1. The trailing '-n' is optional, so 'Table 6' and 'Figure 3.1' become table_6 and figure_3.1. """ match = re.match(r'^(figures?|tables?)\s+((?:[A-Z]+|\d+)(?:\.\d+)*(?:-\d+)?)$', text.strip(), re.IGNORECASE) if not match: return None kind = 'figure' if match.group(1).lower().startswith('figure') else 'table' Loading Loading @@ -885,7 +888,7 @@ def _place_caption_bookmark(para, root, ns, next_bookmark_id): return next_bookmark_id label, after = text_nodes[0].text.split(':', 1) label = label.rstrip() keyword_match = re.match(r'^(Figure|Table)\s+(\d+(?:\.\d+)*-\d+)$', label) keyword_match = re.match(r'^(figures?|tables?)\s+((?:[A-Z]+|\d+)(?:\.\d+)*(?:-\d+)?)$', label, re.IGNORECASE) if not keyword_match: return next_bookmark_id keyword, number = keyword_match.group(1), keyword_match.group(2) Loading Loading @@ -1119,6 +1122,9 @@ def update_heading_styles(docx_input, docx_output): title_slug = re.sub(r'\s+', '-', title.strip()).lower() title_slug = re.sub(r'[.,:;![\]<>"\\(){}]', '', title_slug) bookmark_name = f"{number.replace('.', '')}-{title_slug}" # Bookmarks are limited to 40 characters by Office 365. Office will truncate it when bookmark is longer if len(bookmark_name) >= 40: bookmark_name = bookmark_name[:39] _remove_bookmarks(root, ns, {bookmark_name}, paragraph=para, hashed=True) _insert_bookmark_around(label_run, bookmark_name, next_bookmark_id, ns) next_bookmark_id += 1 Loading Loading @@ -2378,9 +2384,11 @@ def update_table_rows(docx_input, docx_output): # center or other, default to TAC pStyle_elem.set(f"{{{ns['w']}}}val", "TAC") counter_tac += 1 # Disable keepnext to all rows elements to allow the split of the table. Table caption will be kept next to the table due to the style "TH". # Disable keepnext so the table can split. The caption stays with the table through style TH. # keepLines stays off on the first body row: a cell there can be one paragraph # with many hard breaks, taller than a page, and keepLines then leaves the caption alone. # <w:keepNext w:val="0"/> # <w:keepLines w:val="1"/> # <w:keepLines w:val="0"/> on the first body row, <w:keepLines w:val="1"/> on the rows after it # <w:widowControl w:val="0"/> pPr_elem = pStyle_elem.getparent() if pPr_elem is not None: Loading @@ -2389,8 +2397,15 @@ def update_table_rows(docx_input, docx_output): keepnext_elem = etree.Element(f"{{{ns['w']}}}keepNext") keepnext_elem.set(f"{{{ns['w']}}}val", "0") pPr_elem.append(keepnext_elem) first_body_row = True for prev in tr.itersiblings(preceding=True): if prev.tag != f"{{{ns['w']}}}tr": continue if not prev.xpath('./w:trPr/w:tblHeader[@w:val="on"]', namespaces=ns): first_body_row = False break keeplines_elem = etree.Element(f"{{{ns['w']}}}keepLines") keeplines_elem.set(f"{{{ns['w']}}}val", "1") keeplines_elem.set(f"{{{ns['w']}}}val", "0" if first_body_row else "1") pPr_elem.append(keeplines_elem) widowcontrol_elem = etree.Element(f"{{{ns['w']}}}widowControl") widowcontrol_elem.set(f"{{{ns['w']}}}val", "0") Loading Loading @@ -3417,8 +3432,8 @@ def update_references_style(docx_input, docx_output): # Clause 6.2.3, Clause A, or Clause A.1. Figure 6-1 or Figure 6.2-1, Table 7.1-1. # Some text is allowed after the clause citation, such as "Clause 6.2.3 option 1" clause_pattern = re.compile(r'^(?:clauses?|annex(?:es)?)\s+((?:[A-Z]|\d+)(?:\.\d+)*)(?:\s+.*)?$', re.IGNORECASE) figure_pattern = re.compile(r'^figures?\s+\d+(?:\.\d+)*-\d+$', re.IGNORECASE) table_pattern = re.compile(r'^tables?\s+\d+(?:\.\d+)*-\d+$', re.IGNORECASE) figure_pattern = re.compile(r'^figures?\s+(?:[A-Z]+|\d+)(?:\.\d+)*(?:-\d+)?$', re.IGNORECASE) table_pattern = re.compile(r'^tables?\s+(?:[A-Z]+|\d+)(?:\.\d+)*(?:-\d+)?$', re.IGNORECASE) def _bookmark_inner_text(start): bookmark_id = start.get(f"{{{ns['w']}}}id") Loading Loading
generateBaseline/pandocFilter.py +172 −1 Changes for generateBaseline/pandocFilter.py: 172 added lines, 1 removed line. Original line number Diff line number Diff line Loading @@ -8,10 +8,16 @@ # import argparse, os, re, sys from rich import print, inspect from rich import inspect from rich.console import Console from rich.progress import Progress, TextColumn, TimeElapsedColumn # CI captures stdout with no terminal width, and Rich otherwise wraps at 80 columns. # markup is off: a lowercase "[clause 5]" is a Rich tag and would be dropped from the log. print = Console(soft_wrap=True, markup=False).print from PIL import Image from htmlToGridTable import generateGridTableFromHtml from postprocessing import _caption_bookmark_name #from resizeImage import MAX_HEIGHT_IN, MAX_WIDTH_IN, figure_display_limit, format_inches Loading Loading @@ -134,6 +140,29 @@ def checkInCodeBlock(line:str) -> bool: return _inCodeBlock _inGridTable = False def resetGridTableState() -> None: global _inGridTable _inGridTable = False def inGridTable(line:str) -> bool: """True for every line of a grid table. A pipe table is not a grid table.""" global _inGridTable body = line.lstrip(' \t') if not _inGridTable: if _MATCH_GRID_TABLE.match(body): _inGridTable = True return True return False if (_MATCH_GRID_TABLE.match(body) or _MATCH_GRID_TABLE_HEADER_SEPARATOR.match(body) or _MATCH_GRID_TABLE_BODY_SEPARATOR.match(body) or re.match(r'^\|.*\|', body)): return True _inGridTable = False return False # Patterns for skipping transforms inside code blocks and tables. _BLOCKQUOTE_CODE_REGEX = re.compile(r'^\s*>\s*(?:```| )') _INLINE_CODE_REGEX = re.compile(r'`[^`\n]+`') Loading Loading @@ -875,6 +904,145 @@ def convertHtmlTablesTogridTables(progress:Progress, mdLines:list[str]) -> list[ progress.stop_task(_taskID) return _lines def normalizeCitationReferences(progress:Progress, mdLines:list[str]) -> list[str]: """ Normalize citation references. [citation_label](#citation_reference) -> [citation_label](#field_name) [Table 1.1-1](#tbl:MYTABLE) -> [Table 1.1-1](#table_1.1-1) [Figure 6-1](#fig:MYFIGURE) -> [Figure 6-1](#figure_6-1) [Clause 7.1](#sec:CLAUSE7.1) -> [Clause 7.1](#71-my-title-clause) [Annex B](#sec:B) -> [Annex B](#b-my-title-annex) [Annex B.1](#sec:B.1) -> [Annex B.1](#b1-my-title-annex) [Annex B.1.1](#sec:B.1.1) -> [Annex B.1.1](#b11-my-title-annex) [Annex B.1.1.1](#sec:B.1.1.1) -> [Annex B.1.1.1](#b111-my-title-annex) [Annex B.1.1.1.1](#sec:B.1.1.1.1) -> [Annex B.1.1.1.1](#b1111-my-title-annex) [Annex B.1.1.1.1.1](#sec:B.1.1.1.1.1) -> [Annex B.1.1.1.1.1](#b11111-my-title-annex) """ _taskID = progress.add_task('[blue]Normalizing citation references', total=0) resetCodeBlockState() resetGridTableState() clause_pattern = re.compile(r'\[((?:clauses?|annex(?:es)?)\s+((?:[A-Z]+|\d+)(?:\.\d+)*)(?:\s+[^\]\n]*)?)\]\((#sec:[^)]*)\)', re.IGNORECASE) figure_pattern = re.compile(r'\[(figures?\s+(?:(?:[A-Z]+|\d+)(?:\.\d+)*(?:-\d+)?))\]\((#figure_[^)]*)\)', re.IGNORECASE) table_pattern = re.compile(r'\[(tables?\s+(?:(?:[A-Z]+|\d+)(?:\.\d+)*(?:-\d+)?))\]\((#tbl:[^)]*)\)', re.IGNORECASE) citation_replacements:dict[str, tuple[str, str]] = {} _lines:list[str] = [] clause_anchors:dict[str, str] = {} for idx, line in enumerate(mdLines): # Find all headings and determine the reference name. After the title, remove span and/or a tags # "10.1" + "Imports other md files" becomes "101-imports-other-md-files". Any other symbols ".", ",", ":", ";", "!", "[", "]" are removed. # The bookmark covers the number run only. Pandoc's heading bookmark is left unchanged. heading_regex = re.compile(r'^#+\s+(\d+(?:\.\d+)*)\s+(.+)$') annex_heading_regex = re.compile(r'^#+\s+Annex\s+([A-Z])(?:\s*\((?:informative|normative|informative or normative|normative or informative)\))?\s*:\s*(.+)$', re.IGNORECASE) annex_subheading_regex = re.compile(r'^#+\s+([A-Z](?:\.\d+)+)\s+(.+)$', re.IGNORECASE) if match := heading_regex.match(line): number = match.group(1) title = match.group(2) title = re.sub(r'<span[^>]*>.*?</span>', '', title) title = re.sub(r'<a[^>]*>.*?</a>', '', title) title = title.strip() title_slug = re.sub(r'\s+', '-', title.strip()).lower() title_slug = re.sub(r'[.,:;![\]<>"\\(){}]', '', title_slug) bookmark_name = f"{number.replace('.', '')}-{title_slug}" # Bookmarks are limited to 40 characters by Office 365. Office will truncate it when bookmark is longer if len(bookmark_name) >= 40: bookmark_name = bookmark_name[:39] # Save the bookmark name associated to the heading number and the line index clause_anchors[f'{number}'] = (idx, bookmark_name) elif match := (annex_heading_regex.match(line) or annex_subheading_regex.match(line)): annex_letter = match.group(1) annex_title = match.group(2) annex_title = re.sub(r'<span[^>]*>.*?</span>', '', annex_title) annex_title = re.sub(r'<a[^>]*>.*?</a>', '', annex_title) annex_title = annex_title.strip() annex_title_slug = re.sub(r'\s+', '-', annex_title.strip()).lower() annex_title_slug = re.sub(r'[.,:;![\]<>"\\(){}]', '', annex_title_slug) bookmark_name = f"{annex_letter.lower().replace('.', '')}-{annex_title_slug}" # Bookmarks are limited to 40 characters by Office 365. Office will truncate it when bookmark is longer if len(bookmark_name) > 39: bookmark_name = bookmark_name[:39] # Save the bookmark name associated to the heading number and the line index clause_anchors[f'{annex_letter}'] = (idx, bookmark_name) for line in mdLines: citations = [] if checkInCodeBlock(line) or inGridTable(line): _lines.append(line) continue # Normalize table citation references. if table_citations := table_pattern.finditer(line): citations += table_citations # Normalize figure citation references. if figure_citations := figure_pattern.finditer(line): citations += figure_citations for citation in citations: citation_label = citation.group(1) field_name = _caption_bookmark_name(citation_label) if not field_name: continue # Normalize the citation reference to the field name citation_reference = citation.group(2) # Substitute the citation reference with the field name line = line.replace(f'{citation_reference})', f'#{field_name})') # Add citation replacement to the dict if citation_label not in citation_replacements.keys(): citation_replacements[citation_label] = (citation_reference, field_name) print(f'Citation reference: {citation_reference} -> {field_name} for table/figure {citation.group(0).strip()}') # Normalize clause citation references. # Group 2 is the clause number. Group 3 is the #sec: reference. if clause_citations := clause_pattern.finditer(line): for clause_citation in clause_citations: citation_label = clause_citation.group(0).strip() citation_reference = clause_citation.group(3) citation_clause_number = clause_citation.group(2) if citation_clause_number in clause_anchors.keys(): field_name = clause_anchors[citation_clause_number][1] # Normalize the citation reference to the field name # Substitute the citation reference with the field name # Include the closing parenthesis. #sec:INT-COM must not match #sec:INT-COM-E-EndAuth. line = line.replace(f'{citation_reference})', f'#{field_name})') print(f'Citation reference: {citation_reference} -> {field_name} for clause {citation_label}') # Add citation replacement to the dict #citation_replacements[citation_label] = (citation_reference, field_name) _lines.append(line) # Substitute the anchors with the field names. Keep anchors in headings, postprocessing will add the new ones. heading_lines = {index for index, _bookmark_name in clause_anchors.values()} resetGridTableState() for idx, line in enumerate(_lines): if inGridTable(line): continue for citation_label, (citation_reference, field_name) in citation_replacements.items(): # Find any anchor in all lines of the document and replace it with the field name anchors = re.findall(r'<span id="?([^>"]*)"?></span>|<a name="?([^>"]*)"?>(?:</a>)?', line) old_id = citation_reference.lstrip('#') replaced = False for span_id, anchor_name in anchors: for anchor_id in (span_id, anchor_name): if not anchor_id or anchor_id not in (old_id, citation_reference) or anchor_id not in line: continue line = line.replace(anchor_id, f'{field_name}') print(f'Replaced table/figure anchor {anchor_id} with {field_name}') replaced = True break if replaced: break #if idx in heading_lines: # # Remove the anchor from heading line. It will be added in the postprocessing cause Pandoc does not support anchors starting with numbers. # line = re.sub(r'<span[^>]*></span>', '', line) # line = re.sub(r'<a[^>]*>(?:</a>)?', '', line) # print(f'Removed anchor from heading line {idx}: {line.strip()}') _lines[idx] = line progress.stop_task(_taskID) return _lines def process(args) -> None: with Progress(TextColumn('{task.description}'), TimeElapsedColumn()) as progress: mdLines = readMDFile(progress, args.document) Loading Loading @@ -910,6 +1078,9 @@ def process(args) -> None: mdLines = convertHtmlTablesTogridTables(progress, mdLines) print(f'Number of lines in the document after converting HTML tables to grid tables: {len(mdLines)}') writeMDFile(progress, mdLines, args.document, args.outDirectory) mdLines = normalizeCitationReferences(progress, mdLines) print(f'Number of lines in the document after normalizing citation references: {len(mdLines)}') writeMDFile(progress, mdLines, args.document, args.outDirectory) def main(args=None): Loading
generateBaseline/postprocessing.py +23 −8 Changes for generateBaseline/postprocessing.py: 23 added lines, 8 removed lines. Original line number Diff line number Diff line Loading @@ -841,8 +841,11 @@ def _anchor_matches_bookmark(anchor, bookmark_name): def _caption_bookmark_name(text): """'Figure 6-1' or 'Table 7.1-1' -> figure_6-1 / table_7.1-1.""" match = re.match(r'^(figures?|tables?)\s+(\d+(?:\.\d+)*-\d+)$', text.strip(), re.IGNORECASE) """'Figure 6-1' or 'Table 7.1-1' -> figure_6-1 / table_7.1-1. The trailing '-n' is optional, so 'Table 6' and 'Figure 3.1' become table_6 and figure_3.1. """ match = re.match(r'^(figures?|tables?)\s+((?:[A-Z]+|\d+)(?:\.\d+)*(?:-\d+)?)$', text.strip(), re.IGNORECASE) if not match: return None kind = 'figure' if match.group(1).lower().startswith('figure') else 'table' Loading Loading @@ -885,7 +888,7 @@ def _place_caption_bookmark(para, root, ns, next_bookmark_id): return next_bookmark_id label, after = text_nodes[0].text.split(':', 1) label = label.rstrip() keyword_match = re.match(r'^(Figure|Table)\s+(\d+(?:\.\d+)*-\d+)$', label) keyword_match = re.match(r'^(figures?|tables?)\s+((?:[A-Z]+|\d+)(?:\.\d+)*(?:-\d+)?)$', label, re.IGNORECASE) if not keyword_match: return next_bookmark_id keyword, number = keyword_match.group(1), keyword_match.group(2) Loading Loading @@ -1119,6 +1122,9 @@ def update_heading_styles(docx_input, docx_output): title_slug = re.sub(r'\s+', '-', title.strip()).lower() title_slug = re.sub(r'[.,:;![\]<>"\\(){}]', '', title_slug) bookmark_name = f"{number.replace('.', '')}-{title_slug}" # Bookmarks are limited to 40 characters by Office 365. Office will truncate it when bookmark is longer if len(bookmark_name) >= 40: bookmark_name = bookmark_name[:39] _remove_bookmarks(root, ns, {bookmark_name}, paragraph=para, hashed=True) _insert_bookmark_around(label_run, bookmark_name, next_bookmark_id, ns) next_bookmark_id += 1 Loading Loading @@ -2378,9 +2384,11 @@ def update_table_rows(docx_input, docx_output): # center or other, default to TAC pStyle_elem.set(f"{{{ns['w']}}}val", "TAC") counter_tac += 1 # Disable keepnext to all rows elements to allow the split of the table. Table caption will be kept next to the table due to the style "TH". # Disable keepnext so the table can split. The caption stays with the table through style TH. # keepLines stays off on the first body row: a cell there can be one paragraph # with many hard breaks, taller than a page, and keepLines then leaves the caption alone. # <w:keepNext w:val="0"/> # <w:keepLines w:val="1"/> # <w:keepLines w:val="0"/> on the first body row, <w:keepLines w:val="1"/> on the rows after it # <w:widowControl w:val="0"/> pPr_elem = pStyle_elem.getparent() if pPr_elem is not None: Loading @@ -2389,8 +2397,15 @@ def update_table_rows(docx_input, docx_output): keepnext_elem = etree.Element(f"{{{ns['w']}}}keepNext") keepnext_elem.set(f"{{{ns['w']}}}val", "0") pPr_elem.append(keepnext_elem) first_body_row = True for prev in tr.itersiblings(preceding=True): if prev.tag != f"{{{ns['w']}}}tr": continue if not prev.xpath('./w:trPr/w:tblHeader[@w:val="on"]', namespaces=ns): first_body_row = False break keeplines_elem = etree.Element(f"{{{ns['w']}}}keepLines") keeplines_elem.set(f"{{{ns['w']}}}val", "1") keeplines_elem.set(f"{{{ns['w']}}}val", "0" if first_body_row else "1") pPr_elem.append(keeplines_elem) widowcontrol_elem = etree.Element(f"{{{ns['w']}}}widowControl") widowcontrol_elem.set(f"{{{ns['w']}}}val", "0") Loading Loading @@ -3417,8 +3432,8 @@ def update_references_style(docx_input, docx_output): # Clause 6.2.3, Clause A, or Clause A.1. Figure 6-1 or Figure 6.2-1, Table 7.1-1. # Some text is allowed after the clause citation, such as "Clause 6.2.3 option 1" clause_pattern = re.compile(r'^(?:clauses?|annex(?:es)?)\s+((?:[A-Z]|\d+)(?:\.\d+)*)(?:\s+.*)?$', re.IGNORECASE) figure_pattern = re.compile(r'^figures?\s+\d+(?:\.\d+)*-\d+$', re.IGNORECASE) table_pattern = re.compile(r'^tables?\s+\d+(?:\.\d+)*-\d+$', re.IGNORECASE) figure_pattern = re.compile(r'^figures?\s+(?:[A-Z]+|\d+)(?:\.\d+)*(?:-\d+)?$', re.IGNORECASE) table_pattern = re.compile(r'^tables?\s+(?:[A-Z]+|\d+)(?:\.\d+)*(?:-\d+)?$', re.IGNORECASE) def _bookmark_inner_text(start): bookmark_id = start.get(f"{{{ns['w']}}}id") Loading