Repository navigation
rfctr(html): replace html parser - #3218
Conversation
105fa52 to
16ade6e
Compare
16ade6e to
df885d6
Compare
df885d6 to
8e136e7
Compare
8e136e7 to
fde32a2
Compare
fde32a2 to
80f3808
Compare
80f3808 to
fb6eb31
Compare
1567c91 to
fa5dba3
Compare
fa5dba3 to
51d5519
Compare
e2ca119 to
5c85c6d
Compare
|
Hi! @scanny great improvement! def iter_text_segments(self, text: str) -> Iterator[TextSegment]:when call in Phrasing: def _iter_child_text_segments(self, emphasis: str) -> Iterator[TextSegment]:
"""Generate zero-or-more text-segments for phrasing children of this element.
All generated text segments will be annotated with `emphasis` when it is other than the
empty string.
"""
for child in self:
yield from child.iter_text_segments(emphasis)best regards, |
|
Hi @heralight, thanks! :) Can you provide a (real-life) HTML snippet that triggers a problem with that? An In general, phrasing elements cannot themselves contain block elements (so this method would not be called on a I don't need a whole document and don't care what the text is. A small fragment like this will do the trick: <div>
Text of div <b>with <i>hierarchical</i>\nphrasing</b> content before first block item
<p>Click <a href="http://blurb.io">here</a> to see the blurb for this block item. </p>
tail of block item <b>with <i>hierarchical</i> phrasing </b> content
</div> |
|
@heralight btw, I expect shortly we will add that method to I wanted to leave it as an error at first here to try to flush out any legitimate examples where I've mis-classified a flow element as phrasing or missed an element that can take either block or inline display-role depending on its placement. |
|
@scanny , a basic sample is: <a>
<div>
</div>
</a>I found it in a real mainstream website like: <a>
<div class="relative inline-flex">
<span data-spark-component="badge" role="status"></span>
</div><span class="text-caption">Checkout</span>
<!-- a lot of other elements (arround 30)-->
</a>my current workarround is to add: def iter_text_segments(self, text: str) -> Iterator[TextSegment]:
yield TextSegment(text, {})to Flow |
|
@heralight Ah, okay, this is a very helpful example. It occurred to me we might need to be more sophisticated in how we handle anchor ( Here's the solution I think makes sense for this case:
I'm thinking this is the first of a "dual-role" category of element-types. Not sure yet whether it's the only one but I expect there are others. I've just spiked that out and it's a very small change, so I'll add tests for it and add it to this PR. With that change, this code: from unstructured.partition.html import partition_html
from unstructured.staging.base import elements_to_json
html_text = """
<div>
“O Deep Thought computer," he said,
<a>
<div>The task we have designed you to perform is this.</div>
<p>We want you to tell us.... he paused,"</p>
</a>
</div>
"""
elements = partition_html(text=html_text)
print(f"{elements_to_json(elements, indent=2)}")produces these elements: [
{
"element_id": "658df72fa2c379d60e265845e5ceb654",
"metadata": {
"filetype": "text/html",
"languages": ["eng"]
},
"text": "\u201cO Deep Thought computer,\" he said,",
"type": "NarrativeText"
},
{
"element_id": "4cfbb7b43a83e28c32c8186e4c804b58",
"metadata": {
"filetype": "text/html",
"languages": ["eng"]
},
"text": "The task we have designed you to perform is this.",
"type": "NarrativeText"
},
{
"element_id": "ed2fa97fc8314fb9b36c2177faf848d8",
"metadata": {
"filetype": "text/html",
"languages": ["eng"]
},
"text": "We want you to tell us.... he paused,\"",
"type": "NarrativeText"
}
] |
|
@scanny make sense! |
| owards one another in a spirit of brotherhood. All human beings are born fr= | ||
| ee and equal in dignity and rights. They are endowed with reason and consci= | ||
| ence and should act towards one another in a spirit of brotherhood.<br><br>= | ||
| ence and should act towards one another in a spirit of brotherhood. <p> = |
There was a problem hiding this comment.
Was the example doc here supposed to change?
There was a problem hiding this comment.
This email is used by the test that verifies the detect_language_per_element behaviors for EML. That test depends on the body of this email resolving to distinct paragraphs so it can verify each Element (paragraph) was assigned a language separately.
The original HTML text of this email is not separate paragraphs, it just "looks" like separate paragraphs. So that test started failing.
It's a legitimate question whether we want to "double-parse" <div> elements like this one and consider <br/><br/> to be a paragraph boundary. But that's not the behavior this email's test is verifying so I went with the element change.
MthwRobinson
left a comment
There was a problem hiding this comment.
Added inline comments for an initial review.
@amanda103 or @cragwolfe - do you have any input on the behavior changes in the PR description?
| '<div dir=3D"ltr">Hi All,\n' | ||
| " <div><br></div>\n" | ||
| " <div>Get excited for our first annual family day!</div>\n" | ||
| ' <div>Best.<br clear=3D"all">\n' |
There was a problem hiding this comment.
Was this supposed to have changed?
There was a problem hiding this comment.
Hmm, definitely didn't need to change. I don't know why it did. =3D is a synonym for = and is only used in email as far as I know. I could add it back if you want. Otherwise it's a random test that both variants work :)
| "element_id": "568c824acda361cfc270a75e2eca7a23", | ||
| "text": "Weather.gov >", | ||
| "element_id": "6ef25d028f4c859b5d955c777c4c597e", | ||
| "text": "Weather.gov > News Around NOAA > Are You Weather-Ready for the Spring?", |
There was a problem hiding this comment.
This looks like a good change to me, with link texts captured below
There was a problem hiding this comment.
Yeah, the HTML behind this looks like this:
<div>
<a href="https://www.weather.gov">Weather.gov</a>
> <a href="https://www.weather.gov/news">News Around NOAA</a>
> Are You Weather-Ready for the Spring?
</div>All the content of the <div> is phrasing (inline) content so it's all considered the same paragraph and therefore Element.
The old parser would break the paragraph/element when there were two <a> elements in succession.
That's sometimes the right choice, but only when the <a> element is itself surrounding a block element like <div> or <p>.
| ], | ||
| "emphasized_text_tags": [ | ||
| "strong" | ||
| "b" |
| @@ -1,8 +1,9 @@ | |||
| ## 0.14.8-dev3 | |||
| ## 0.14.8-dev4 | |||
There was a problem hiding this comment.
Let's bump to 0.15.0 when we release this since it's a major change.
|
|
||
| # -- the first non-whitespace phrase or element gets the link annotation -- | ||
| while q: | ||
| print(f"{q=}") |
There was a problem hiding this comment.
Testing out in the API - this print is pretty noisy.
There was a problem hiding this comment.
Oooh, that's not supposed to be there! Good catch, thanks @awalker4 :)
| @@ -1,8 +1,9 @@ | |||
| ## 0.14.11-dev0 | |||
| ## 0.14.11-dev1 | |||
There was a problem hiding this comment.
Reminder to bump to 0.15.0
MthwRobinson
left a comment
There was a problem hiding this comment.
LGTM from my end once you bump the version and fix the merge conflicts.
Adjust unit tests that relied on behaviors changed by the new HTML parser.
These differences have all been accounted for by bug-fixes and desired behavior changes of the new HTML parser.
Summary
Replace legacy HTML parser with recursive version that captures all content and provides flexibility to add new metadata. It's also substantially faster although that's just a happy side-effect.
Additional Context
The prior HTML parsing algorithm that makes up the core of HTML partitioning was buggy and very difficult to reason about because it did not conform to the inherently recursive structure of HTML. The new version retains
lxmlas the performant and reliable base library but useslxml's custom element classes to efficiently classify HTML elements by their behaviors (block-item and inline (phrasing) primarily) and give those elements the desired partitioning behaviors.This solves a host of existing problems with content being skipped and elements (paragraphs) being divided improperly, but also provides a clear domain model for reasoning about its behavior and reliably adjusting it to suit our existing and future purposes.
The parser's operation is recursive, closely modeling the recursive structure of HTML itself. It's behaviors are based on the HTML Standard and reliably produce proper and explainable results even for novel cases.
Fixes #2325
Fixes #2562
Fixes #2675
Fixes #3168
Fixes #3227
Fixes #3228
Fixes #3230
Fixes #3237
Fixes #3245
Fixes #3247
Fixes #3255
Fixes #3309
BEHAVIOR DIFFERENCES
emphasized_text_tagsencoding is changed:<strong>is encoded as"b"rather than"strong".<em>is encoded as"i"rather than"em".<span>is no longer recorded inemphasized_text_tags(because without the CSS we can't tell whether it's used for emphasis or if so what kind).emphasized_text_contentsis broken on emphasis-change boundaries, like:{ "emphasized_text_contents": ["bar", "baz", "bada"], "emphasized_text_tags": ["b", "bi", "b"] }{ "emphasized_text_contents": ["bar baz bada", "baz"], "emphasized_text_tags": ["b", "i"] }<pre>text is preserved as it appears in the htmlExcept that a leading newline is removed if present (has to be in position 0 of text). Also, a trailing newline is stripped but only if it appears in the very last position ([-1]) of the
<pre>text. Old parser stripped all leading and trailing whitespace.Result is that:
parses to
"foo\nbar\nbaz"which is the same result produced for:This equivalence is the same behavior exhibited by a browser, which is why we did the extra work to make it this way.
Whitespace normalization
Leading and trailing whitespace are removed from element text, just as it is removed in the browser. Runs of whitespace within the element text are reduced to a single space character (like in the browser). Note this means that
\t,\n, and are replaced with a regular space character. All text derived from elements is whitespace normalized except the text within a<pre>tag. Any leading or trailing newline is trimmed from<pre>element text; all other whitespace is preserved just as it appeared in the HTML source.link_start_indexesmetadata is no longer captured. Rationale:-1.<br/>element is replaced with a single newline ("\n")but that is usually replaced with a space in
Element.textwhen it is normalized. The newline is preserved within a<pre>element.<br/><br/>Empty
h1..h6elements are dropped.HTML heading elements (
<h1..h6>) are "skipped" (do not generate aTitleelement) when they contain no text or contain only whitespace.