| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | from __future__ import annotations |
| 11 | |
| 12 | import unittest |
| 13 | from dataclasses import dataclass, field |
| 14 | |
| 15 | from src.providers.llm import ChatResult |
| 16 | from src.pricing import Usage |
| 17 | from src.summarize import GroundedSummary, Summarizer, build_summary_prompt, resolve_scope |
| 18 | from src.summarize.prompt import NO_CONTENT_SENTENCE |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | @dataclass |
| 24 | class _Unit: |
| 25 | |
| 26 | |
| 27 | span_id: str |
| 28 | page: int |
| 29 | text: str |
| 30 | retrieval_disi: bool = False |
| 31 | |
| 32 | @property |
| 33 | def retrievable(self) -> bool: |
| 34 | return not self.retrieval_disi |
| 35 | |
| 36 | |
| 37 | @dataclass |
| 38 | class _Doc: |
| 39 | |
| 40 | units: list = field(default_factory=list) |
| 41 | |
| 42 | |
| 43 | class _StubLLMClient: |
| 44 | |
| 45 | |
| 46 | |
| 47 | def __init__(self, text="Özet [1].", texts=None, model="deepseek-chat"): |
| 48 | self.text = text |
| 49 | self._texts = list(texts) if texts is not None else None |
| 50 | self.model = model |
| 51 | self.calls = 0 |
| 52 | self.last_prompt = None |
| 53 | self.last_system = None |
| 54 | self.prompts: list[str] = [] |
| 55 | |
| 56 | def chat(self, prompt, system=None, *, temperature=0.3, max_tokens=None, extra=None): |
| 57 | self.calls += 1 |
| 58 | self.last_prompt = prompt |
| 59 | self.last_system = system |
| 60 | self.prompts.append(prompt) |
| 61 | if self._texts is not None: |
| 62 | text = self._texts[min(self.calls - 1, len(self._texts) - 1)] |
| 63 | else: |
| 64 | text = self.text |
| 65 | return ChatResult(text=text, usage=Usage(input_cache_hit=0, input_cache_miss=10, |
| 66 | output=5, reasoning=0), |
| 67 | model=self.model, latency_s=0.001) |
| 68 | |
| 69 | |
| 70 | def _noop_recorder(**kwargs): |
| 71 | |
| 72 | return {"cost_usd": 0.0} |
| 73 | |
| 74 | |
| 75 | def _five_units(): |
| 76 | return [ |
| 77 | _Unit("s1", 1, "metin1"), |
| 78 | _Unit("s2", 2, "metin2"), |
| 79 | _Unit("s3", 3, "metin3"), |
| 80 | _Unit("s4", 4, "metin4"), |
| 81 | _Unit("s5", 5, "metin5"), |
| 82 | ] |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | class ResolveScopeTests(unittest.TestCase): |
| 88 | def _doc(self): |
| 89 | units = [ |
| 90 | _Unit("s1", 1, "metin1"), |
| 91 | _Unit("s2", 2, "metin2"), |
| 92 | _Unit("s3", 3, "metin3"), |
| 93 | _Unit("s3b", 3, "gizli-metin", retrieval_disi=True), |
| 94 | _Unit("s4", 4, "metin4"), |
| 95 | _Unit("s5", 5, "metin5"), |
| 96 | ] |
| 97 | return _Doc(units=units) |
| 98 | |
| 99 | def test_page_range_returns_matching_units_in_read_order(self): |
| 100 | doc = self._doc() |
| 101 | out = resolve_scope(doc, pages=[2, 3]) |
| 102 | self.assertEqual([u.span_id for u in out], ["s2", "s3"]) |
| 103 | |
| 104 | def test_span_ids_returns_matching_units_in_read_order(self): |
| 105 | doc = self._doc() |
| 106 | out = resolve_scope(doc, span_ids=["s5", "s1"]) |
| 107 | self.assertEqual([u.span_id for u in out], ["s1", "s5"]) |
| 108 | |
| 109 | def test_pages_and_span_ids_combined_are_union(self): |
| 110 | doc = self._doc() |
| 111 | out = resolve_scope(doc, pages=[1], span_ids=["s4"]) |
| 112 | self.assertEqual([u.span_id for u in out], ["s1", "s4"]) |
| 113 | |
| 114 | def test_retrieval_disi_unit_excluded_even_if_page_matches(self): |
| 115 | doc = self._doc() |
| 116 | out = resolve_scope(doc, pages=[3]) |
| 117 | self.assertEqual([u.span_id for u in out], ["s3"]) |
| 118 | self.assertNotIn("s3b", [u.span_id for u in out]) |
| 119 | |
| 120 | def test_no_scope_given_returns_empty_list(self): |
| 121 | doc = self._doc() |
| 122 | self.assertEqual(resolve_scope(doc), []) |
| 123 | self.assertEqual(resolve_scope(doc, pages=None, span_ids=None), []) |
| 124 | |
| 125 | def test_empty_scope_args_return_empty_list(self): |
| 126 | doc = self._doc() |
| 127 | self.assertEqual(resolve_scope(doc, pages=[], span_ids=[]), []) |
| 128 | |
| 129 | def test_scope_matching_nothing_returns_empty_list(self): |
| 130 | doc = self._doc() |
| 131 | self.assertEqual(resolve_scope(doc, pages=[999]), []) |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | class BuildSummaryPromptTests(unittest.TestCase): |
| 137 | def test_sources_numbered_with_pages_and_detail_citation_instructions(self): |
| 138 | blocks = [ |
| 139 | {"n": 1, "page": 10, "text": "DNA çift sarmaldır."}, |
| 140 | {"n": 2, "page": 25, "text": "Fotosentez ışığa bağlıdır."}, |
| 141 | ] |
| 142 | system, user = build_summary_prompt(blocks, scope_label="s.10-25") |
| 143 | |
| 144 | self.assertIn("[Kaynak 1 | s.10]", user) |
| 145 | self.assertIn("DNA çift sarmaldır.", user) |
| 146 | self.assertIn("[Kaynak 2 | s.25]", user) |
| 147 | self.assertIn("Fotosentez ışığa bağlıdır.", user) |
| 148 | self.assertIn("KAPSAM: s.10-25", user) |
| 149 | |
| 150 | |
| 151 | self.assertIn("DETAYLI", system) |
| 152 | self.assertIn("[N]", system) |
| 153 | self.assertIn(NO_CONTENT_SENTENCE, system) |
| 154 | |
| 155 | def test_missing_page_falls_back_to_placeholder(self): |
| 156 | blocks = [{"n": 1, "page": None, "text": "metin"}] |
| 157 | _, user = build_summary_prompt(blocks) |
| 158 | self.assertIn("[Kaynak 1 | s.?]", user) |
| 159 | |
| 160 | def test_no_scope_label_omits_kapsam_line(self): |
| 161 | blocks = [{"n": 1, "page": 1, "text": "metin"}] |
| 162 | _, user = build_summary_prompt(blocks) |
| 163 | self.assertNotIn("KAPSAM:", user) |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | class FailClosedTests(unittest.TestCase): |
| 169 | def test_empty_units_abstains_without_calling_llm(self): |
| 170 | ds = _StubLLMClient() |
| 171 | summarizer = Summarizer(ds, cost_recorder=_noop_recorder) |
| 172 | |
| 173 | result = summarizer.summarize([]) |
| 174 | |
| 175 | self.assertIsInstance(result, GroundedSummary) |
| 176 | self.assertTrue(result.abstained) |
| 177 | self.assertEqual(result.reason, "empty_scope") |
| 178 | self.assertEqual(result.text, NO_CONTENT_SENTENCE) |
| 179 | self.assertEqual(result.cost_usd, 0.0) |
| 180 | self.assertEqual(result.citations, []) |
| 181 | self.assertEqual(result.n_source_units, 0) |
| 182 | self.assertFalse(result.hierarchical) |
| 183 | self.assertEqual(ds.calls, 0, "LLM ÇAĞRILMAMALI (boş kapsam)") |
| 184 | |
| 185 | def test_cost_recorder_not_called_on_empty_scope(self): |
| 186 | calls = [] |
| 187 | |
| 188 | def spy(**kwargs): |
| 189 | calls.append(kwargs) |
| 190 | return {"cost_usd": 0.0} |
| 191 | |
| 192 | ds = _StubLLMClient() |
| 193 | summarizer = Summarizer(ds, cost_recorder=spy) |
| 194 | summarizer.summarize([]) |
| 195 | |
| 196 | self.assertEqual(calls, []) |
| 197 | |
| 198 | |
| 199 | |
| 200 | |
| 201 | class SinglePassTests(unittest.TestCase): |
| 202 | def test_single_pass_citations_map_to_correct_span_and_page(self): |
| 203 | units = [ |
| 204 | _Unit("s1", 10, "DNA çift sarmal yapıya sahiptir."), |
| 205 | _Unit("s2", 25, "Fotosentez ışığa bağlı bir tepkimedir."), |
| 206 | ] |
| 207 | ds = _StubLLMClient(text="DNA hakkında özet [1]. Fotosentez hakkında özet [2].") |
| 208 | summarizer = Summarizer(ds, cost_recorder=_noop_recorder, max_units_per_group=12) |
| 209 | |
| 210 | result = summarizer.summarize(units, scope_label="s.10-25") |
| 211 | |
| 212 | self.assertFalse(result.abstained) |
| 213 | self.assertFalse(result.hierarchical) |
| 214 | self.assertEqual(ds.calls, 1) |
| 215 | self.assertEqual(result.n_source_units, 2) |
| 216 | self.assertEqual(result.scope_pages, [10, 25]) |
| 217 | |
| 218 | c_by_n = {c["n"]: c for c in result.citations} |
| 219 | self.assertEqual(len(c_by_n), 2) |
| 220 | self.assertEqual(c_by_n[1]["span_ids"], ["s1"]) |
| 221 | self.assertEqual(c_by_n[1]["pages"], [10]) |
| 222 | self.assertEqual(c_by_n[2]["span_ids"], ["s2"]) |
| 223 | self.assertEqual(c_by_n[2]["pages"], [25]) |
| 224 | |
| 225 | self.assertGreater(result.cost_usd, 0.0) |
| 226 | self.assertIsNotNone(result.usage) |
| 227 | self.assertIn("[Kaynak 1 | s.10]", ds.last_prompt) |
| 228 | self.assertIn("[Kaynak 2 | s.25]", ds.last_prompt) |
| 229 | |
| 230 | def test_phantom_citation_silently_dropped_without_crashing(self): |
| 231 | units = [_Unit("s1", 1, "metin1")] |
| 232 | ds = _StubLLMClient(text="Bir özet [1] ve hayali [9].") |
| 233 | summarizer = Summarizer(ds, cost_recorder=_noop_recorder) |
| 234 | |
| 235 | result = summarizer.summarize(units) |
| 236 | |
| 237 | self.assertFalse(result.abstained) |
| 238 | self.assertEqual(len(result.citations), 1) |
| 239 | self.assertEqual(result.citations[0]["n"], 1) |
| 240 | |
| 241 | def test_comma_and_adjacent_bracket_citation_forms_parsed(self): |
| 242 | units = [_Unit("s1", 1, "m1"), _Unit("s2", 2, "m2"), |
| 243 | _Unit("s3", 3, "m3"), _Unit("s4", 4, "m4")] |
| 244 | ds = _StubLLMClient(text="X [1, 2]. Y [3][4].") |
| 245 | summarizer = Summarizer(ds, cost_recorder=_noop_recorder) |
| 246 | |
| 247 | result = summarizer.summarize(units) |
| 248 | |
| 249 | self.assertEqual({c["n"] for c in result.citations}, {1, 2, 3, 4}) |
| 250 | |
| 251 | |
| 252 | |
| 253 | |
| 254 | class HierarchicalTests(unittest.TestCase): |
| 255 | def test_hierarchical_triggered_above_max_units_per_group(self): |
| 256 | units = _five_units() |
| 257 | texts = [ |
| 258 | "Grup1 özeti [1][2].", |
| 259 | "Grup2 özeti [1].", |
| 260 | "Grup3 özeti [1].", |
| 261 | "Nihai özet [1][2][3].", |
| 262 | ] |
| 263 | ds = _StubLLMClient(texts=texts) |
| 264 | summarizer = Summarizer(ds, cost_recorder=_noop_recorder, max_units_per_group=2) |
| 265 | |
| 266 | result = summarizer.summarize(units) |
| 267 | |
| 268 | self.assertTrue(result.hierarchical) |
| 269 | self.assertFalse(result.abstained) |
| 270 | self.assertEqual(result.n_source_units, 5) |
| 271 | self.assertEqual(result.scope_pages, [1, 2, 3, 4, 5]) |
| 272 | |
| 273 | |
| 274 | |
| 275 | self.assertGreaterEqual(ds.calls, 4) |
| 276 | |
| 277 | |
| 278 | |
| 279 | cited = {sid for c in result.citations for sid in c["span_ids"]} |
| 280 | self.assertTrue(result.citations) |
| 281 | self.assertTrue(cited) |
| 282 | self.assertTrue(cited <= {"s1", "s2", "s3", "s5"}) |
| 283 | self.assertNotIn("s4", cited) |
| 284 | |
| 285 | self.assertGreater(result.cost_usd, 0.0) |
| 286 | self.assertIsNotNone(result.usage) |
| 287 | |
| 288 | self.assertEqual(result.usage.output, ds.calls * 5) |
| 289 | |
| 290 | def test_hierarchical_drops_group_with_no_valid_citation(self): |
| 291 | |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | |
| 301 | units = [_Unit("s1", 1, "m1"), _Unit("s2", 2, "m2"), _Unit("s3", 3, "m3")] |
| 302 | texts = [ |
| 303 | NO_CONTENT_SENTENCE, |
| 304 | "Grup2 özeti [1].", |
| 305 | "Nihai özet [2].", |
| 306 | ] |
| 307 | ds = _StubLLMClient(texts=texts) |
| 308 | summarizer = Summarizer(ds, cost_recorder=_noop_recorder, max_units_per_group=2) |
| 309 | |
| 310 | result = summarizer.summarize(units) |
| 311 | |
| 312 | self.assertTrue(result.hierarchical) |
| 313 | c_by_n = {c["n"]: c for c in result.citations} |
| 314 | self.assertNotIn(1, c_by_n) |
| 315 | self.assertEqual(c_by_n[2]["span_ids"], ["s3"]) |
| 316 | self.assertEqual(c_by_n[2]["pages"], [3]) |
| 317 | |
| 318 | |
| 319 | class HierarchicalCitationFabricationTests(unittest.TestCase): |
| 320 | |
| 321 | |
| 322 | |
| 323 | |
| 324 | |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | |
| 332 | def _kos(self, texts, units, mupg=3): |
| 333 | ds = _StubLLMClient(texts=texts) |
| 334 | s = Summarizer(ds, cost_recorder=_noop_recorder, max_units_per_group=mupg) |
| 335 | return s.summarize(units), ds |
| 336 | |
| 337 | def _dokuz(self): |
| 338 | return [_Unit(f"s{i}", i, f"metin{i}") for i in range(1, 10)] |
| 339 | |
| 340 | def test_denetimde_kosulan_senaryo_tek_atif_tek_citation(self): |
| 341 | |
| 342 | |
| 343 | texts = ["Grup1 [1].", "Grup2 [1].", "Grup3 [1].", "Nihai özet [1]."] |
| 344 | res, _ = self._kos(texts, self._dokuz()) |
| 345 | self.assertEqual([c["n"] for c in res.citations], [1]) |
| 346 | self.assertEqual(res.citations[0]["pages"], [1]) |
| 347 | sayfalar = {p for c in res.citations for p in c["pages"]} |
| 348 | self.assertNotIn(4, sayfalar) |
| 349 | self.assertNotIn(7, sayfalar) |
| 350 | |
| 351 | def test_iki_atif_iki_citation(self): |
| 352 | texts = ["Grup1 [1].", "Grup2 [1].", "Grup3 [1].", "Nihai [1][3]."] |
| 353 | res, _ = self._kos(texts, self._dokuz()) |
| 354 | self.assertEqual([c["n"] for c in res.citations], [1, 3]) |
| 355 | self.assertEqual({p for c in res.citations for p in c["pages"]}, {1, 7}) |
| 356 | |
| 357 | def test_hic_atif_yoksa_citation_da_yok(self): |
| 358 | |
| 359 | texts = ["Grup1 [1].", "Grup2 [1].", "Grup3 [1].", "Nihai özet, atıf yok."] |
| 360 | res, _ = self._kos(texts, self._dokuz()) |
| 361 | self.assertEqual(res.citations, []) |
| 362 | |
| 363 | def test_hayalet_atif_sessizce_elenir(self): |
| 364 | |
| 365 | |
| 366 | texts = ["Grup1 [1].", "Grup2 [1].", "Grup3 [1].", "Nihai [1][9]."] |
| 367 | res, _ = self._kos(texts, self._dokuz()) |
| 368 | self.assertEqual([c["n"] for c in res.citations], [1]) |
| 369 | |
| 370 | def test_her_donen_atif_metinde_gercekten_yaziyor(self): |
| 371 | |
| 372 | import re |
| 373 | texts = ["G1 [1].", "G2 [1].", "G3 [1].", "Nihai [2] ve ayrıca [3]."] |
| 374 | res, _ = self._kos(texts, self._dokuz()) |
| 375 | metindeki = {int(n) for n in re.findall(r"\[(\d+)\]", res.text)} |
| 376 | self.assertTrue({c["n"] for c in res.citations} <= metindeki) |
| 377 | self.assertEqual({c["n"] for c in res.citations}, {2, 3}) |
| 378 | |
| 379 | def test_merge_cekimser_olursa_abstained_true(self): |
| 380 | |
| 381 | |
| 382 | texts = ["G1 [1].", "G2 [1].", "G3 [1].", NO_CONTENT_SENTENCE] |
| 383 | res, _ = self._kos(texts, self._dokuz()) |
| 384 | self.assertTrue(res.abstained) |
| 385 | self.assertEqual(res.reason, "llm_no_content") |
| 386 | self.assertEqual(res.citations, []) |
| 387 | |
| 388 | def test_cekimser_olmayan_merge_abstained_false_kalir(self): |
| 389 | texts = ["G1 [1].", "G2 [1].", "G3 [1].", "Nihai özet [1]."] |
| 390 | res, _ = self._kos(texts, self._dokuz()) |
| 391 | self.assertFalse(res.abstained) |
| 392 | self.assertEqual(res.reason, "") |
| 393 | |
| 394 | def test_ozyinelemeli_seviyede_de_gecerli(self): |
| 395 | |
| 396 | |
| 397 | texts = ["G [1]." for _ in range(5)] + ["M [1]." for _ in range(10)] |
| 398 | res, ds = self._kos(texts, self._dokuz(), mupg=2) |
| 399 | self.assertGreater(ds.calls, 6) |
| 400 | self.assertEqual(len(res.citations), 1) |
| 401 | self.assertEqual(res.citations[0]["pages"], [1]) |
| 402 | |
| 403 | def test_maliyet_hala_tum_seviyelerin_toplami(self): |
| 404 | |
| 405 | texts = ["G1 [1].", "G2 [1].", "G3 [1].", "Nihai, atıf yok."] |
| 406 | res, ds = self._kos(texts, self._dokuz()) |
| 407 | self.assertGreater(res.cost_usd, 0.0) |
| 408 | self.assertEqual(res.usage.output, ds.calls * 5) |
| 409 | |
| 410 | |
| 411 | |
| 412 | |
| 413 | class CostRecorderSpyTests(unittest.TestCase): |
| 414 | def test_cost_recorder_called_with_ozet_module_single_pass(self): |
| 415 | calls = [] |
| 416 | |
| 417 | def spy(**kwargs): |
| 418 | calls.append(kwargs) |
| 419 | return {"cost_usd": 0.0} |
| 420 | |
| 421 | units = [_Unit("s1", 1, "m1")] |
| 422 | ds = _StubLLMClient(text="Özet [1].") |
| 423 | summarizer = Summarizer(ds, module="ozet", cost_recorder=spy) |
| 424 | |
| 425 | result = summarizer.summarize(units) |
| 426 | |
| 427 | self.assertFalse(result.abstained) |
| 428 | self.assertEqual(len(calls), 1) |
| 429 | call = calls[0] |
| 430 | self.assertEqual(call["module"], "ozet") |
| 431 | self.assertEqual(call["model"], "deepseek-chat") |
| 432 | self.assertIs(call["usage"], result.usage) |
| 433 | self.assertEqual(call["items"], 1) |
| 434 | |
| 435 | def test_cost_recorder_called_once_per_real_llm_call_hierarchical(self): |
| 436 | calls = [] |
| 437 | |
| 438 | def spy(**kwargs): |
| 439 | calls.append(kwargs) |
| 440 | return {"cost_usd": 0.0} |
| 441 | |
| 442 | units = _five_units() |
| 443 | texts = ["Grup1 [1][2].", "Grup2 [1].", "Grup3 [1].", "Nihai [1][2][3]."] |
| 444 | ds = _StubLLMClient(texts=texts) |
| 445 | summarizer = Summarizer(ds, module="ozet", cost_recorder=spy, max_units_per_group=2) |
| 446 | |
| 447 | summarizer.summarize(units) |
| 448 | |
| 449 | |
| 450 | self.assertEqual(len(calls), ds.calls) |
| 451 | self.assertTrue(all(c["module"] == "ozet" for c in calls)) |
| 452 | |
| 453 | |
| 454 | if __name__ == "__main__": |
| 455 | unittest.main() |