Loading generateBaseline/postprocessing.py +173 −7 Changes for generateBaseline/postprocessing.py: 173 added lines, 7 removed lines. Original line number Diff line number Diff line Loading @@ -2455,6 +2455,36 @@ def update_references(docx_input, docx_output): root = etree.fromstring(xml_data) new_style = "EX" counter = 0 bookmark_ids = root.xpath('.//w:bookmarkStart/@w:id', namespaces=ns) next_bookmark_id = max((int(i) for i in bookmark_ids if str(i).isdigit()), default=0) + 1 used_bookmark_names = set(root.xpath('.//w:bookmarkStart/@w:name', namespaces=ns)) def _unique_ref_bookmark_name(para_text): # REF_ plus letters and digits from the reference title. Word names are at most 40 characters. body = re.sub(r'^\[(?:i\.)?(?:\d+|n)\]\s*', '', para_text, count=1, flags=re.IGNORECASE) if ':' in body: body = body.split(':', 1)[0] slug = re.sub(r'[^A-Za-z0-9]', '', body).upper() or "REF" base = f"REF_{slug}" name = base[:40] if name not in used_bookmark_names: used_bookmark_names.add(name) return name n = 2 while True: suffix = f"_{n}" name = base[:40 - len(suffix)] + suffix if name not in used_bookmark_names: used_bookmark_names.add(name) return name n += 1 def _fld_char_run(fld_char_type): run = OxmlElement('w:r') fld = OxmlElement('w:fldChar') fld.set(qn('w:fldCharType'), fld_char_type) run.append(fld) return run def _paragraph_text_from_runs(para): # Build paragraph text from runs (including runs inside hyperlinks). Loading Loading @@ -2521,13 +2551,80 @@ def update_references(docx_input, docx_output): tab_run = OxmlElement('w:r') tab = OxmlElement('w:tab') tab_run.append(tab) # Bookmark the reference label and add a SEQ field around the number, # with the bookmark end immediately before the tab run. # Informative [i.1] keeps "i." in front of the field; normative [1] is the field result. # The existing bookmark is left in place. label_elem = None label_text = "" for text_elem in reference_run.xpath('.//w:t', namespaces=ns): if text_elem.text: label_elem = text_elem label_text = text_elem.text break informative = bool(re.match(r'\[i\.', label_text)) number_match = re.search(r'(?:\[i\.|\[)(\d+|n)\]', label_text) number = number_match.group(1) if number_match else label_text seq_instr = ' SEQ REFI ' if informative else ' SEQ REF ' if label_elem is not None and not informative: label_elem.text = number bookmark_id = str(next_bookmark_id) next_bookmark_id += 1 bookmark_start_elem = OxmlElement('w:bookmarkStart') bookmark_start_elem.set(qn('w:id'), bookmark_id) bookmark_start_elem.set(qn('w:name'), _unique_ref_bookmark_name(para_text)) seq_run = OxmlElement('w:r') instr = OxmlElement('w:instrText') instr.set('{http://www.w3.org/XML/1998/namespace}space', 'preserve') instr.text = seq_instr seq_run.append(instr) bookmark_end_elem = OxmlElement('w:bookmarkEnd') bookmark_end_elem.set(qn('w:id'), bookmark_id) begin_run = _fld_char_run('begin') separate_run = _fld_char_run('separate') end_run = _fld_char_run('end') # Insert the tab run as a sibling right after the reference_run parent = reference_run.getparent() if parent is not None: ref_index = list(parent).index(reference_run) parent.insert(ref_index + 1, tab_run) rPr = reference_run.find(qn('w:rPr')) def _text_run(text): run = OxmlElement('w:r') if rPr is not None: run.append(etree.fromstring(etree.tostring(rPr))) text_elem = OxmlElement('w:t') text_elem.text = text run.append(text_elem) return run close_bracket_run = _text_run(']') if informative and label_elem is not None: label_elem.text = '[i.' result_run = _text_run(number) parent.insert(ref_index, bookmark_start_elem) parent.insert(ref_index + 2, begin_run) parent.insert(ref_index + 3, seq_run) parent.insert(ref_index + 4, separate_run) parent.insert(ref_index + 5, result_run) parent.insert(ref_index + 6, end_run) parent.insert(ref_index + 7, close_bracket_run) parent.insert(ref_index + 8, bookmark_end_elem) parent.insert(ref_index + 9, tab_run) next_index = ref_index + 10 else: open_bracket_run = _text_run('[') parent.insert(ref_index, bookmark_start_elem) parent.insert(ref_index + 1, open_bracket_run) parent.insert(ref_index + 2, begin_run) parent.insert(ref_index + 3, seq_run) parent.insert(ref_index + 4, separate_run) parent.insert(ref_index + 6, end_run) parent.insert(ref_index + 7, close_bracket_run) parent.insert(ref_index + 8, bookmark_end_elem) parent.insert(ref_index + 9, tab_run) next_index = ref_index + 10 # Trim any space in the next w:r/w:t element after the tab run next_index = ref_index + 2 if next_index < len(parent): next_elem = parent[next_index] if next_elem.tag.endswith('}r') and next_elem.xpath('.//w:t', namespaces=ns): Loading Loading @@ -2805,11 +2902,38 @@ def update_references_style(docx_input, docx_output): root = etree.fromstring(xml_data) new_style = "Normal" counter = 0 field_counter = 0 # Pattern to match internal references: [i.1] or [1] or [i.12] or [12] reference_pattern = re.compile(r'^\[(i\.)?\d+\]$', re.IGNORECASE) # Old declaration bookmark name -> REF_ bookmark added by update_references. # The old bookmarks stay in the document. anchor_to_ref = {} for para in root.xpath('.//w:p', namespaces=ns): ref_names = [] old_names = [] for start in para.xpath('./w:bookmarkStart', namespaces=ns): name = start.get(f"{{{ns['w']}}}name") if not name: continue if name.startswith('REF_'): ref_names.append(name) else: old_names.append(name) if len(ref_names) == 1: for old_name in old_names: anchor_to_ref[old_name] = ref_names[0] def _fld_run(fld_char_type): run = OxmlElement('w:r') fld = OxmlElement('w:fldChar') fld.set(qn('w:fldCharType'), fld_char_type) run.append(fld) return run # Loop over all elements to find "Hyperlink" and change to "Normal" pending_fields = [] for elem in root.xpath('.//w:rStyle[@w:val="Hyperlink"]', namespaces=ns): # Change the style to "Normal" if it is an internal reference (matches \[(i\.)?\d+\]) rPr = elem.getparent() Loading @@ -2818,21 +2942,63 @@ def update_references_style(docx_input, docx_output): r = rPr.getparent() if r is None: continue para = r.getparent() if para is None: hyperlink = r.getparent() if hyperlink is None: continue if para.tag != f"{{{ns['w']}}}hyperlink": if hyperlink.tag != f"{{{ns['w']}}}hyperlink": continue t = r.xpath(".//w:t", namespaces=ns) if not t: continue full_text = "".join((text_elem.text or "") for text_elem in t).strip() raw_text = "".join((text_elem.text or "") for text_elem in t) full_text = raw_text.strip() if not reference_pattern.match(full_text): continue if reference_pattern.match(full_text): elem.set(f"{{{ns['w']}}}val", new_style) counter += 1 anchor = hyperlink.get(f"{{{ns['w']}}}anchor") ref_name = anchor_to_ref.get(anchor) if ref_name: pending_fields.append((hyperlink, rPr, raw_text, ref_name)) for hyperlink, rPr, raw_text, ref_name in pending_fields: parent = hyperlink.getparent() if parent is None: continue index = list(parent).index(hyperlink) inner_text = raw_text.strip() if inner_text.startswith('[') and inner_text.endswith(']'): inner_text = inner_text[1:-1] def _text_run(text): run = OxmlElement('w:r') run.append(etree.fromstring(etree.tostring(rPr))) text_elem = OxmlElement('w:t') text_elem.text = text run.append(text_elem) return run begin_run = _fld_run('begin') instr_run = OxmlElement('w:r') instr = OxmlElement('w:instrText') instr.set('{http://www.w3.org/XML/1998/namespace}space', 'preserve') instr.text = f' REF {ref_name} \\h \\* MERGEFORMAT ' instr_run.append(instr) separate_run = _fld_run('separate') result_hyperlink = OxmlElement('w:hyperlink') result_hyperlink.set(qn('w:anchor'), ref_name) result_hyperlink.set(qn('w:history'), '1') result_hyperlink.append(_text_run(inner_text)) end_run = _fld_run('end') parent.remove(hyperlink) for offset, elem in enumerate((_text_run('['), begin_run, instr_run, separate_run, result_hyperlink, end_run, _text_run(']'))): parent.insert(index + offset, elem) field_counter += 1 print(f'Changed style "Hyperlink" to "Normal" {counter} times') print(f'Replaced reference hyperlinks with REF fields {field_counter} times') xml_data = etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone="yes") Loading Loading
generateBaseline/postprocessing.py +173 −7 Changes for generateBaseline/postprocessing.py: 173 added lines, 7 removed lines. Original line number Diff line number Diff line Loading @@ -2455,6 +2455,36 @@ def update_references(docx_input, docx_output): root = etree.fromstring(xml_data) new_style = "EX" counter = 0 bookmark_ids = root.xpath('.//w:bookmarkStart/@w:id', namespaces=ns) next_bookmark_id = max((int(i) for i in bookmark_ids if str(i).isdigit()), default=0) + 1 used_bookmark_names = set(root.xpath('.//w:bookmarkStart/@w:name', namespaces=ns)) def _unique_ref_bookmark_name(para_text): # REF_ plus letters and digits from the reference title. Word names are at most 40 characters. body = re.sub(r'^\[(?:i\.)?(?:\d+|n)\]\s*', '', para_text, count=1, flags=re.IGNORECASE) if ':' in body: body = body.split(':', 1)[0] slug = re.sub(r'[^A-Za-z0-9]', '', body).upper() or "REF" base = f"REF_{slug}" name = base[:40] if name not in used_bookmark_names: used_bookmark_names.add(name) return name n = 2 while True: suffix = f"_{n}" name = base[:40 - len(suffix)] + suffix if name not in used_bookmark_names: used_bookmark_names.add(name) return name n += 1 def _fld_char_run(fld_char_type): run = OxmlElement('w:r') fld = OxmlElement('w:fldChar') fld.set(qn('w:fldCharType'), fld_char_type) run.append(fld) return run def _paragraph_text_from_runs(para): # Build paragraph text from runs (including runs inside hyperlinks). Loading Loading @@ -2521,13 +2551,80 @@ def update_references(docx_input, docx_output): tab_run = OxmlElement('w:r') tab = OxmlElement('w:tab') tab_run.append(tab) # Bookmark the reference label and add a SEQ field around the number, # with the bookmark end immediately before the tab run. # Informative [i.1] keeps "i." in front of the field; normative [1] is the field result. # The existing bookmark is left in place. label_elem = None label_text = "" for text_elem in reference_run.xpath('.//w:t', namespaces=ns): if text_elem.text: label_elem = text_elem label_text = text_elem.text break informative = bool(re.match(r'\[i\.', label_text)) number_match = re.search(r'(?:\[i\.|\[)(\d+|n)\]', label_text) number = number_match.group(1) if number_match else label_text seq_instr = ' SEQ REFI ' if informative else ' SEQ REF ' if label_elem is not None and not informative: label_elem.text = number bookmark_id = str(next_bookmark_id) next_bookmark_id += 1 bookmark_start_elem = OxmlElement('w:bookmarkStart') bookmark_start_elem.set(qn('w:id'), bookmark_id) bookmark_start_elem.set(qn('w:name'), _unique_ref_bookmark_name(para_text)) seq_run = OxmlElement('w:r') instr = OxmlElement('w:instrText') instr.set('{http://www.w3.org/XML/1998/namespace}space', 'preserve') instr.text = seq_instr seq_run.append(instr) bookmark_end_elem = OxmlElement('w:bookmarkEnd') bookmark_end_elem.set(qn('w:id'), bookmark_id) begin_run = _fld_char_run('begin') separate_run = _fld_char_run('separate') end_run = _fld_char_run('end') # Insert the tab run as a sibling right after the reference_run parent = reference_run.getparent() if parent is not None: ref_index = list(parent).index(reference_run) parent.insert(ref_index + 1, tab_run) rPr = reference_run.find(qn('w:rPr')) def _text_run(text): run = OxmlElement('w:r') if rPr is not None: run.append(etree.fromstring(etree.tostring(rPr))) text_elem = OxmlElement('w:t') text_elem.text = text run.append(text_elem) return run close_bracket_run = _text_run(']') if informative and label_elem is not None: label_elem.text = '[i.' result_run = _text_run(number) parent.insert(ref_index, bookmark_start_elem) parent.insert(ref_index + 2, begin_run) parent.insert(ref_index + 3, seq_run) parent.insert(ref_index + 4, separate_run) parent.insert(ref_index + 5, result_run) parent.insert(ref_index + 6, end_run) parent.insert(ref_index + 7, close_bracket_run) parent.insert(ref_index + 8, bookmark_end_elem) parent.insert(ref_index + 9, tab_run) next_index = ref_index + 10 else: open_bracket_run = _text_run('[') parent.insert(ref_index, bookmark_start_elem) parent.insert(ref_index + 1, open_bracket_run) parent.insert(ref_index + 2, begin_run) parent.insert(ref_index + 3, seq_run) parent.insert(ref_index + 4, separate_run) parent.insert(ref_index + 6, end_run) parent.insert(ref_index + 7, close_bracket_run) parent.insert(ref_index + 8, bookmark_end_elem) parent.insert(ref_index + 9, tab_run) next_index = ref_index + 10 # Trim any space in the next w:r/w:t element after the tab run next_index = ref_index + 2 if next_index < len(parent): next_elem = parent[next_index] if next_elem.tag.endswith('}r') and next_elem.xpath('.//w:t', namespaces=ns): Loading Loading @@ -2805,11 +2902,38 @@ def update_references_style(docx_input, docx_output): root = etree.fromstring(xml_data) new_style = "Normal" counter = 0 field_counter = 0 # Pattern to match internal references: [i.1] or [1] or [i.12] or [12] reference_pattern = re.compile(r'^\[(i\.)?\d+\]$', re.IGNORECASE) # Old declaration bookmark name -> REF_ bookmark added by update_references. # The old bookmarks stay in the document. anchor_to_ref = {} for para in root.xpath('.//w:p', namespaces=ns): ref_names = [] old_names = [] for start in para.xpath('./w:bookmarkStart', namespaces=ns): name = start.get(f"{{{ns['w']}}}name") if not name: continue if name.startswith('REF_'): ref_names.append(name) else: old_names.append(name) if len(ref_names) == 1: for old_name in old_names: anchor_to_ref[old_name] = ref_names[0] def _fld_run(fld_char_type): run = OxmlElement('w:r') fld = OxmlElement('w:fldChar') fld.set(qn('w:fldCharType'), fld_char_type) run.append(fld) return run # Loop over all elements to find "Hyperlink" and change to "Normal" pending_fields = [] for elem in root.xpath('.//w:rStyle[@w:val="Hyperlink"]', namespaces=ns): # Change the style to "Normal" if it is an internal reference (matches \[(i\.)?\d+\]) rPr = elem.getparent() Loading @@ -2818,21 +2942,63 @@ def update_references_style(docx_input, docx_output): r = rPr.getparent() if r is None: continue para = r.getparent() if para is None: hyperlink = r.getparent() if hyperlink is None: continue if para.tag != f"{{{ns['w']}}}hyperlink": if hyperlink.tag != f"{{{ns['w']}}}hyperlink": continue t = r.xpath(".//w:t", namespaces=ns) if not t: continue full_text = "".join((text_elem.text or "") for text_elem in t).strip() raw_text = "".join((text_elem.text or "") for text_elem in t) full_text = raw_text.strip() if not reference_pattern.match(full_text): continue if reference_pattern.match(full_text): elem.set(f"{{{ns['w']}}}val", new_style) counter += 1 anchor = hyperlink.get(f"{{{ns['w']}}}anchor") ref_name = anchor_to_ref.get(anchor) if ref_name: pending_fields.append((hyperlink, rPr, raw_text, ref_name)) for hyperlink, rPr, raw_text, ref_name in pending_fields: parent = hyperlink.getparent() if parent is None: continue index = list(parent).index(hyperlink) inner_text = raw_text.strip() if inner_text.startswith('[') and inner_text.endswith(']'): inner_text = inner_text[1:-1] def _text_run(text): run = OxmlElement('w:r') run.append(etree.fromstring(etree.tostring(rPr))) text_elem = OxmlElement('w:t') text_elem.text = text run.append(text_elem) return run begin_run = _fld_run('begin') instr_run = OxmlElement('w:r') instr = OxmlElement('w:instrText') instr.set('{http://www.w3.org/XML/1998/namespace}space', 'preserve') instr.text = f' REF {ref_name} \\h \\* MERGEFORMAT ' instr_run.append(instr) separate_run = _fld_run('separate') result_hyperlink = OxmlElement('w:hyperlink') result_hyperlink.set(qn('w:anchor'), ref_name) result_hyperlink.set(qn('w:history'), '1') result_hyperlink.append(_text_run(inner_text)) end_run = _fld_run('end') parent.remove(hyperlink) for offset, elem in enumerate((_text_run('['), begin_run, instr_run, separate_run, result_hyperlink, end_run, _text_run(']'))): parent.insert(index + offset, elem) field_counter += 1 print(f'Changed style "Hyperlink" to "Normal" {counter} times') print(f'Replaced reference hyperlinks with REF fields {field_counter} times') xml_data = etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone="yes") Loading