File size: 12,920 Bytes
e8f6f4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
"""Comprehensive verification test suite for multimodal PDF element chunker.

Tests compliance with the CocoIndex PDF Elements architecture and LlamaIndex
RecursiveTextSplitter integration:

1. Text splitting using LlamaIndex SentenceSplitter with boundary preservation.
2. Table chunking with header repetition on large partitioned financial tables.
3. Figure/chart chunking with pixel filtering, classification, and image path tracking.
4. Heading breadcrumb propagation and page coordinates.
5. Deterministic fingerprinting and JSON serialization round-trips.
6. Real filing extraction processing (Annual Report, Presentation, Transcript).

Google Python Style Guide Compliant.
"""

from __future__ import annotations

import json
from pathlib import Path
import sys
import unittest

from ingestion.chunker import (
    CHUNKER_VERSION,
    DEFAULT_ANNUAL_SKIP_SECTIONS,
    ELEMENT_FIGURE,
    ELEMENT_TABLE,
    ELEMENT_TEXT,
    Chunk,
    ChunkSet,
    chunk_document,
    read_chunk_cache,
    write_chunk_cache,
)
from ingestion.documents.content import (
    KIND_FIGURE,
    KIND_HEADING,
    KIND_LIST,
    KIND_TABLE,
    KIND_TEXT,
    Block,
    ExtractedDocument,
    Figure,
    Table,
)


class TestSentenceSplitter(unittest.TestCase):
    """Verifies recursive text splitting logic."""

    def test_small_text_stays_single_chunk(self) -> None:
        doc = ExtractedDocument(
            doc_id="test_doc",
            doc_type="concall_presentation",
            ticker="TEST",
            label="Test Presentation",
            blocks=[
                Block(kind=KIND_HEADING, text="Overview", path=["Overview"], page=1),
                Block(kind=KIND_TEXT, text="Short business update paragraph.", path=["Overview"], page=1),
            ],
        )
        chunk_set = chunk_document(doc, chunk_size=500, chunk_overlap=50)
        self.assertEqual(chunk_set.n_chunks, 1)
        chunk = chunk_set.chunks[0]
        self.assertEqual(chunk.element_type, ELEMENT_TEXT)
        self.assertEqual(chunk.page_start, 1)
        self.assertEqual(chunk.path, ["Overview"])
        self.assertIn("Short business update paragraph.", chunk.text)
        self.assertIn("Section: Overview", chunk.embed_text)

    def test_long_prose_is_recursively_split(self) -> None:
        long_paragraph = (
            "Operating margins improved across all three business units during the fiscal period. "
            * 25
        )
        doc = ExtractedDocument(
            doc_id="test_long",
            doc_type="annual_report",
            ticker="TEST",
            label="Annual Report",
            blocks=[
                Block(kind=KIND_HEADING, text="MD&A", path=["MD&A"], page=5),
                Block(kind=KIND_TEXT, text=long_paragraph, path=["MD&A"], page=5),
            ],
        )
        chunk_set = chunk_document(doc, chunk_size=300, chunk_overlap=50)
        self.assertGreater(chunk_set.n_chunks, 1)
        for chunk in chunk_set.chunks:
            self.assertEqual(chunk.element_type, ELEMENT_TEXT)
            self.assertEqual(chunk.page_start, 5)
            self.assertGreater(len(chunk.text), 0)
            self.assertLess(len(chunk.text), 2000)


class TestTableChunking(unittest.TestCase):
    """Verifies structured table preservation and large table partitioning."""

    def test_small_table_stays_intact(self) -> None:
        table = Table(
            rows=[
                ["Segment", "Revenue (INR Cr)", "EBITDA Margin"],
                ["IT Services", "22,500", "16.4%"],
                ["Consulting", "4,200", "14.1%"],
            ],
            header_rows=1,
            caption="Segment Performance",
            page=12,
        )
        doc = ExtractedDocument(
            doc_id="test_tbl_small",
            doc_type="annual_report",
            ticker="TEST",
            label="Annual Report",
            blocks=[
                Block(kind=KIND_HEADING, text="Segment Review", path=["Segment Review"], page=12),
                Block(kind=KIND_TABLE, text=table.to_markdown(), path=["Segment Review"], table=table, page=12),
            ],
        )
        chunk_set = chunk_document(doc)
        self.assertEqual(chunk_set.n_chunks, 1)
        chunk = chunk_set.chunks[0]
        self.assertEqual(chunk.element_type, ELEMENT_TABLE)
        self.assertEqual(chunk.page_start, 12)
        self.assertIn("IT Services", chunk.text)
        self.assertIn("Consulting", chunk.text)
        self.assertEqual(chunk.metadata["n_rows"], 3)
        self.assertEqual(chunk.metadata["header_rows"], 1)

    def test_large_table_is_partitioned_with_headers_repeated(self) -> None:
        header = [["Line Item", "FY26", "FY25"]]
        body = [[f"Schedule Item {i}", f"{1000 + i}", f"{900 + i}"] for i in range(1, 60)]
        table = Table(
            rows=header + body,
            header_rows=1,
            caption="Consolidated Financial Schedules",
            page=20,
        )
        doc = ExtractedDocument(
            doc_id="test_tbl_large",
            doc_type="annual_report",
            ticker="TEST",
            label="Annual Report",
            blocks=[
                Block(kind=KIND_HEADING, text="Financials", path=["Financials"], page=20),
                Block(kind=KIND_TABLE, text=table.to_markdown(), path=["Financials"], table=table, page=20),
            ],
        )
        chunk_set = chunk_document(doc)
        self.assertGreater(chunk_set.n_chunks, 1)
        for chunk in chunk_set.chunks:
            self.assertEqual(chunk.element_type, ELEMENT_TABLE)
            self.assertIn("Line Item", chunk.text)
            self.assertIn("FY26", chunk.text)
            self.assertIn("Table Part", chunk.embed_text)


class TestFigureChunking(unittest.TestCase):
    """Verifies visual element and figure metadata extraction."""

    def test_meaningful_chart_creates_figure_chunk(self) -> None:
        fig = Figure(
            path="figures/test_fig/p0004-01.png",
            page=4,
            kind="bar_chart",
            width=800,
            height=400,
            caption="Quarterly Revenue Trend",
        )
        doc = ExtractedDocument(
            doc_id="test_fig",
            doc_type="concall_presentation",
            ticker="TEST",
            label="Investor Presentation",
            blocks=[
                Block(kind=KIND_HEADING, text="Revenue Growth", path=["Revenue Growth"], page=4),
                Block(kind=KIND_FIGURE, text="", path=["Revenue Growth"], figure=fig, page=4),
            ],
        )
        chunk_set = chunk_document(doc)
        self.assertEqual(chunk_set.n_chunks, 1)
        chunk = chunk_set.chunks[0]
        self.assertEqual(chunk.element_type, ELEMENT_FIGURE)
        self.assertEqual(chunk.page_start, 4)
        self.assertEqual(chunk.figure_path, "figures/test_fig/p0004-01.png")
        self.assertIn("figures/test_fig/p0004-01.png", chunk.text)
        self.assertEqual(chunk.metadata["kind"], "bar_chart")
        self.assertEqual(chunk.metadata["width"], 800)
        self.assertEqual(chunk.metadata["height"], 400)

    def test_tiny_decorative_furniture_is_filtered(self) -> None:
        tiny_icon = Figure(
            path="figures/test_fig/icon.png",
            page=1,
            kind="icon",
            width=24,
            height=24,
            caption="",
        )
        doc = ExtractedDocument(
            doc_id="test_filter",
            doc_type="concall_presentation",
            ticker="TEST",
            label="Presentation",
            blocks=[
                Block(kind=KIND_FIGURE, text="", path=[], figure=tiny_icon, page=1),
            ],
        )
        chunk_set = chunk_document(doc, min_figure_pixels=48)
        self.assertEqual(chunk_set.n_chunks, 0)


class TestChunkSerialization(unittest.TestCase):
    """Verifies chunk serialization and persistence."""

    def test_chunk_and_chunkset_roundtrip(self) -> None:
        chunk = Chunk(
            chunk_id="test_p0001_txt_001",
            doc_id="test_doc",
            ticker="TEST",
            doc_type="annual_report",
            label="FY26 Report",
            element_type=ELEMENT_TEXT,
            page_start=1,
            page_end=1,
            section="Executive Summary",
            path=["Executive Summary", "Strategic Highlights"],
            text="Revenue increased 12% YoY.",
            embed_text="[TEST] Revenue increased 12% YoY.",
            metadata={"char_count": 26},
        )
        chunk_set = ChunkSet(
            doc_id="test_doc",
            ticker="TEST",
            doc_type="annual_report",
            label="FY26 Report",
            fingerprint="abc123hash",
            params={"chunk_size": 800},
            chunks=[chunk],
        )

        serialized = chunk_set.to_dict()
        reconstructed = ChunkSet.from_dict(serialized)

        self.assertEqual(reconstructed.doc_id, chunk_set.doc_id)
        self.assertEqual(reconstructed.fingerprint, chunk_set.fingerprint)
        self.assertEqual(reconstructed.n_chunks, 1)
        r_chunk = reconstructed.chunks[0]
        self.assertEqual(r_chunk.chunk_id, chunk.chunk_id)
        self.assertEqual(r_chunk.element_type, chunk.element_type)
        self.assertEqual(r_chunk.path, chunk.path)

    def test_llamaindex_node_conversion(self) -> None:
        chunk_txt = Chunk(
            chunk_id="test_txt_001",
            doc_id="test_doc",
            ticker="TEST",
            element_type=ELEMENT_TEXT,
            page_start=2,
            page_end=2,
            section="Overview",
            text="Prose content for LlamaIndex node.",
        )
        chunk_fig = Chunk(
            chunk_id="test_fig_001",
            doc_id="test_doc",
            ticker="TEST",
            element_type=ELEMENT_FIGURE,
            page_start=4,
            page_end=4,
            figure_path="figures/test_doc/p0004-01.png",
            text="Figure markdown description.",
        )
        chunk_set = ChunkSet(
            doc_id="test_doc",
            ticker="TEST",
            chunks=[chunk_txt, chunk_fig],
        )

        nodes = chunk_set.to_nodes()
        self.assertEqual(len(nodes), 2)
        from llama_index.core.schema import ImageNode, TextNode
        self.assertIsInstance(nodes[0], TextNode)
        self.assertIsInstance(nodes[1], ImageNode)
        self.assertEqual(nodes[1].image_path, "figures/test_doc/p0004-01.png")

        reconstructed_chunk = Chunk.from_node(nodes[0])
        self.assertEqual(reconstructed_chunk.chunk_id, "test_txt_001")
        self.assertEqual(reconstructed_chunk.text, "Prose content for LlamaIndex node.")

        from llama_index.core.schema import NodeRelationship
        self.assertIn(NodeRelationship.NEXT, nodes[0].relationships)
        self.assertEqual(nodes[0].relationships[NodeRelationship.NEXT].node_id, nodes[1].node_id)
        self.assertIn(NodeRelationship.PREVIOUS, nodes[1].relationships)
        self.assertEqual(nodes[1].relationships[NodeRelationship.PREVIOUS].node_id, nodes[0].node_id)

        reconstructed_set = ChunkSet.from_nodes(nodes, doc_id="test_doc", ticker="TEST")
        self.assertEqual(reconstructed_set.n_chunks, 2)


class TestRealExtractions(unittest.TestCase):
    """Verifies chunking against real extracted corporate filings."""

    def setUp(self) -> None:
        self.extracted_dir = Path("output/WIPRO/extracted")

    def test_presentation_chunking(self) -> None:
        path = self.extracted_dir / "presentation_2026_01.json"
        if not path.exists():
            self.skipTest("Extracted presentation not available")
        doc = ExtractedDocument.from_dict(json.loads(path.read_text("utf-8")))
        chunk_set = chunk_document(doc)
        counts = chunk_set.element_counts()
        self.assertGreater(chunk_set.n_chunks, 20)
        self.assertGreater(counts.get(ELEMENT_FIGURE, 0), 10)
        self.assertGreater(counts.get(ELEMENT_TEXT, 0), 10)

    def test_annual_report_chunking(self) -> None:
        path = self.extracted_dir / "annual_report_FY2026_financials.json"
        if not path.exists():
            self.skipTest("Extracted annual report not available")
        doc = ExtractedDocument.from_dict(json.loads(path.read_text("utf-8")))
        chunk_set = chunk_document(doc)
        counts = chunk_set.element_counts()
        self.assertGreater(chunk_set.n_chunks, 30)
        self.assertGreater(counts.get(ELEMENT_TABLE, 0), 5)
        self.assertGreater(counts.get(ELEMENT_TEXT, 0), 30)

    def test_transcript_chunking(self) -> None:
        path = self.extracted_dir / "transcript_2026_07.json"
        if not path.exists():
            self.skipTest("Extracted transcript not available")
        doc = ExtractedDocument.from_dict(json.loads(path.read_text("utf-8")))
        chunk_set = chunk_document(doc)
        self.assertGreater(chunk_set.n_chunks, 20)


if __name__ == "__main__":
    unittest.main()