|
| 1 | +""" |
| 2 | +Unit tests for nltk.tokenize.texttiling. |
| 3 | +
|
| 4 | +Marti A. Hearst (1997) "TextTiling: Segmenting Text into Multi-Paragraph |
| 5 | +Subtopic Passages", Computational Linguistics, 23(1), pp. 33-64. |
| 6 | +https://aclanthology.org/J97-1003.pdf |
| 7 | +""" |
| 8 | + |
| 9 | +from nltk.tokenize.texttiling import ( |
| 10 | + BLOCK_COMPARISON, |
| 11 | + VOCABULARY_INTRODUCTION, |
| 12 | + TextTilingTokenizer, |
| 13 | +) |
| 14 | + |
| 15 | +# A text with clear topic shifts for testing. |
| 16 | +# Topic 1: animals in nature |
| 17 | +# Topic 2: stock market / finance |
| 18 | +# Topic 3: marine biology |
| 19 | +# Topic 4: weather / agriculture |
| 20 | +MULTI_TOPIC_TEXT = ( |
| 21 | + """ |
| 22 | +The quick brown fox jumped over the lazy dog. The dog was sleeping |
| 23 | +in the sun. It was a beautiful day outside in the forest. The fox |
| 24 | +continued on its way through the dense woodland. Birds were singing |
| 25 | +in the trees and rabbits scurried through the underbrush. The animals |
| 26 | +were enjoying the warm afternoon sunshine. |
| 27 | +
|
| 28 | +Meanwhile, in the city, the stock market was experiencing significant |
| 29 | +changes. Traders were anxious about the new economic policies. The |
| 30 | +financial sector was particularly affected by the recent changes in |
| 31 | +interest rates. Banks reported lower quarterly earnings. Investors |
| 32 | +were pulling their money out of risky assets. The central bank was |
| 33 | +considering raising rates again. |
| 34 | +
|
| 35 | +In other news, scientists discovered a new species of deep-sea fish. |
| 36 | +The fish was found at a depth of three thousand meters below the |
| 37 | +surface. Marine biologists were excited about the discovery. The |
| 38 | +specimen was brought to the laboratory for further study. Researchers |
| 39 | +believe the species has been living in the deep ocean for millions |
| 40 | +of years. |
| 41 | +
|
| 42 | +The weather forecast predicted rain for the weekend across the region. |
| 43 | +Farmers were hoping for the precipitation to help their growing crops. |
| 44 | +The drought had lasted several months with no relief in sight. Water |
| 45 | +reservoirs were at critically low levels. Irrigation systems were |
| 46 | +being strained beyond their capacity. |
| 47 | +""" |
| 48 | + * 3 |
| 49 | +) # repeat to get enough text for the algorithm |
| 50 | + |
| 51 | + |
| 52 | +class TestTextTilingBlockComparison: |
| 53 | + """Tests for the block comparison method (Hearst 1997, Section 3.2).""" |
| 54 | + |
| 55 | + def test_returns_segments(self): |
| 56 | + """Block comparison should return a list of text segments.""" |
| 57 | + tt = TextTilingTokenizer(w=10, k=5, similarity_method=BLOCK_COMPARISON) |
| 58 | + segments = tt.tokenize(MULTI_TOPIC_TEXT) |
| 59 | + assert isinstance(segments, list) |
| 60 | + assert len(segments) >= 1 |
| 61 | + |
| 62 | + def test_segments_cover_full_text(self): |
| 63 | + """Concatenated segments should reconstruct the original text.""" |
| 64 | + tt = TextTilingTokenizer(w=10, k=5, similarity_method=BLOCK_COMPARISON) |
| 65 | + segments = tt.tokenize(MULTI_TOPIC_TEXT) |
| 66 | + assert "".join(segments) == MULTI_TOPIC_TEXT |
| 67 | + |
| 68 | + def test_demo_mode_returns_scores(self): |
| 69 | + """In demo mode, should return (gap_scores, smooth, depth, boundaries).""" |
| 70 | + tt = TextTilingTokenizer( |
| 71 | + w=10, k=5, similarity_method=BLOCK_COMPARISON, demo_mode=True |
| 72 | + ) |
| 73 | + result = tt.tokenize(MULTI_TOPIC_TEXT) |
| 74 | + assert len(result) == 4 |
| 75 | + gap_scores, smooth_scores, depth_scores, boundaries = result |
| 76 | + assert len(gap_scores) > 0 |
| 77 | + assert len(smooth_scores) > 0 |
| 78 | + assert len(depth_scores) > 0 |
| 79 | + assert len(boundaries) > 0 |
| 80 | + |
| 81 | + def test_gap_scores_between_zero_and_one(self): |
| 82 | + """Block comparison gap scores should be in [0, 1] (cosine similarity).""" |
| 83 | + tt = TextTilingTokenizer( |
| 84 | + w=10, k=5, similarity_method=BLOCK_COMPARISON, demo_mode=True |
| 85 | + ) |
| 86 | + gap_scores, _, _, _ = tt.tokenize(MULTI_TOPIC_TEXT) |
| 87 | + for score in gap_scores: |
| 88 | + assert 0.0 <= score <= 1.0, f"Score {score} out of [0, 1] range" |
| 89 | + |
| 90 | + def test_homogeneous_text_few_boundaries(self): |
| 91 | + """Repeating the same paragraph should produce few boundaries.""" |
| 92 | + paragraph = "The cat sat on the mat. The dog chased the ball. " |
| 93 | + # Need paragraph breaks (double newlines) for the algorithm |
| 94 | + repeated = ("\n\n".join([paragraph] * 10)) + "\n\n" |
| 95 | + tt = TextTilingTokenizer(w=10, k=5, similarity_method=BLOCK_COMPARISON) |
| 96 | + segments = tt.tokenize(repeated) |
| 97 | + # Homogeneous text should have few segments |
| 98 | + assert len(segments) <= 5 |
| 99 | + |
| 100 | + |
| 101 | +class TestTextTilingVocabIntroduction: |
| 102 | + """Tests for the vocabulary introduction method (Hearst 1997, Section 3.2).""" |
| 103 | + |
| 104 | + def test_returns_segments(self): |
| 105 | + """Vocabulary introduction should return a list of text segments.""" |
| 106 | + tt = TextTilingTokenizer(w=10, k=5, similarity_method=VOCABULARY_INTRODUCTION) |
| 107 | + segments = tt.tokenize(MULTI_TOPIC_TEXT) |
| 108 | + assert isinstance(segments, list) |
| 109 | + assert len(segments) >= 1 |
| 110 | + |
| 111 | + def test_segments_cover_full_text(self): |
| 112 | + """Concatenated segments should reconstruct the original text.""" |
| 113 | + tt = TextTilingTokenizer(w=10, k=5, similarity_method=VOCABULARY_INTRODUCTION) |
| 114 | + segments = tt.tokenize(MULTI_TOPIC_TEXT) |
| 115 | + assert "".join(segments) == MULTI_TOPIC_TEXT |
| 116 | + |
| 117 | + def test_demo_mode_returns_scores(self): |
| 118 | + """In demo mode, should return (gap_scores, smooth, depth, boundaries).""" |
| 119 | + tt = TextTilingTokenizer( |
| 120 | + w=10, k=5, similarity_method=VOCABULARY_INTRODUCTION, demo_mode=True |
| 121 | + ) |
| 122 | + result = tt.tokenize(MULTI_TOPIC_TEXT) |
| 123 | + assert len(result) == 4 |
| 124 | + gap_scores, smooth_scores, depth_scores, boundaries = result |
| 125 | + assert len(gap_scores) > 0 |
| 126 | + assert len(smooth_scores) > 0 |
| 127 | + assert len(depth_scores) > 0 |
| 128 | + assert len(boundaries) > 0 |
| 129 | + |
| 130 | + def test_gap_scores_non_negative(self): |
| 131 | + """Vocabulary introduction scores should be non-negative.""" |
| 132 | + tt = TextTilingTokenizer( |
| 133 | + w=10, k=5, similarity_method=VOCABULARY_INTRODUCTION, demo_mode=True |
| 134 | + ) |
| 135 | + gap_scores, _, _, _ = tt.tokenize(MULTI_TOPIC_TEXT) |
| 136 | + for score in gap_scores: |
| 137 | + assert score >= 0.0, f"Score {score} is negative" |
| 138 | + |
| 139 | + def test_homogeneous_text_low_scores(self): |
| 140 | + """Repeating the same paragraph should produce low vocab intro scores.""" |
| 141 | + paragraph = "The cat sat on the mat. The dog chased the ball. " |
| 142 | + repeated = ("\n\n".join([paragraph] * 10)) + "\n\n" |
| 143 | + tt = TextTilingTokenizer( |
| 144 | + w=10, k=5, similarity_method=VOCABULARY_INTRODUCTION, demo_mode=True |
| 145 | + ) |
| 146 | + gap_scores, _, _, _ = tt.tokenize(repeated) |
| 147 | + # After the first few windows, no new vocabulary is introduced |
| 148 | + # so later scores should be near zero |
| 149 | + later_scores = gap_scores[len(gap_scores) // 2 :] |
| 150 | + avg_later = sum(later_scores) / len(later_scores) if later_scores else 0 |
| 151 | + assert ( |
| 152 | + avg_later < 0.15 |
| 153 | + ), f"Average later score {avg_later} too high for repeated text" |
| 154 | + |
| 155 | + |
| 156 | +class TestTextTilingCommon: |
| 157 | + """Tests common to both methods.""" |
| 158 | + |
| 159 | + def test_both_methods_find_boundaries(self): |
| 160 | + """Both methods should find at least one boundary in multi-topic text.""" |
| 161 | + for method in [BLOCK_COMPARISON, VOCABULARY_INTRODUCTION]: |
| 162 | + tt = TextTilingTokenizer(w=10, k=5, similarity_method=method) |
| 163 | + segments = tt.tokenize(MULTI_TOPIC_TEXT) |
| 164 | + assert ( |
| 165 | + len(segments) > 1 |
| 166 | + ), f"Method {method} found no boundaries in multi-topic text" |
| 167 | + |
| 168 | + def test_invalid_similarity_method(self): |
| 169 | + """Invalid similarity method should raise ValueError.""" |
| 170 | + tt = TextTilingTokenizer(similarity_method="invalid") |
| 171 | + try: |
| 172 | + tt.tokenize(MULTI_TOPIC_TEXT) |
| 173 | + assert False, "Expected ValueError" |
| 174 | + except ValueError: |
| 175 | + pass |
| 176 | + |
| 177 | + def test_invalid_smoothing_method(self): |
| 178 | + """Invalid smoothing method should raise ValueError.""" |
| 179 | + tt = TextTilingTokenizer(smoothing_method="invalid") |
| 180 | + try: |
| 181 | + tt.tokenize(MULTI_TOPIC_TEXT) |
| 182 | + assert False, "Expected ValueError" |
| 183 | + except ValueError: |
| 184 | + pass |
| 185 | + |
| 186 | + def test_boundary_count_matches_segments(self): |
| 187 | + """Number of boundaries should be number of segments minus 1.""" |
| 188 | + for method in [BLOCK_COMPARISON, VOCABULARY_INTRODUCTION]: |
| 189 | + tt = TextTilingTokenizer(w=10, k=5, similarity_method=method) |
| 190 | + segments = tt.tokenize(MULTI_TOPIC_TEXT) |
| 191 | + tt_demo = TextTilingTokenizer( |
| 192 | + w=10, k=5, similarity_method=method, demo_mode=True |
| 193 | + ) |
| 194 | + _, _, _, boundaries = tt_demo.tokenize(MULTI_TOPIC_TEXT) |
| 195 | + num_boundaries = sum(boundaries) |
| 196 | + # segments = boundaries + 1 (approximately, due to normalization) |
| 197 | + assert num_boundaries >= len(segments) - 2 |
0 commit comments