unstructured icon indicating copy to clipboard operation
unstructured copied to clipboard

bug/partition_html only partially extracts text of element with nested inline tag

Open dgunning opened this issue 2 years ago • 22 comments

Describe the bug When a html contains a div with a nested tag e.g. a b or span, the element created from the div contains only the text up to the inline element.

This is likely a behaviour of lxml related to these issues

To Reproduce

html = """
<html>
<body>
    <div>
    the Company issues shares at $<div style="display:inline;"><span>5.22</span></div> per share. 
    There is more text
    </div>
</body>
</html>
"""

elements = partition_html(text=html)
print(''.join(e.text for e in elements))

This results in

"the Company issues shares at $5.22"

Expected behavior The following should be printed

"the Company issues shares at $5.22 per share. There is more text"

Screenshots

Environment Info Please run python scripts/collect_env.py and paste the output here. This will help us understand more about the environment in which the bug occurred.

Additional context Add any other context about the problem here.

dgunning avatar Jan 07 '24 23:01 dgunning

1704791657913

same issue with it

kingle-zhuang avatar Jan 09 '24 09:01 kingle-zhuang

missing in the left navigation bar

kingle-zhuang avatar Jan 09 '24 09:01 kingle-zhuang

Some examples from the community not using <div> but <br>:

>>> str(partition_html(text='<p>abc <a href="somewhere">def</a><br><strong></strong><strong>ghi</strong></p>')[0])
'abc'
>>> str(partition_html(text='<p>abc <a href="somewhere">def</a><br>ghi</p>')[0])
'abc'
>>> str(partition_html(text='<p>abc <br>ghi</p>')[0])
'abc'
>>> str(partition_html(text='<p>abc ghi</p>')[0])
'abc ghi'
>>> str(partition_html(text='<p>abc <a href="somewhere">def</a> ghi</p>')[0])
'abc def ghi'
>>> str(partition_html(text='<p>abc <br/>ghi</p>')[0])
'abc'

ref: community slack thread

LaverdeS avatar Jan 16 '24 14:01 LaverdeS

more examples

>>> print([str(x) for x in partition_html(text="<div><ul><li>a</li></ul> b </div>")])
['a']

with quoting in the mix

>>> print([str(x) for x in partition_html(text="<div><ul><li>a</li></ul> b <a href='something'>c</a></div>")])
['a']
>>> print([str(x) for x in partition_html(text="<div><ul><li>a</li></ul> b '<a href='something'>c</a>'</div>")])
['a', "c'"]

stdweird avatar Jan 17 '24 08:01 stdweird

Hey everyone,

I've looked at the HTML parser and think I found a solution. But I don't fully understand the intention of the original code.

Source of the problem

The problem is with etree and the html parser as mentioned here https://stackoverflow.com/questions/4770191/lxml-etree-element-text-doesnt-return-the-entire-text-from-an-element The .text property doesn't return the full text of an element and in general is kinda weird. Used here: https://github.com/Unstructured-IO/unstructured/blob/7378a378f65f8f59304e5a20164bc44fbe3c03dd/unstructured/documents/html.py#L187

Now to what I don't understand in the original code: Was it intended that tag_elem.text should return the Company issues shares at $5.22 per share. \n There is more text?
And the emphasized_texts contains a list of containing string? (Which can be achieved with tag_elem.xpath("string()"))

Or should the .text only include the Company issues shares at $ per share. \n There is more text without the 5.22 span. Anyway, if it doesn't include the 5.22 the ordering of the elements becomes difficult. (this could be achieved with tag_elem.xpath("text()") and join the strings)

Solution

If we just drop in replace the tag_elem.text with tag_elem.xpath("string()") this has the problem that the output becomes:

[ `the Company issues shares at $5.22 per share. \n There is more text`, `5.22`]

as the span is a next element in article.iter().

To solve this, the function _get_emphasized_texts_from_tag(tag_elem) could return the found emphasized texts and add them to the descendanttag_elems. https://github.com/Unstructured-IO/unstructured/blob/7378a378f65f8f59304e5a20164bc44fbe3c03dd/unstructured/documents/html.py#L183

To something like this:

emphasized_texts, found_tag_elements = _get_emphasized_texts_from_tag(tag_elem)
descendanttag_elems = descendanttag_elems + tuple(found_tag_elements)

with this function:

https://github.com/Unstructured-IO/unstructured/blob/7378a378f65f8f59304e5a20164bc44fbe3c03dd/unstructured/documents/html.py#L372

def _get_emphasized_texts_from_tag(tag_elem: etree._Element) -> List[Dict[str, str]]:
    """Emphasized text within and below `tag_element`.

    Emphasis is indicated by `<strong>`, `<em>`, `<span>`, `<b>`, `<i>` tags.
    """
    emphasized_texts: List[Dict[str, str]] = []
    tags_to_track = ["strong", "em", "span", "b", "i"]

    if tag_elem.tag in tags_to_track:
        text = _construct_text(tag_elem, False)
        if text:
            emphasized_texts.append({"text": text, "tag": tag_elem.tag})

    found_tag_elements = []
    for descendant_tag_elem in tag_elem.iterdescendants(*tags_to_track):
        text = _construct_text(descendant_tag_elem, False)
        if text:
            emphasized_texts.append({"text": text, "tag": descendant_tag_elem.tag})
            found_tag_elements.append(descendant_tag_elem)

    return emphasized_texts, found_tag_elements

I've modified the remaining occurrences of _get_emphasized_texts_from_tag to ignore the second return value, and it seems to work as intended.

Could someone from unstructured test that?

FAbrahamDev avatar Jan 19 '24 14:01 FAbrahamDev

It should return the Company issues shares at $5.22 per share. \n There is more text

Looks like you are on the right track. However, would it handle divs styled as inline?

<div>This is a parent with<div style='display:inline'>INLINE TEXT</div></div>

dgunning avatar Jan 19 '24 15:01 dgunning

@dgunning what do you expect as output there? @FAbrahamDev i think that one other issue is that using .text in etree elements, should always keep in mind to also deal with the .tail part. see eg https://stackoverflow.com/questions/4770191/lxml-etree-element-text-doesnt-return-the-entire-text-from-an-element

stdweird avatar Jan 21 '24 09:01 stdweird

@stdweird ignore the last comment .. it works for inline divs

def partition(text):
    elements = partition_html(text=text)
    return ''.join(e.text for e in elements)

partition('<div>The company issued a dividend of <div style="display:inline">$5.00</div> per share</div>')

The company issued a dividend of $5.00 per share

dgunning avatar Jan 21 '24 16:01 dgunning

@dgunning what do you expect as output there? @FAbrahamDev i think that one other issue is that using .text in etree elements, should always keep in mind to also deal with the .tail part. see eg https://stackoverflow.com/questions/4770191/lxml-etree-element-text-doesnt-return-the-entire-text-from-an-element

Given the outputs of the different approaches commented by demented hedgehog, I don't understand the difference between root.xpath("string()") and the tail approach.

@dgunning Thank you for checking it. I did not find any time over the weekend. But it seems to do what was intended?

FAbrahamDev avatar Jan 22 '24 08:01 FAbrahamDev

@FAbrahamDev i don't think there is any difference ;) it looks like to get text with etree one should use .xpath("string()") or some weird combinatio of .text and .tail

i would however prefer to add a wrapper function _text_from_etree_element and use that where needed; instead of repacing .text with .xpath(...). one never knows what other cases we will need to handle.

and unittests ;)

stdweird avatar Jan 22 '24 08:01 stdweird

I've tested @dgunnings example:

<div>This is a parent with<div style='display:inline'>INLINE TEXT</div></div>

But get a different result: This is a parent withINLINE TEXTINLINE TEXT Because the containing div is not found in _get_emphasized_texts_from_tag, because it's not one of <strong>, <em>, <span>, <b>, <i>.

I'm not sure what's the correct approach in this example.

Maybe depending on the return value of _get_emphasized_texts_from_tag use .text otherwise use .xpath or your wrapper.

One could also check if .text and the .xpath approach yield the same solution, which would mean that there is an element inside which needs to be found and excluded for the next iteration?

I think for the purpose of this repo, extracting more in edge cases is better than missing text.

FAbrahamDev avatar Jan 22 '24 10:01 FAbrahamDev

When we are at it:

<div>
    <span>MISSING TEXT.<p>FOUND TEXT <p>1.<p>2.<p>3.<p>4.<p>5.</p></p></p></p></p></p></span>
</div>

I found another example where the MISSING TEXT is not included in the output if there are too many nested tags. When I remove the

5.

tag, the missing text is included again.

I do believe that this is intended given the comments in the code, but I think it should probably be reconsidered given that the amount of tags doesn't mean anything for the content length. I'd prefer if there is a bigger content piece that the chunker should handle the splitting and not a depth check in the HTML.

FAbrahamDev avatar Jan 22 '24 10:01 FAbrahamDev

@FAbrahamDev :+1: on making the depth configurable.

stdweird avatar Jan 22 '24 12:01 stdweird

@FAbrahamDev do you happen to have a patch or PR for this? i would like to give it a try

stdweird avatar Jan 24 '24 12:01 stdweird

this is confusing me a lot. i added some debug prints

def dbel(el, msg, lvl=2):                                                                                                                                               
    print("  "*lvl, msg, el, 'text', el.text, 'tail', el.tail, 'string', el.xpath("string()")) 

and now have

 python -c 'from unstructured.partition.html import partition_html;print([str(x) for x in partition_html(text="<html><body><div>a<ul>b<li>c1</li>d1<li>c2</li>d2</ul>e</div>f<br>g</body></html>")])'
 article <Element html at 0x7fbf585c2300> text None tail None string abc1d1c2d2efg
   article 0 <Element html at 0x7fbf585c2300> text None tail None string abc1d1c2d2efg
     _is_container_with_text <Element html at 0x7fbf585c2300> text None tail None string abc1d1c2d2efg
   article 1 <Element body at 0x7fbf245005c0> text None tail None string abc1d1c2d2efg
     _is_container_with_text <Element body at 0x7fbf245005c0> text None tail None string abc1d1c2d2efg
   article 2 <Element div at 0x7fbf24526d00> text a tail f string abc1d1c2d2e
     _has_adjacent_bulleted_spans children0 <Element ul at 0x7fbf24526b40> text b tail e string bc1d1c2d2
     _is_container_with_text <Element div at 0x7fbf24526d00> text a tail f string abc1d1c2d2e
     _get_links_from_tag <Element div at 0x7fbf24526d00> text a tail f string abc1d1c2d2e
     _is_container_with_text YES <Element div at 0x7fbf24526d00> text a tail f string abc1d1c2d2e
   article 3 <Element ul at 0x7fbf24526b40> text b tail e string bc1d1c2d2
     _is_container_with_text <Element ul at 0x7fbf24526b40> text b tail e string bc1d1c2d2
   article 4 <Element li at 0x7fbf245005c0> text c1 tail d1 string c1
     _is_container_with_text <Element li at 0x7fbf245005c0> text c1 tail d1 string c1
     _construct_text <Element li at 0x7fbf245005c0> text c1 tail d1 string c1
     _get_links_from_tag <Element li at 0x7fbf245005c0> text c1 tail d1 string c1
   article 5 <Element li at 0x7fbf24526c00> text c2 tail d2 string c2
     _is_container_with_text <Element li at 0x7fbf24526c00> text c2 tail d2 string c2
     _construct_text <Element li at 0x7fbf24526c00> text c2 tail d2 string c2
     _get_links_from_tag <Element li at 0x7fbf24526c00> text c2 tail d2 string c2
   article 6 <Element br at 0x7fbf2a115640> text None tail g string 
     _get_links_from_tag <Element br at 0x7fbf2a115640> text None tail g string 
     _construct_text <Element br at 0x7fbf2a115640> text None tail g string 
['c1d1', 'c2d2']

@dgunning what would be a correct partition output? i would expect to at least have all letters in some partition

i also think that the .tail data is actually text belonging to the parent element, not to the element that has the tail

stdweird avatar Jan 26 '24 15:01 stdweird

Yes I think it should have all the letters in some partition

dgunning avatar Jan 27 '24 23:01 dgunning

@FAbrahamDev this is a piece of html that should also retrun somethign useful: "<html><body><div>aa<ul><li>bb</li></ul><b>cc</b></div></body></html>" with .xpath(string) on the div, you get all the text back, incl the list i tried with only joining the texts of the foudn_tags element, but that will return aacc (but at least not the list), but you expect here something like ['aa', 'bb', 'cc'] i assume

@dgunning wrt tail, i tried replacing all tail with a text tag, it gives partial success; but still finetuneing more.

stdweird avatar Jan 29 '24 16:01 stdweird

@dgunning i made a PR https://github.com/Unstructured-IO/unstructured/pull/2483 with some code i am currently using i have not added any unittests to deal with the examples discussed here. i am unfamiliar with the way the unittests are set up in this repo tbh

stdweird avatar Jan 31 '24 11:01 stdweird

I added this to my fork of unstructured and copying your change in and it passes. What do you need to have the test one the PR and the PR to be approved?

def test_partition_html_with_nested_inline_tag():
    html_text = """
     <html>
     <body>
         <div>
         the Company issues shares at $<div style="display:inline;"><span>5.22</span></div> per share. 
         Here is more text
         </div>
     </body>
     </html>
     """
    partitions = partition_html(text=html_text)
    result = "\n".join([str(p) for p in partitions])
    assert 'Here is more text' in result

dgunning avatar Feb 23 '24 22:02 dgunning

I wrote the following test

def test_nested_divs_containing_nested_spans():
    html_str = """
    <div>
        Head
        <div><span>Nested</span></div>
        Tail
    </div>
    """
    html_document = HTMLDocument.from_string(html_str)

The original behaviour is to create multiple indlvidual html elements with "Head", "Nested". (The original code does not create an element for "Tail")

This fix works but puts everything inside 1 element that renders as

""" Head Nested Tail """

Not sure what the downstream effects are. Will continue testing

dgunning avatar Feb 25 '24 14:02 dgunning