Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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:
# <xhtml:div> becomes <div>.
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 `<p>`, `<li>` and `<br/>`, 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 `<br/>`.

See `tests/integration/examples/05_extract_requirement_text` for a complete
example with its input file and expected output.

Expand Down
76 changes: 76 additions & 0 deletions reqif/helpers/xhtml.py
Original file line number Diff line number Diff line change
@@ -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., "<p>First.</p><p>Second.</p>".
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
<p>, <li> or <div>, as well as <br/>, 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 <br/> 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)
25 changes: 25 additions & 0 deletions tests/integration/examples/05_extract_requirement_text/input.reqif
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,26 @@
<SPEC-OBJECT-TYPE-REF>SPEC-OBJECT-TYPE-REQUIREMENT</SPEC-OBJECT-TYPE-REF>
</TYPE>
</SPEC-OBJECT>
<SPEC-OBJECT IDENTIFIER="SPEC-OBJECT-REQ-3" LAST-CHANGE="2026-01-01T00:00:00+00:00" LONG-NAME="Session timeout">
<VALUES>
<ATTRIBUTE-VALUE-STRING THE-VALUE="REQ-3">
<DEFINITION>
<ATTRIBUTE-DEFINITION-STRING-REF>ATTRIBUTE-FOREIGN-ID</ATTRIBUTE-DEFINITION-STRING-REF>
</DEFINITION>
</ATTRIBUTE-VALUE-STRING>
<ATTRIBUTE-VALUE-XHTML>
<DEFINITION>
<ATTRIBUTE-DEFINITION-XHTML-REF>ATTRIBUTE-TEXT</ATTRIBUTE-DEFINITION-XHTML-REF>
</DEFINITION>
<THE-VALUE>
<xhtml:div><xhtml:p>The system <xhtml:b>shall</xhtml:b> end a session after:</xhtml:p><xhtml:ul><xhtml:li>15 minutes without activity, or</xhtml:li><xhtml:li>a logout.</xhtml:li></xhtml:ul></xhtml:div>
</THE-VALUE>
</ATTRIBUTE-VALUE-XHTML>
</VALUES>
<TYPE>
<SPEC-OBJECT-TYPE-REF>SPEC-OBJECT-TYPE-REQUIREMENT</SPEC-OBJECT-TYPE-REF>
</TYPE>
</SPEC-OBJECT>
</SPEC-OBJECTS>
<SPECIFICATIONS>
<SPECIFICATION IDENTIFIER="SPECIFICATION-1" LAST-CHANGE="2026-01-01T00:00:00+00:00" LONG-NAME="System requirements">
Expand All @@ -123,6 +143,11 @@
<SPEC-OBJECT-REF>SPEC-OBJECT-REQ-2</SPEC-OBJECT-REF>
</OBJECT>
</SPEC-HIERARCHY>
<SPEC-HIERARCHY IDENTIFIER="SPEC-HIERARCHY-REQ-3" LAST-CHANGE="2026-01-01T00:00:00+00:00">
<OBJECT>
<SPEC-OBJECT-REF>SPEC-OBJECT-REQ-3</SPEC-OBJECT-REF>
</OBJECT>
</SPEC-HIERARCHY>
</CHILDREN>
</SPEC-HIERARCHY>
</CHILDREN>
Expand Down
11 changes: 1 addition & 10 deletions tests/integration/examples/05_extract_requirement_text/script.py
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
61 changes: 61 additions & 0 deletions tests/unit/reqif/helpers/test_xhtml.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import pytest

from reqif.helpers.xhtml import xhtml_to_plain_text

INDENTED = """
<div>
<p>The system <b>shall</b> lock after:</p>
<ul>
<li>5 attempts, or</li>
<li>admin request.</li>
</ul>
</div>
"""

COMPACT = (
"<div><p>The system <b>shall</b> lock after:</p>"
"<ul><li>5 attempts, or</li><li>admin request.</li></ul></div>"
)


@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."),
("<p>First.</p><p>Second.</p>", "First. Second."),
("<div>Line one<br/>Line two</div>", "Line one Line two"),
("<div>Some <i>inline</i> <b>markup</b>.</div>", "Some inline markup."),
("Plain text only", "Plain text only"),
("Before<p>inside</p>after", "Before inside after"),
("", ""),
("<div></div>", ""),
],
)
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.",
),
("<p>First.</p><p>Second.</p>", "First.\n\nSecond."),
("<div>Line one<br/>Line two</div>", "Line one\nLine two"),
("<div><p>Nested</p></div><div>blocks</div>", "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("<p>Text<!-- note --></p><p>more</p>") == ("Text more")
Loading