Skip to content

Commit 6fd0b78

Browse files
synfonia-llccodexdgunning
authored
feat(documents): expose inline XBRL fact IDs on table cells (#2016) (#2017)
* feat(documents): expose inline XBRL fact IDs on table cells (#2016) Keep filed inline fact IDs attached to their physical table cells. Preserve ordering and cell markup boundaries across native parsing paths, reuse the document footnote relationships, and verify both EMEA amounts from the Oracle filing. Co-Authored-By: GPT-6.2 Sol <noreply@openai.com> * Keep nested cells out of basic HTML table grids Reuse owned row, cell and caption traversal in basic table mode so nested markup cannot duplicate fact IDs or determine the outer table's headers. Preserve each owned cell's existing text extraction and the fallback's data-cell-before-header-cell ordering. Cover nested data and header cells, reverse lookups, and mixed-header fact identities in both parsers for #2016. Co-Authored-By: GPT-6.2 Sol <noreply@openai.com> Co-Authored-By: GPT-6.2 Astra <noreply@openai.com> * Reuse the bundled Oracle 10-Q for cell fact regression Verify both filed Note 7 EMEA revenue cells, the shared footnote and unique reverse cell matches on Oracle accession 0000950170-24-104905. Use the repeated untagged MD&A cells and an unlinked Americas fact as controls. Remove the redundant reduced Oracle fixture. Co-Authored-By: GPT-6.2 Sol <noreply@openai.com> Co-Authored-By: GPT-6.2 Astra <noreply@openai.com> --------- Co-authored-by: GPT-6.2 Sol <noreply@openai.com> Co-authored-by: Dwight Gunning <dgunning@gmail.com>
1 parent 1ca9a1f commit 6fd0b78

6 files changed

Lines changed: 282 additions & 6 deletions

File tree

‎changelog.d/2016.added.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
**`Cell.xbrl_fact_ids` exposes Inline XBRL IDs from HTML table cells.** Oracle's filed $3,726 million EMEA revenue cell can be traced to its explicit Inline XBRL footnote through the existing document APIs. (GH #2016)

‎docs/guides/xbrl-footnotes.md‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,35 @@ the `fact-footnote` arcrole, or none) attach a footnote. A relationship with any
230230
arcrole, such as `fact-explanatoryFact` between two facts, is not an ordinary footnote and
231231
is not attached; EdgarTools does not yet model those relationships.
232232

233+
### Follow an Inline XBRL Footnote from a Table Cell
234+
235+
`Cell.xbrl_fact_ids` lists the filed IDs of Inline XBRL facts inside that HTML table
236+
cell, in document order. Use the IDs to join the cell to `Document.xbrl_facts`,
237+
then open the explicit links through `Document.xbrl_footnotes`.
238+
239+
```python
240+
def footnotes_for_cell(doc, cell):
241+
notes = {}
242+
for fact_id in dict.fromkeys(cell.xbrl_fact_ids):
243+
facts = [fact for fact in doc.xbrl_facts if fact.fact_id == fact_id]
244+
if len(facts) != 1:
245+
continue
246+
for note_id in facts[0].footnotes:
247+
note = doc.xbrl_footnotes.get(note_id)
248+
if note is not None:
249+
notes[note_id] = note
250+
return list(notes.values())
251+
```
252+
253+
For example, the $3,726 million and $3,481 million EMEA revenue cells in the
254+
[Oracle quarterly filing](https://www.sec.gov/Archives/edgar/data/1341439/000119312526389274/orcl-20260831.htm)
255+
carry different fact IDs, and both facts link to the filed EMEA definition.
256+
Printed note markers remain cell text. The tuple excludes IDs inside nested tables,
257+
`ix:header` and `ix:hidden` elements and uses markup ownership without evaluating CSS
258+
visibility. Cell IDs are available as markup metadata. Following an XBRL footnote
259+
requires extracting the document's Inline XBRL facts. The tuple preserves repeated
260+
IDs from the source, so the example checks for a unique fact before attributing a note.
261+
233262
### Facts in an Exhibit: Parse the Document Set
234263

235264
The inline documents of one filing form a single Inline XBRL document set, and only one of

‎edgar/documents/strategies/document_builder.py‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -792,31 +792,37 @@ def _should_process_children(self, element: HtmlElement, node: Node) -> bool:
792792

793793
def _process_table_basic(self, element: HtmlElement, style: Style) -> TableNode:
794794
"""Basic table processing without advanced strategy."""
795+
from edgar.documents.strategies.table_processing import TableProcessor, _cell_xbrl_fact_ids
796+
795797
table = TableNode(style=style)
796798

797799
# Set config for rendering decisions
798800
table._config = self.config
799801

800802
# Extract caption
801-
caption_elem = element.find('.//caption')
803+
caption_elem = TableProcessor._own_section(element, 'caption')
802804
if caption_elem is not None:
803805
table.caption = caption_elem.text_content().strip()
804806

805807
# Process rows
806-
for tr in element.findall('.//tr'):
808+
for tr in TableProcessor._own_rows(element):
809+
owned_cells = TableProcessor._own_cells(tr)
810+
# Basic mode historically emits data cells before header cells in a mixed row.
811+
owned_cells.sort(key=lambda cell: cell.tag == 'th')
807812
cells = []
808-
for td in tr.findall('.//td') + tr.findall('.//th'):
813+
for td in owned_cells:
809814
cell = Cell(
810815
content=td.text_content().strip(),
811816
colspan=int(td.get('colspan', '1')),
812817
rowspan=int(td.get('rowspan', '1')),
813818
is_header=(td.tag == 'th'),
814-
align=td.get('align')
819+
align=td.get('align'),
820+
xbrl_fact_ids=_cell_xbrl_fact_ids(td),
815821
)
816822
cells.append(cell)
817823

818824
if cells:
819-
row = Row(cells=cells, is_header=(tr.find('.//th') is not None))
825+
row = Row(cells=cells, is_header=any(cell.is_header for cell in cells))
820826

821827
# Determine if header or data row
822828
if tr.getparent().tag == 'thead' or row.is_header:

‎edgar/documents/strategies/table_processing.py‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
from edgar.documents.config import ParserConfig
1414
from edgar.documents.strategies.style_parser import StyleParser
15+
from edgar.documents.strategies.xbrl_extraction import _IX_CLARK_PREFIX, XBRLExtractor
1516
from edgar.documents.table_nodes import Cell, Row, TableNode
1617
from edgar.documents.types import TableType
1718

@@ -43,6 +44,34 @@ def _text_content(elem) -> str:
4344
return ''.join(parts)
4445

4546

47+
_CELL_FACT_TAGS = (
48+
*(f"ix:{tag}" for tag in XBRLExtractor.FACT_TAGS),
49+
f"{_IX_CLARK_PREFIX}nonFraction",
50+
f"{_IX_CLARK_PREFIX}nonNumeric",
51+
f"{_IX_CLARK_PREFIX}fraction",
52+
)
53+
_INLINE_XBRL_CONTAINERS = (
54+
"ix:hidden", "ix:header", f"{_IX_CLARK_PREFIX}hidden", f"{_IX_CLARK_PREFIX}header",
55+
)
56+
_CELL_FACT_BOUNDARIES = ("td", "th", "table", *_INLINE_XBRL_CONTAINERS)
57+
58+
59+
def _cell_xbrl_fact_ids(cell: HtmlElement) -> tuple[str, ...]:
60+
"""Keep the IDs of inline facts whose closest cell or boundary is this cell."""
61+
if not len(cell):
62+
return ()
63+
64+
fact_ids = []
65+
for fact in cell.iterdescendants(*_CELL_FACT_TAGS):
66+
fact_id = fact.get("id")
67+
if fact_id and fact_id.strip() and next(fact.iterancestors(*_CELL_FACT_BOUNDARIES), None) is cell:
68+
fact_ids.append(fact_id)
69+
70+
if fact_ids and next(cell.iterancestors(*_INLINE_XBRL_CONTAINERS), None) is None:
71+
return tuple(fact_ids)
72+
return ()
73+
74+
4675
class TableProcessor:
4776
"""
4877
Advanced table processing with type detection and structure analysis.
@@ -451,7 +480,8 @@ def _process_cell(self, elem: HtmlElement, is_header: bool) -> Optional[Cell]:
451480
colspan=colspan,
452481
rowspan=rowspan,
453482
is_header=is_header,
454-
align=align
483+
align=align,
484+
xbrl_fact_ids=_cell_xbrl_fact_ids(elem),
455485
)
456486

457487
return cell

‎edgar/documents/table_nodes.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ class Cell:
7878
rowspan: int = 1
7979
is_header: bool = False
8080
align: Optional[str] = None
81+
# IDs on inline facts belonging to this physical cell, in source order.
82+
xbrl_fact_ids: tuple[str, ...] = field(default=(), repr=False, compare=False, kw_only=True)
8183

8284
def text(self) -> str:
8385
"""Extract text from cell."""
Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
"""Physical HTML cells preserve filed Inline XBRL fact identities.
2+
3+
GitHub Issue: https://github.com/dgunning/edgartools/issues/2016
4+
"""
5+
6+
import pytest
7+
from lxml import etree, html
8+
9+
from edgar.documents import ParserConfig, parse_html
10+
from edgar.documents.strategies.table_processing import TableProcessor
11+
from edgar.documents.table_nodes import Cell
12+
from tests.paths import FIXTURES_DIR, REPO_ROOT
13+
14+
pytestmark = pytest.mark.fast
15+
16+
# https://www.sec.gov/Archives/edgar/data/1341439/000095017024104905/orcl-20240831.htm
17+
ORACLE_FIXTURE = REPO_ROOT / "data/html/Oracle.10-Q.html"
18+
ORACLE_EMEA = {
19+
"3,228": ("F_b8604f4b-10f0-4509-8e6a-4b2044b63073", "3228000000"),
20+
"3,005": ("F_6c2fb952-8c5e-4ea5-a1c3-e998c3f20684", "3005000000"),
21+
}
22+
EMEA_FOOTNOTE = "FNT_101dfb5e-8641-4a4f-a4a3-578450fa445b"
23+
24+
25+
@pytest.fixture(scope="module")
26+
def oracle_document():
27+
return parse_html(ORACLE_FIXTURE.read_bytes(), ParserConfig(form="10-Q"))
28+
29+
30+
def find_cell(table, row_label, cell_text):
31+
return next(
32+
cell
33+
for row in table.rows
34+
if row.cells[0].text() == row_label
35+
for cell in row.cells
36+
if cell.text() == cell_text
37+
)
38+
39+
40+
def test_oracle_emea_cells_lead_to_their_filed_footnote(oracle_document):
41+
"""Oracle Form 10-Q, filed September 10, 2024, accession 0000950170-24-104905, Note 7."""
42+
note_table = oracle_document.tables[17]
43+
facts = {fact.fact_id: fact for fact in oracle_document.xbrl_facts}
44+
45+
for display, (fact_id, value) in ORACLE_EMEA.items():
46+
cell = find_cell(note_table, "EMEA(1)", display)
47+
assert cell.numeric_value == float(display.replace(",", ""))
48+
assert cell.xbrl_fact_ids == (fact_id,)
49+
50+
fact = facts[cell.xbrl_fact_ids[0]]
51+
assert fact.value == value
52+
assert fact.footnotes == [EMEA_FOOTNOTE]
53+
assert oracle_document.xbrl_footnotes[fact.footnotes[0]].text == (
54+
"Comprised of Europe, the Middle East and Africa"
55+
)
56+
57+
reverse_cell, = (
58+
candidate
59+
for table in oracle_document.tables
60+
for row_cells in table.headers + [row.cells for row in table.rows + table.footer]
61+
for candidate in row_cells
62+
if fact_id in candidate.xbrl_fact_ids
63+
)
64+
assert reverse_cell is cell
65+
66+
67+
def test_oracle_markers_and_untagged_repeat_do_not_borrow_fact_ids(oracle_document):
68+
note_table = oracle_document.tables[17]
69+
mda_table = oracle_document.tables[21]
70+
71+
assert find_cell(note_table, "EMEA(1)", "EMEA(1)").xbrl_fact_ids == ()
72+
assert find_cell(mda_table, "EMEA(1)", "EMEA(1)").xbrl_fact_ids == ()
73+
for display in ORACLE_EMEA:
74+
assert find_cell(mda_table, "EMEA(1)", display).xbrl_fact_ids == ()
75+
76+
# A real fact can belong to a cell without having any filed footnote.
77+
americas = find_cell(note_table, "Americas", "8,372")
78+
assert len(americas.xbrl_fact_ids) == 1
79+
americas_fact, = (
80+
fact for fact in oracle_document.xbrl_facts if fact.fact_id == americas.xbrl_fact_ids[0]
81+
)
82+
assert americas_fact.value == "8372000000"
83+
assert americas_fact.footnotes == []
84+
85+
86+
@pytest.mark.parametrize("table_extraction", [True, False], ids=["advanced", "basic"])
87+
def test_cell_keeps_its_own_inline_fact_ids_in_source_order(table_extraction):
88+
markup = """<html><body><ix:nonNumeric id="ancestor" name="t:TextBlock">
89+
<table><tr>
90+
<td><span><ix:nonFraction id="b" name="t:Amount">7</ix:nonFraction></span>
91+
<ix:nonNumeric id="a" name="t:Label">label</ix:nonNumeric>
92+
<ix:nonFraction id="b" name="t:Other">8</ix:nonFraction>
93+
<ix:fraction id="fraction" name="t:Fraction"><ix:numerator>1</ix:numerator>
94+
<ix:denominator>2</ix:denominator></ix:fraction>
95+
<ix:nonFraction name="t:NoID">9</ix:nonFraction>
96+
<ix:nonFraction id="" name="t:EmptyID">9</ix:nonFraction>
97+
<ix:nonFraction id=" " name="t:BlankID">9</ix:nonFraction>
98+
<ix:footnote id="resource">note resource</ix:footnote>
99+
<ix:continuation id="continued">continuation</ix:continuation>
100+
<ix:hidden><ix:nonFraction id="hidden" name="t:Amount">10</ix:nonFraction></ix:hidden>
101+
<table><tr><td><ix:nonFraction id="nested" name="t:Amount">11</ix:nonFraction></td></tr></table>
102+
</td>
103+
</tr></table></ix:nonNumeric></body></html>"""
104+
doc = parse_html(markup, ParserConfig(table_extraction=table_extraction))
105+
cell = doc.tables[0].rows[0].cells[0]
106+
107+
# The enclosing fact and the nested cell's fact belong to different elements.
108+
assert cell.xbrl_fact_ids == ("b", "a", "b", "fraction")
109+
110+
111+
def test_manual_cell_keeps_existing_rendering_and_equality():
112+
cell = Cell("3,726", xbrl_fact_ids=("fact",))
113+
plain = Cell("3,726")
114+
115+
assert plain.xbrl_fact_ids == ()
116+
assert cell == plain
117+
assert repr(cell) == repr(plain)
118+
assert cell.text() == "3,726"
119+
assert cell.html() == "<td>3,726</td>"
120+
assert cell.numeric_value == 3726
121+
122+
123+
def test_toc_section_tables_keep_distinct_facts_with_equal_displayed_values():
124+
"""NIKE Form 10-K, accession 0000320187-25-000047, Item 8."""
125+
fixture = FIXTURES_DIR / "html/nke/10k/nke-10-k-2025-07-17.html"
126+
doc = parse_html(fixture.read_bytes(), ParserConfig(form="10-K"))
127+
section = doc.sections["part_ii_item_8"]
128+
assert section.detection_method == "toc"
129+
130+
ids = [
131+
cell.xbrl_fact_ids
132+
for table in section.tables()
133+
for row in table.rows
134+
if row.cells[0].text() == "Net income"
135+
for cell in row.cells
136+
if cell.text() == "3,219"
137+
]
138+
assert ids == [("f-101",), ("f-185",), ("f-365",), ("f-366",)]
139+
140+
141+
def test_cell_keeps_fact_in_namespace_aware_inline_child():
142+
table = html.fromstring("<table><tr><td>Example</td><td></td></tr></table>")
143+
value_cell = table.xpath(".//td")[1]
144+
namespace = "{http://www.xbrl.org/2013/inlineXBRL}"
145+
etree.SubElement(value_cell, namespace + "nonFraction", id="visible").text = "7"
146+
hidden = etree.SubElement(value_cell, namespace + "hidden")
147+
etree.SubElement(hidden, namespace + "nonFraction", id="hidden").text = "8"
148+
149+
parsed = TableProcessor(ParserConfig()).process(table)
150+
assert parsed.rows[0].cells[1].xbrl_fact_ids == ("visible",)
151+
152+
153+
@pytest.mark.parametrize("nested_tag", ["td", "th"])
154+
def test_basic_table_keeps_nested_cells_out_of_its_outer_grid(nested_tag):
155+
markup = f"""<table><tbody><tr>
156+
<td>Outer<ix:nonNumeric id="A" name="t:Label">a</ix:nonNumeric>
157+
<table><caption>Nested caption</caption><tr>
158+
<{nested_tag}>Inner<ix:nonNumeric id="B" name="t:Label">b</ix:nonNumeric></{nested_tag}>
159+
</tr></table>
160+
</td>
161+
<td>After<ix:nonNumeric id="C" name="t:Label">c</ix:nonNumeric></td>
162+
</tr></tbody></table>"""
163+
doc = parse_html(markup, ParserConfig(table_extraction=False))
164+
outer, = doc.tables
165+
166+
rows = [[cell.xbrl_fact_ids for cell in row.cells] for row in outer.rows]
167+
reverse_matches = [
168+
cell for cells in [*outer.headers, *(row.cells for row in outer.rows)]
169+
for cell in cells if "B" in cell.xbrl_fact_ids
170+
]
171+
assert (rows, len(reverse_matches)) == ([[("A",), ("C",)]], 0)
172+
assert not outer.headers
173+
assert outer.caption is None
174+
assert [" ".join(cell.text().split()) for cell in outer.rows[0].cells] == [
175+
"Outera Nested caption Innerb", "Afterc",
176+
]
177+
assert [fact.fact_id for fact in doc.xbrl_facts] == ["A", "B", "C"]
178+
179+
180+
@pytest.mark.parametrize(
181+
("table_extraction", "expected_header", "rendered_header"),
182+
[
183+
(False, [("Period", ("period",)), ("Label", ("label",))],
184+
"<tr><td>Period</td><th>Label</th></tr>"),
185+
(True, [("Label", ("label",)), ("Period", ("period",))],
186+
"<tr><th>Label</th><th>Period</th></tr>"),
187+
],
188+
ids=["basic", "advanced"],
189+
)
190+
def test_table_preserves_mixed_header_fact_ownership(
191+
table_extraction, expected_header, rendered_header
192+
):
193+
markup = """<table><caption>Metrics</caption>
194+
<thead><tr>
195+
<th><ix:nonNumeric id="label" name="t:Label">Label</ix:nonNumeric></th>
196+
<td><ix:nonNumeric id="period" name="t:Period">Period</ix:nonNumeric></td>
197+
</tr></thead>
198+
<tbody><tr><td>Example</td><td>42</td></tr></tbody>
199+
</table>"""
200+
doc = parse_html(markup, ParserConfig(table_extraction=table_extraction))
201+
table, = doc.tables
202+
header, = table.headers
203+
204+
assert table.caption == "Metrics"
205+
assert [(cell.text(), cell.xbrl_fact_ids) for cell in header] == expected_header
206+
assert table.rows[0].cells[1].numeric_value == 42
207+
assert rendered_header in table.html()
208+
assert "<tr><td>Example</td><td>42</td></tr>" in table.html()

0 commit comments

Comments
 (0)