diff --git a/README.md b/README.md index 117f842..b14dac4 100644 --- a/README.md +++ b/README.md @@ -55,12 +55,11 @@ A `SPEC-HIERARCHY` node does not contain the requirement itself. It only references a `SPEC-OBJECT` by its identifier (`SPEC-OBJECT-REF`). The `SPEC-OBJECT` stores its attribute values, and the attribute names (for example, `ReqIF.Text`) come from its `SPEC-OBJECT-TYPE`. The values of the XHTML -attributes are XHTML fragments that can be converted to plain text with `lxml`, -which is installed together with `reqif`: +attributes are XHTML fragments that `xhtml_to_plain_text` converts to plain +text: ```py -import lxml.html - +from reqif.helpers.xhtml import xhtml_to_plain_text from reqif.models.reqif_types import SpecObjectAttributeType from reqif.parser import ReqIFParser @@ -77,13 +76,17 @@ for specification in reqif_bundle.core_content.req_if_content.specifications: if attribute.attribute_type == SpecObjectAttributeType.XHTML: # value_stripped_xhtml is the XHTML without the namespace prefix: # becomes
. - text = lxml.html.fromstring(attribute.value_stripped_xhtml).text_content() - value = " ".join(text.split()) + value = xhtml_to_plain_text(attribute.value_stripped_xhtml) else: value = attribute.value print(f" {attribute_name}: {value}") ``` +`xhtml_to_plain_text` collapses the whitespace of the XHTML and separates the +words of block elements such as `

`, `

  • ` and `
    `, even when the XHTML +has no whitespace between the tags. Pass `keep_paragraphs=True` to separate the +blocks with a blank line and to start a new line at each `
    `. + See `tests/integration/examples/05_extract_requirement_text` for a complete example with its input file and expected output. diff --git a/reqif/helpers/xhtml.py b/reqif/helpers/xhtml.py new file mode 100644 index 0000000..89c16c5 --- /dev/null +++ b/reqif/helpers/xhtml.py @@ -0,0 +1,76 @@ +from lxml.html import fragment_fromstring + +# Elements after which the text continues on a new line. Without a break, the +# words of adjacent blocks run together when the XHTML has no whitespace +# between the tags, e.g., "

    First.

    Second.

    ". +BLOCK_TAGS = { + "address", + "blockquote", + "dd", + "div", + "dl", + "dt", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "hr", + "li", + "ol", + "p", + "pre", + "table", + "td", + "th", + "tr", + "ul", +} + +# Markers for the breaks, from the Unicode Private Use Area. lxml does not +# accept control characters in text, and these code points have no meaning in +# requirement text. +_PARAGRAPH_BREAK = "\ue000" +_LINE_BREAK = "\ue001" + + +def xhtml_to_plain_text(xhtml: str, keep_paragraphs: bool = False) -> str: + """ + Convert an XHTML attribute value to plain text. + + The input is an XHTML fragment without namespace prefixes, such as + SpecObjectAttribute.value_stripped_xhtml. The fragment may have several + top-level elements, plain text only, or be empty. + + The whitespace of the XHTML is collapsed, and block elements such as +

    ,

  • or
    , as well as
    , separate the words of adjacent + blocks. + + By default, the result is one line. With keep_paragraphs=True, the + blocks are separated by a blank line and
    starts a new line. + """ + root = fragment_fromstring(xhtml, create_parent="div") + for element in root.iterdescendants(): + if not isinstance(element.tag, str): + # Comments and processing instructions. + continue + tag = element.tag.lower() + if tag == "br": + element.tail = _LINE_BREAK + (element.tail or "") + elif tag in BLOCK_TAGS: + element.text = _PARAGRAPH_BREAK + (element.text or "") + element.tail = _PARAGRAPH_BREAK + (element.tail or "") + text = root.text_content() + + if not keep_paragraphs: + text = text.replace(_PARAGRAPH_BREAK, " ").replace(_LINE_BREAK, " ") + return " ".join(text.split()) + + paragraphs = [] + for paragraph in text.split(_PARAGRAPH_BREAK): + lines = [" ".join(line.split()) for line in paragraph.split(_LINE_BREAK)] + lines = [line for line in lines if line] + if lines: + paragraphs.append("\n".join(lines)) + return "\n\n".join(paragraphs) diff --git a/tests/integration/examples/05_extract_requirement_text/input.reqif b/tests/integration/examples/05_extract_requirement_text/input.reqif index 939de88..91a64dd 100644 --- a/tests/integration/examples/05_extract_requirement_text/input.reqif +++ b/tests/integration/examples/05_extract_requirement_text/input.reqif @@ -101,6 +101,26 @@ SPEC-OBJECT-TYPE-REQUIREMENT + + + + + ATTRIBUTE-FOREIGN-ID + + + + + ATTRIBUTE-TEXT + + + The system shall end a session after:15 minutes without activity, ora logout. + + + + + SPEC-OBJECT-TYPE-REQUIREMENT + + @@ -123,6 +143,11 @@ SPEC-OBJECT-REQ-2 + + + SPEC-OBJECT-REQ-3 + + diff --git a/tests/integration/examples/05_extract_requirement_text/script.py b/tests/integration/examples/05_extract_requirement_text/script.py index 314ce60..5a7fca3 100644 --- a/tests/integration/examples/05_extract_requirement_text/script.py +++ b/tests/integration/examples/05_extract_requirement_text/script.py @@ -1,17 +1,8 @@ # ruff: noqa: T201 -import lxml.html - +from reqif.helpers.xhtml import xhtml_to_plain_text from reqif.models.reqif_types import SpecObjectAttributeType from reqif.parser import ReqIFParser - -def xhtml_to_plain_text(xhtml: str) -> str: - # Keep only the text of the XHTML fragment and collapse the whitespace - # that comes from the indentation of the XHTML tags. - text = lxml.html.fromstring(xhtml).text_content() - return " ".join(text.split()) - - input_file_path = "input.reqif" reqif_bundle = ReqIFParser.parse(input_file_path) diff --git a/tests/integration/examples/05_extract_requirement_text/test.itest b/tests/integration/examples/05_extract_requirement_text/test.itest index 65b6e1c..e300549 100644 --- a/tests/integration/examples/05_extract_requirement_text/test.itest +++ b/tests/integration/examples/05_extract_requirement_text/test.itest @@ -11,6 +11,10 @@ CHECK-NEXT: SPEC-OBJECT: SPEC-OBJECT-REQ-2 CHECK-NEXT: LONG-NAME: Failed logins CHECK-NEXT: ReqIF.ForeignID: REQ-2 CHECK-NEXT: ReqIF.Text: The system shall lock an account after: 5 failed login attempts, or an administrator request. +CHECK-NEXT: SPEC-OBJECT: SPEC-OBJECT-REQ-3 +CHECK-NEXT: LONG-NAME: Session timeout +CHECK-NEXT: ReqIF.ForeignID: REQ-3 +CHECK-NEXT: ReqIF.Text: The system shall end a session after: 15 minutes without activity, or a logout. # The requirement text must be plain text, without any XHTML tags left. RUN: python %S/script.py | filecheck %s --check-prefix=CHECK-PLAIN-TEXT --dump-input=fail diff --git a/tests/unit/reqif/helpers/test_xhtml.py b/tests/unit/reqif/helpers/test_xhtml.py new file mode 100644 index 0000000..49cc73a --- /dev/null +++ b/tests/unit/reqif/helpers/test_xhtml.py @@ -0,0 +1,61 @@ +import pytest + +from reqif.helpers.xhtml import xhtml_to_plain_text + +INDENTED = """ +
    +

    The system shall lock after:

    +
      +
    • 5 attempts, or
    • +
    • admin request.
    • +
    +
    +""" + +COMPACT = ( + "

    The system shall lock after:

    " + "
    • 5 attempts, or
    • admin request.
    " +) + + +@pytest.mark.parametrize( + "xhtml, expected", + [ + (INDENTED, "The system shall lock after: 5 attempts, or admin request."), + (COMPACT, "The system shall lock after: 5 attempts, or admin request."), + ("

    First.

    Second.

    ", "First. Second."), + ("
    Line one
    Line two
    ", "Line one Line two"), + ("
    Some inline markup.
    ", "Some inline markup."), + ("Plain text only", "Plain text only"), + ("Before

    inside

    after", "Before inside after"), + ("", ""), + ("
    ", ""), + ], +) +def test_xhtml_to_plain_text(xhtml, expected): + assert xhtml_to_plain_text(xhtml) == expected + + +@pytest.mark.parametrize( + "xhtml, expected", + [ + ( + INDENTED, + "The system shall lock after:\n\n5 attempts, or\n\nadmin request.", + ), + ( + COMPACT, + "The system shall lock after:\n\n5 attempts, or\n\nadmin request.", + ), + ("

    First.

    Second.

    ", "First.\n\nSecond."), + ("
    Line one
    Line two
    ", "Line one\nLine two"), + ("

    Nested

    blocks
    ", "Nested\n\nblocks"), + ("", ""), + ], +) +def test_xhtml_to_plain_text_keeps_paragraphs(xhtml, expected): + assert xhtml_to_plain_text(xhtml, keep_paragraphs=True) == expected + + +def test_xhtml_to_plain_text_ignores_comments(): + assert xhtml_to_plain_text("

    Text

    more

    ") == ("Text more")