Ayristiriciyi sikilastir, hayalet [N]'i kirp, cekimserlikten
Browse files at this commitaaf05cff00a31a73ccbba9dad86e897524728e35Parent: 95f922b- fix
- ayristiriciyi sikilastir, hayalet [N]'i kirp, cekimserlikten
5 changed files +338 -47
- src/generate/citations.py +96 -0
- src/generate/generator.py +62 -25
- src/service/handler.py +4 -0
- src/summarize/summarizer.py +9 -18
- tests/unit/test_generate.py +167 -4
src/generate/citations.pyadded+96 -0
| @@ -0,0 +1,96 @@ | |||
| 1 | +"""Atıf işaretçisi (`[N]`) ayrıştırma — **TEK KAYNAK**. | ||
| 2 | + | ||
| 3 | +M2-5 (#57, EXP-010/ACC-04 + ACC-14). Bu mantık eskiden iki yerde ayrı ayrı | ||
| 4 | +duruyordu (`generate/generator.py` ve `summarize/summarizer.py`); ikincisinin | ||
| 5 | +yorumu "KASITLI kod tekrarı ... regex davranışı değişirse HER İKİ modülde de | ||
| 6 | +senkron güncellenmeli" diyordu. Böyle bir senkron sözü kodda tutulmaz — ACC-10'da | ||
| 7 | +(parent genişletme) eval ile üretim tam bu şekilde ayrışmıştı ve yayınlanmış | ||
| 8 | +sayılar üretimi temsil etmemişti. Bu yüzden ortak modüle alındı. | ||
| 9 | +""" | ||
| 10 | +from __future__ import annotations | ||
| 11 | + | ||
| 12 | +import re | ||
| 13 | + | ||
| 14 | +# ASCII rakam ZORUNLU: `\d` + `str.isdigit()` Unicode'dur, `[١]` (Arapça-Hint) | ||
| 15 | +# `1` olarak kabul ediliyordu (koşularak kanıtlandı). | ||
| 16 | +CITATION_RE = re.compile(r"\[([0-9,\s]+)\]", re.ASCII) | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +def parse_citations(text: str, n_sources: int | None = None): | ||
| 20 | + """`[N]` işaretlerini üç kovaya ayırır. | ||
| 21 | + | ||
| 22 | + Döner: `(atıflanan, hayalet, belirsiz_gruplar)` | ||
| 23 | + - **atıflanan**: bütün parçaları `1..n_sources` aralığında olan gruplar. | ||
| 24 | + - **hayalet**: TEK parçalı ve aralık dışı grup (`[9]`, `[1000000]`). | ||
| 25 | + Model gerçekten atıf yapmaya çalışmış ama çözülemiyor → `invalid_citations` | ||
| 26 | + olarak raporlanır ve kullanıcıya gösterilen metinden **kırpılır** (#62). | ||
| 27 | + - **belirsiz_gruplar**: ÇOK parçalı ve içinde aralık dışı parça olan grup | ||
| 28 | + (`[0,1]`, `[1, 9]`). Atıf sayılmaz, metinden **kırpılmaz**, hayalet de | ||
| 29 | + sayılmaz — yalnız telemetriye yazılır. | ||
| 30 | + | ||
| 31 | + Neden bu üçlü ayrım (#57/ACC-04) — koşulan kanıt: | ||
| 32 | + `"Olasılık değeri [0,1] aralığında yer alır [2]."` eski ayrıştırıcıda | ||
| 33 | + `[0,1,2]` üretiyordu; `0` hayalet sayılıyor ama **`1` geçerli bir kaynağa | ||
| 34 | + eşlenip s.5 UYDURMA atıf olarak cevaba ekleniyordu**. Model yalnız `[2]`'yi | ||
| 35 | + atıflamıştı. Golden set'te kimya ve fizik var; aralık gösterimi olağan. | ||
| 36 | + | ||
| 37 | + İki tasarım kararı ve gerekçeleri: | ||
| 38 | + | ||
| 39 | + 1. *Çok parçalı grupta bir parça bile dışarıdaysa grubun TAMAMI atıl sayılır.* | ||
| 40 | + Zarar asimetriktir: veriyi atıf sanmak öğrenciye **gerçek sayfa numarasıyla | ||
| 41 | + uydurma bir atıf** gösterir (ürünün temel sözünün ihlali); atıfı veri sanmak | ||
| 42 | + yalnız bir atıf kaybettirir ve atıfsız kalan cevap zaten `ungrounded` | ||
| 43 | + kapısından çekimser olur. Bu yüzden `[1, 9]` artık `1`'i de atıflamaz. | ||
| 44 | + 2. *Belirsiz grup metinden KIRPILMAZ.* `[0,1]` cümlenin içeriğidir; kırpmak | ||
| 45 | + "Olasılık değeri aralığında yer alır" gibi **bozuk bir cevap** üretir. | ||
| 46 | + Kırpma yalnız tek parçalı hayalet işaretler için güvenlidir. | ||
| 47 | + | ||
| 48 | + `n_sources` verilmezse aralık denetimi yapılmaz (ham ayrıştırma). | ||
| 49 | + """ | ||
| 50 | + atiflanan: list[int] = [] | ||
| 51 | + hayalet: list[int] = [] | ||
| 52 | + belirsiz: list[str] = [] | ||
| 53 | + for m in CITATION_RE.finditer(text): | ||
| 54 | + parts = [p.strip() for p in m.group(1).split(",")] | ||
| 55 | + if any(not p or not p.isascii() or not p.isdigit() for p in parts): | ||
| 56 | + continue # `[1.2]`, `[١]`, `[ ]` -> atıf değil | ||
| 57 | + sayilar = [int(p) for p in parts] | ||
| 58 | + if n_sources is None: | ||
| 59 | + atiflanan.extend(sayilar) | ||
| 60 | + continue | ||
| 61 | + disarida = [n for n in sayilar if n < 1 or n > n_sources] | ||
| 62 | + if not disarida: | ||
| 63 | + atiflanan.extend(sayilar) | ||
| 64 | + elif len(sayilar) == 1: | ||
| 65 | + hayalet.append(sayilar[0]) | ||
| 66 | + else: | ||
| 67 | + belirsiz.append(m.group(0)) | ||
| 68 | + return atiflanan, hayalet, belirsiz | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def parse_citation_ns(text: str, n_sources: int | None = None) -> list[int]: | ||
| 72 | + """Yalnız atıflanan numaralar (bkz. `parse_citations`).""" | ||
| 73 | + return parse_citations(text, n_sources)[0] | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +def strip_phantom(text: str, hayalet: list[int]) -> str: | ||
| 77 | + """Kullanıcıya gösterilen metinden **çözülemeyen tek parçalı** `[N]` | ||
| 78 | + işaretlerini kırpar (#62/ACC-12: geçersiz işaret metinde duruyor ama | ||
| 79 | + karşılığında tıklanabilir atıf kaydı olmuyordu). | ||
| 80 | + | ||
| 81 | + Yalnız gösterim içindir; ölçümde ham metin kullanılır. Çok parçalı belirsiz | ||
| 82 | + gruplar KIRPILMAZ — onlar cümlenin içeriği olabilir (bkz. `parse_citations`). | ||
| 83 | + """ | ||
| 84 | + if not hayalet: | ||
| 85 | + return text | ||
| 86 | + out = text | ||
| 87 | + for n in dict.fromkeys(hayalet): | ||
| 88 | + out = re.sub(r"\[\s*" + str(n) + r"\s*\]", "", out) | ||
| 89 | + out = re.sub(r"[ \t]+([.,;:!?])", r"\1", out) | ||
| 90 | + out = re.sub(r"[ \t]{2,}", " ", out) | ||
| 91 | + return out.strip() | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +def strip_citations(text: str) -> str: | ||
| 95 | + """Metinden atıf işaretlerini çıkarır (karşılaştırma/normalizasyon için).""" | ||
| 96 | + return CITATION_RE.sub("", text) | ||
src/generate/generator.pymodified+62 -25
| @@ -22,13 +22,14 @@ from __future__ import annotations | |||
| 22 | 22 | ||
| 23 | import re | 23 | import re |
| 24 | from dataclasses import dataclass, field, replace | 24 | from dataclasses import dataclass, field, replace |
| 25 | -from difflib import SequenceMatcher | ||
| 26 | 25 | ||
| 27 | from .. import costlog | 26 | from .. import costlog |
| 28 | from ..guard import check_input, check_output | 27 | from ..guard import check_input, check_output |
| 29 | from ..pricing import Usage, cost_usd as pricing_cost_usd | 28 | from ..pricing import Usage, cost_usd as pricing_cost_usd |
| 30 | from ..providers.deepseek import DeepSeek | 29 | from ..providers.deepseek import DeepSeek |
| 31 | from ..rerank.pipeline import rerank_select | 30 | from ..rerank.pipeline import rerank_select |
| 31 | +from .citations import (CITATION_RE, parse_citation_ns, parse_citations, | ||
| 32 | + strip_phantom) | ||
| 32 | from .prompt import ABSTAIN_SENTENCE, build_grounded_prompt | 33 | from .prompt import ABSTAIN_SENTENCE, build_grounded_prompt |
| 33 | 34 | ||
| 34 | # answer(role_ctx=...) için sentinel: "verilmedi → __init__'teki role_ctx'i kullan" | 35 | # answer(role_ctx=...) için sentinel: "verilmedi → __init__'teki role_ctx'i kullan" |
| @@ -38,9 +39,7 @@ _USE_INIT_ROLE = object() | |||
| 38 | # Parantez içini yakalar ("1", "1, 2", "1,2" ...); virgül/boşlukla ayrılmış çoklu | 39 | # Parantez içini yakalar ("1", "1, 2", "1,2" ...); virgül/boşlukla ayrılmış çoklu |
| 39 | # atıfları TEK eşleşmede yakalamak için [\d,\s]+ kullanılır — [1][2] ve [1] [2] | 40 | # atıfları TEK eşleşmede yakalamak için [\d,\s]+ kullanılır — [1][2] ve [1] [2] |
| 40 | # gibi bitişik/ayrı parantezler ise doğal olarak iki ayrı eşleşme üretir. | 41 | # gibi bitişik/ayrı parantezler ise doğal olarak iki ayrı eşleşme üretir. |
| 41 | -_CITATION_RE = re.compile(r"\[([\d,\s]+)\]") | 42 | +_ABSTAIN_MATCH_THRESHOLD = 0.90 # (#58 ile kullanımdan kalktı; geri uyum için duruyor) |
| 42 | - | ||
| 43 | -_ABSTAIN_MATCH_THRESHOLD = 0.90 # normalize edilmiş cevap ~ ABSTAIN_SENTENCE benzerliği | ||
| 44 | 43 | ||
| 45 | 44 | ||
| 46 | @dataclass | 45 | @dataclass |
| @@ -57,16 +56,8 @@ class GroundedAnswer: | |||
| 57 | cache_hit: bool = False # True -> ResponseCache'ten döndü, LLM/retrieval HİÇ ÇALIŞMADI | 56 | cache_hit: bool = False # True -> ResponseCache'ten döndü, LLM/retrieval HİÇ ÇALIŞMADI |
| 58 | 57 | ||
| 59 | 58 | ||
| 60 | -def _parse_citation_ns(text: str) -> list[int]: | 59 | +_CITATION_RE = CITATION_RE # geri uyum (eski içe aktarımlar) |
| 61 | - """Metindeki `[N]`, `[N, M]`, `[N,M]`, `[N][M]`, `[N] [M]` atıflarının hepsini | 60 | +_parse_citation_ns = parse_citation_ns |
| 62 | - ayrıştırır: parantez içini yakala (`[\\d,\\s]+`), virgülle böl, int'e çevir.""" | ||
| 63 | - ns: list[int] = [] | ||
| 64 | - for group in _CITATION_RE.findall(text): | ||
| 65 | - for part in group.split(","): | ||
| 66 | - part = part.strip() | ||
| 67 | - if part.isdigit(): | ||
| 68 | - ns.append(int(part)) | ||
| 69 | - return ns | ||
| 70 | 61 | ||
| 71 | 62 | ||
| 72 | def _normalize_for_abstain_compare(text: str) -> str: | 63 | def _normalize_for_abstain_compare(text: str) -> str: |
| @@ -82,16 +73,49 @@ def _normalize_for_abstain_compare(text: str) -> str: | |||
| 82 | _ABSTAIN_NORM = _normalize_for_abstain_compare(ABSTAIN_SENTENCE) | 73 | _ABSTAIN_NORM = _normalize_for_abstain_compare(ABSTAIN_SENTENCE) |
| 83 | 74 | ||
| 84 | 75 | ||
| 76 | +# M2-6 (#58, EXP-010/ACC-05) — KARAKTER BENZERLIGI BIRAKILDI. | ||
| 77 | +# Eski olcut: difflib.SequenceMatcher orani >= 0.90. Turkcede olumlu/olumsuz ayrimi tek | ||
| 78 | +# ek oldugu icin metrik ANLAMI TERS cumleleri de yakaliyordu (oranlar hesaplandi): | ||
| 79 | +# "Kaynaklarda bu bilgi bulunamadi." 1,0000 cekimser DOGRU | ||
| 80 | +# "Kaynaklarda bu bilgi bulunmaktadir." 0,9231 cekimser YANLIS (pozitif bastirildi) | ||
| 81 | +# "Kaynaklarda bu bilgi bulunmaktadir [1]." 0,9231 cekimser YANLIS (ATIFLI cevap bastirildi) | ||
| 82 | +# "Kaynaklarda bu bilgi bulunmuyor." 0,8710 cevap YANLIS (gercek cekimser kacti) | ||
| 83 | +# Yani esik IKI YONDE de yanlisti. | ||
| 84 | +# | ||
| 85 | +# Yeni olcut: tam esitlik + OLUMSUZLUK KOKU. Kritik guvenlik agi zaten | ||
| 86 | +# `if not citations` (temellendirme kapisi) -- bu fonksiyonun agresif olmasina | ||
| 87 | +# gerek YOK; yanlis pozitifi kisa "evet + kaynak var" cevaplarinda recall | ||
| 88 | +# kaybina yol aciyordu. | ||
| 89 | +_ABSTAIN_NEGATIVE_STEMS = ( | ||
| 90 | + "bulunamad", "bulunmuyor", "bulamad", "yer almıyor", "yer almamakta", | ||
| 91 | + "geçmiyor", "mevcut değil", "yok", | ||
| 92 | +) | ||
| 93 | +# Olumsuzluk koku TEK BASINA yetmez: "DNA cift sarmaldir ama atif yok." cumlesi | ||
| 94 | +# `yok` icerdigi icin cekimser sayiliyordu (testte yakalandi). Cumlenin KAYNAKLAR | ||
| 95 | +# HAKKINDA olmasi da sart -- cekimserlik "kaynakta bulamadim" demektir. | ||
| 96 | +_ABSTAIN_SUBJECT_STEMS = ("kaynak", "kaynakta", "metinde", "belgede", "verilen") | ||
| 97 | + | ||
| 98 | + | ||
| 85 | def _looks_like_abstain(text: str) -> bool: | 99 | def _looks_like_abstain(text: str) -> bool: |
| 86 | - """Cevap, prompt'taki kaynak-yok cümlesine (ABSTAIN_SENTENCE) eşit ya da çok | 100 | + """Cevap, kaynak-yok cümlesinin bir varyantı mı? |
| 87 | - yakın mı? (post-hoc abstain algılama — model FAIL-CLOSED eşiğini geçti ama | 101 | + |
| 88 | - fiilen kaynaksız olduğunu kendi söyledi).""" | 102 | + İki koşul BİRLİKTE aranır (#58): |
| 103 | + 1. Normalize edilmiş metin `ABSTAIN_SENTENCE`'a eşit **ya da** onun belirgin | ||
| 104 | + bir varyantı (aynı özne + olumsuzluk kökü), | ||
| 105 | + 2. metinde **hiç atıf işareti yok** — atıflı bir cevap tanım gereği çekimser | ||
| 106 | + değildir. (Eskiden "Kaynaklarda bu bilgi bulunmaktadır [1]." bastırılıyordu.) | ||
| 107 | + """ | ||
| 89 | norm = _normalize_for_abstain_compare(text) | 108 | norm = _normalize_for_abstain_compare(text) |
| 90 | if not norm: | 109 | if not norm: |
| 91 | return False | 110 | return False |
| 92 | if norm == _ABSTAIN_NORM: | 111 | if norm == _ABSTAIN_NORM: |
| 93 | return True | 112 | return True |
| 94 | - return SequenceMatcher(None, norm, _ABSTAIN_NORM).ratio() >= _ABSTAIN_MATCH_THRESHOLD | 113 | + if parse_citation_ns(text): |
| 114 | + return False # atıflı cevap çekimser sayılmaz | ||
| 115 | + if len(norm) > len(_ABSTAIN_NORM) * 2: | ||
| 116 | + return False # uzun, gerçek bir cevap | ||
| 117 | + return (any(k in norm for k in _ABSTAIN_SUBJECT_STEMS) | ||
| 118 | + and any(k in norm for k in _ABSTAIN_NEGATIVE_STEMS)) | ||
| 95 | 119 | ||
| 96 | 120 | ||
| 97 | def _is_effectively_empty(text: str) -> bool: | 121 | def _is_effectively_empty(text: str) -> bool: |
| @@ -417,19 +441,28 @@ class Generator: | |||
| 417 | max_tokens=max_tokens) | 441 | max_tokens=max_tokens) |
| 418 | 442 | ||
| 419 | # cevaptaki [N]/[N,M]/[N][M] atıflarını ayrıştır → gerçek kaynağa eşle (kaynak yer bulma) | 443 | # cevaptaki [N]/[N,M]/[N][M] atıflarını ayrıştır → gerçek kaynağa eşle (kaynak yer bulma) |
| 420 | - cited_ns = sorted(set(_parse_citation_ns(result.text))) | 444 | + # #57: kaynak sayısı VERİLİR → `[0,1]` gibi veri gösterimleri atıf sanılıp |
| 445 | + # UYDURMA atıf üretmesin. Üç kova döner (bkz. generate/citations.py). | ||
| 446 | + ham_ns, hayalet_ns, belirsiz_gruplar = parse_citations(result.text, | ||
| 447 | + len(numbered_sources)) | ||
| 448 | + cited_ns = sorted(set(ham_ns)) | ||
| 421 | citations = [] | 449 | citations = [] |
| 422 | used_source_ids = [] | 450 | used_source_ids = [] |
| 423 | - invalid_citations = [] | 451 | + invalid_citations = sorted(set(hayalet_ns)) |
| 424 | for n in cited_ns: | 452 | for n in cited_ns: |
| 425 | src = source_lookup.get(n) | 453 | src = source_lookup.get(n) |
| 426 | - if src is None: | 454 | + if src is None: # aralık denetimi sonrası olmamalı |
| 427 | - invalid_citations.append(n) # kaynak sayısını aşan [N] — patlamadan işaretle | 455 | + invalid_citations.append(n) |
| 428 | continue | 456 | continue |
| 429 | citations.append({"n": n, "chunk_id": src["chunk_id"], | 457 | citations.append({"n": n, "chunk_id": src["chunk_id"], |
| 430 | "span_ids": src["span_ids"], "pages": src["pages"], | 458 | "span_ids": src["span_ids"], "pages": src["pages"], |
| 431 | "ders": self.ders}) | 459 | "ders": self.ders}) |
| 432 | used_source_ids.append(src["chunk_id"]) | 460 | used_source_ids.append(src["chunk_id"]) |
| 461 | + invalid_citations = sorted(set(invalid_citations)) | ||
| 462 | + # #62: hayalet `[N]` kullanıcıya gösterilen metinden KIRPILIR — eskiden | ||
| 463 | + # metinde duruyor ama karşılığında tıklanabilir atıf kaydı olmuyordu. | ||
| 464 | + # Belirsiz gruplar (`[0,1]`) kırpılmaz: onlar cümlenin içeriği olabilir. | ||
| 465 | + gosterim_metni = strip_phantom(result.text, invalid_citations) | ||
| 433 | 466 | ||
| 434 | if invalid_citations and not citations: | 467 | if invalid_citations and not citations: |
| 435 | reason = "all_citations_phantom" # [N] var ama HİÇBİRİ geçerli değil | 468 | reason = "all_citations_phantom" # [N] var ama HİÇBİRİ geçerli değil |
| @@ -461,7 +494,7 @@ class Generator: | |||
| 461 | # post-hoc abstain algılama: cevap kaynak-yok cümlesine çok yakın YA DA | 494 | # post-hoc abstain algılama: cevap kaynak-yok cümlesine çok yakın YA DA |
| 462 | # (geçerli atıf yok + cevap fiilen boş) → model aslında çekimser kaldı. | 495 | # (geçerli atıf yok + cevap fiilen boş) → model aslında çekimser kaldı. |
| 463 | if _looks_like_abstain(result.text) or (not citations and _is_effectively_empty(result.text)): | 496 | if _looks_like_abstain(result.text) or (not citations and _is_effectively_empty(result.text)): |
| 464 | - return GroundedAnswer(text=result.text, citations=citations, | 497 | + return GroundedAnswer(text=gosterim_metni, citations=citations, |
| 465 | used_source_ids=used_source_ids, | 498 | used_source_ids=used_source_ids, |
| 466 | invalid_citations=invalid_citations, abstained=True, | 499 | invalid_citations=invalid_citations, abstained=True, |
| 467 | reason="model_abstained", usage=result.usage, | 500 | reason="model_abstained", usage=result.usage, |
| @@ -479,13 +512,17 @@ class Generator: | |||
| 479 | reason=r, usage=result.usage, cost_usd=usd, | 512 | reason=r, usage=result.usage, cost_usd=usd, |
| 480 | latency_s=result.latency_s) | 513 | latency_s=result.latency_s) |
| 481 | 514 | ||
| 482 | - final_answer = GroundedAnswer(text=result.text, citations=citations, | 515 | + final_answer = GroundedAnswer(text=gosterim_metni, citations=citations, |
| 483 | used_source_ids=used_source_ids, | 516 | used_source_ids=used_source_ids, |
| 484 | invalid_citations=invalid_citations, abstained=False, | 517 | invalid_citations=invalid_citations, abstained=False, |
| 485 | reason=reason, usage=result.usage, cost_usd=usd, | 518 | reason=reason, usage=result.usage, cost_usd=usd, |
| 486 | latency_s=result.latency_s) | 519 | latency_s=result.latency_s) |
| 487 | _tr("decision", stage="generate", abstained=False, reason=reason or "answer", | 520 | _tr("decision", stage="generate", abstained=False, reason=reason or "answer", |
| 488 | - n_citations=len(citations), cost_usd=round(usd, 6)) | 521 | + n_citations=len(citations), n_phantom=len(invalid_citations), |
| 522 | + # #57 telemetrisi: `[0,1]` gibi belirsiz gruplar atıf sayılmadı. | ||
| 523 | + # Sıklığı bilinmeden kuralın doğru eşikte olduğu iddia EDİLEMEZ. | ||
| 524 | + n_belirsiz_grup=len(belirsiz_gruplar), | ||
| 525 | + cost_usd=round(usd, 6)) | ||
| 489 | 526 | ||
| 490 | # Yalnız GERÇEK (abstained olmayan) cevaplar cache'e yazılır. FAIL-CLOSED | 527 | # Yalnız GERÇEK (abstained olmayan) cevaplar cache'e yazılır. FAIL-CLOSED |
| 491 | # abstain zaten LLM'i hiç çağırmadı (cache'lemenin maliyet kazancı yok); | 528 | # abstain zaten LLM'i hiç çağırmadı (cache'lemenin maliyet kazancı yok); |
src/service/handler.pymodified+4 -0
| @@ -71,6 +71,10 @@ def _answer_to_dict(a) -> dict: | |||
| 71 | "span_ids": c.get("span_ids", []), "pages": c.get("pages", []), | 71 | "span_ids": c.get("span_ids", []), "pages": c.get("pages", []), |
| 72 | "ders": c.get("ders", "")} for c in a.citations], | 72 | "ders": c.get("ders", "")} for c in a.citations], |
| 73 | "used_source_ids": list(a.used_source_ids), | 73 | "used_source_ids": list(a.used_source_ids), |
| 74 | + # #62 (EXP-010/ACC-12): hayalet `[N]` numaralari payload'a HIC girmiyordu. | ||
| 75 | + # Metinden kirpilsa bile backend'in "bu cevapta cozulemeyen atif vardi" | ||
| 76 | + # bilgisine erisimi olmali (telemetri + kalite kapisi O-?/A-*). | ||
| 77 | + "invalid_citations": list(getattr(a, "invalid_citations", []) or []), | ||
| 74 | "cost_usd": round(a.cost_usd, 6), | 78 | "cost_usd": round(a.cost_usd, 6), |
| 75 | "cache_hit": bool(getattr(a, "cache_hit", False)), | 79 | "cache_hit": bool(getattr(a, "cache_hit", False)), |
| 76 | } | 80 | } |
src/summarize/summarizer.pymodified+9 -18
| @@ -27,24 +27,15 @@ from .. import costlog | |||
| 27 | from ..ingest.canonical import CanonicalUnit | 27 | from ..ingest.canonical import CanonicalUnit |
| 28 | from ..pricing import Usage, cost_usd as pricing_cost_usd | 28 | from ..pricing import Usage, cost_usd as pricing_cost_usd |
| 29 | from ..providers.deepseek import DeepSeek | 29 | from ..providers.deepseek import DeepSeek |
| 30 | +from ..generate.citations import CITATION_RE, parse_citation_ns | ||
| 30 | from .prompt import NO_CONTENT_SENTENCE, build_summary_prompt | 31 | from .prompt import NO_CONTENT_SENTENCE, build_summary_prompt |
| 31 | 32 | ||
| 32 | -# generator.py'daki (src/generate/generator.py) [N]/[N,M]/[N][M] atıf ayrıştırma | 33 | +# #57: bu mantık eskiden burada AYRI bir kopyaydı ve yorumu "KASITLI kod tekrarı |
| 33 | -# deseniyle BİREBİR AYNI davranış — KASITLI kod tekrarı: iki modül birbirinin | 34 | +# ... regex davranışı değişirse HER İKİ modülde de senkron güncellenmeli" diyordu. |
| 34 | -# private (alt çizgili) fonksiyonlarına bağlanmasın diye burada yeniden | 35 | +# Böyle bir senkron sözü kodda tutulmaz (ACC-10'da tam bu şekilde ayrışmıştı), |
| 35 | -# tanımlanır. Regex davranışı değişirse HER İKİ modülde de senkron güncellenmeli. | 36 | +# bu yüzden tek kaynağa taşındı. |
| 36 | -_CITATION_RE = re.compile(r"\[([\d,\s]+)\]") | 37 | +_CITATION_RE = CITATION_RE |
| 37 | - | 38 | +_parse_citation_ns = parse_citation_ns |
| 38 | - | ||
| 39 | -def _parse_citation_ns(text: str) -> list[int]: | ||
| 40 | - """`[N]`, `[N, M]`, `[N,M]`, `[N][M]`, `[N] [M]` atıflarının hepsini ayrıştırır.""" | ||
| 41 | - ns: list[int] = [] | ||
| 42 | - for group in _CITATION_RE.findall(text): | ||
| 43 | - for part in group.split(","): | ||
| 44 | - part = part.strip() | ||
| 45 | - if part.isdigit(): | ||
| 46 | - ns.append(int(part)) | ||
| 47 | - return ns | ||
| 48 | 39 | ||
| 49 | 40 | ||
| 50 | def _format_pages(pages: list[int]) -> str: | 41 | def _format_pages(pages: list[int]) -> str: |
| @@ -176,7 +167,7 @@ class Summarizer: | |||
| 176 | # cevaptaki [N]/[N,M]/[N][M] atıflarını ayrıştır -> gerçek birime eşle | 167 | # cevaptaki [N]/[N,M]/[N][M] atıflarını ayrıştır -> gerçek birime eşle |
| 177 | # (kaynak yer bulma). Kaynak sayısını aşan [N] -> sessizce elenir (hayalet | 168 | # (kaynak yer bulma). Kaynak sayısını aşan [N] -> sessizce elenir (hayalet |
| 178 | # atıf patlamaya değil sessiz elemeye yol açar, generator.py ile TUTARLI). | 169 | # atıf patlamaya değil sessiz elemeye yol açar, generator.py ile TUTARLI). |
| 179 | - cited_ns = sorted(set(_parse_citation_ns(result.text))) | 170 | + cited_ns = sorted(set(_parse_citation_ns(result.text, len(units)))) # #57 |
| 180 | citations = [] | 171 | citations = [] |
| 181 | for n in cited_ns: | 172 | for n in cited_ns: |
| 182 | src = source_lookup.get(n) | 173 | src = source_lookup.get(n) |
| @@ -228,7 +219,7 @@ class Summarizer: | |||
| 228 | # uydurmaz" diyordu -- dogru, ama KOD uyduruyordu. Ozet yuzeyinde atif | 219 | # uydurmaz" diyordu -- dogru, ama KOD uyduruyordu. Ozet yuzeyinde atif |
| 229 | # precision'i yapisal olarak 1/grup_sayisi'na dusuyordu. | 220 | # precision'i yapisal olarak 1/grup_sayisi'na dusuyordu. |
| 230 | # Cozum tek-gecis yolundaki desenin AYNISI: yalniz atiflanan N'ler. | 221 | # Cozum tek-gecis yolundaki desenin AYNISI: yalniz atiflanan N'ler. |
| 231 | - cited_ns = sorted(set(_parse_citation_ns(result.text))) | 222 | + cited_ns = sorted(set(_parse_citation_ns(result.text, len(summaries)))) # #57 |
| 232 | citations = [] | 223 | citations = [] |
| 233 | for n in cited_ns: | 224 | for n in cited_ns: |
| 234 | src = merge_lookup.get(n) | 225 | src = merge_lookup.get(n) |
tests/unit/test_generate.pymodified+167 -4
| @@ -372,17 +372,39 @@ class CommaAndAdjacentCitationRegexTests(unittest.TestCase): | |||
| 372 | self.assertFalse(result.abstained) | 372 | self.assertFalse(result.abstained) |
| 373 | self.assertEqual({c["n"] for c in result.citations}, {1, 2, 3, 4}) | 373 | self.assertEqual({c["n"] for c in result.citations}, {1, 2, 3, 4}) |
| 374 | 374 | ||
| 375 | - def test_phantom_still_flagged_with_comma_citation(self): | 375 | + def test_mixed_group_is_no_longer_partially_cited(self): |
| 376 | - # [1, 9]: 1 geçerli, 9 hayalet (yalnız 2 kaynak var) — patlamadan işaretlenmeli | 376 | + """SÖZLEŞME DEĞİŞTİ (#57, 2026-09-11). |
| 377 | + | ||
| 378 | + Eski davranış: `[1, 9]` (2 kaynak var) → `1` atıflanır, `9` hayalet | ||
| 379 | + işaretlenir, cevap sunulur. Bu tam olarak ACC-04'ün zarar yoluydu: | ||
| 380 | + `"Olasılık değeri [0,1] aralığında yer alır [2]."` cümlesinde de `1` | ||
| 381 | + geçerli bir kaynağa eşlenip **s.5 uydurma atıf** olarak cevaba | ||
| 382 | + ekleniyordu — model yalnız `[2]`'yi atıflamıştı. | ||
| 383 | + | ||
| 384 | + Yeni kural: çok parçalı bir grupta tek parça bile aralık dışındaysa | ||
| 385 | + grubun tamamı atıl sayılır. `[1, 9]`'un gerçekte "1 ve 9'a atıf" mı | ||
| 386 | + yoksa bir veri gösterimi mi olduğu BİLİNEMEZ; zarar asimetrik olduğu | ||
| 387 | + için güvenli taraf seçilir (uydurma atıf > kayıp atıf). Atıfsız kalan | ||
| 388 | + cevap `ungrounded_no_citations` kapısından çekimser olur. | ||
| 389 | + """ | ||
| 377 | deepseek = _StubDeepSeek(text="X [1, 9].") | 390 | deepseek = _StubDeepSeek(text="X [1, 9].") |
| 378 | gen = _make_generator(deepseek, scores={"c1": 0.9, "c2": 0.85}) | 391 | gen = _make_generator(deepseek, scores={"c1": 0.9, "c2": 0.85}) |
| 379 | result = gen.answer("DNA nedir?") | 392 | result = gen.answer("DNA nedir?") |
| 380 | 393 | ||
| 394 | + self.assertTrue(result.abstained) | ||
| 395 | + self.assertEqual(result.reason, "ungrounded_no_citations") | ||
| 396 | + self.assertEqual(result.citations, []) | ||
| 397 | + | ||
| 398 | + def test_single_out_of_range_is_still_a_phantom(self): | ||
| 399 | + """Tek parçalı `[N]`'de aralık gösterimi yorumu YOK → gerçek hayalet.""" | ||
| 400 | + deepseek = _StubDeepSeek(text="A [1]. B [9].") | ||
| 401 | + gen = _make_generator(deepseek, scores={"c1": 0.9, "c2": 0.85}) | ||
| 402 | + result = gen.answer("DNA nedir?") | ||
| 403 | + | ||
| 381 | self.assertFalse(result.abstained) | 404 | self.assertFalse(result.abstained) |
| 382 | self.assertEqual(result.reason, "phantom_citation") | 405 | self.assertEqual(result.reason, "phantom_citation") |
| 383 | self.assertEqual(result.invalid_citations, [9]) | 406 | self.assertEqual(result.invalid_citations, [9]) |
| 384 | - self.assertEqual(len(result.citations), 1) | 407 | + self.assertEqual([c["n"] for c in result.citations], [1]) |
| 385 | - self.assertEqual(result.citations[0]["n"], 1) | ||
| 386 | 408 | ||
| 387 | 409 | ||
| 388 | class AllCitationsPhantomTests(unittest.TestCase): | 410 | class AllCitationsPhantomTests(unittest.TestCase): |
| @@ -503,6 +525,147 @@ class ParentTextContextTests(unittest.TestCase): | |||
| 503 | self.assertIn("source_units", inspect.getsource(runner)) | 525 | self.assertIn("source_units", inspect.getsource(runner)) |
| 504 | 526 | ||
| 505 | 527 | ||
| 528 | +class CitationParserHardeningTests(unittest.TestCase): | ||
| 529 | + """#57 (EXP-010/ACC-04 + ACC-14) — atıf ayrıştırıcısı veriyi atıf sanıyordu.""" | ||
| 530 | + | ||
| 531 | + def _gen(self, text, scores=None): | ||
| 532 | + ds = _StubDeepSeek(text=text) | ||
| 533 | + return _make_generator(ds, scores=scores or {"c1": 0.9, "c2": 0.85}), ds | ||
| 534 | + | ||
| 535 | + def test_interval_notation_does_not_produce_a_citation(self): | ||
| 536 | + """Denetimin kanıtı: `[0,1]` eski ayrıştırıcıda `1`'i gerçek bir kaynağa | ||
| 537 | + eşleyip s.5'i UYDURMA atıf olarak cevaba ekliyordu.""" | ||
| 538 | + gen, _ = self._gen("Olasılık değeri [0,1] aralığında yer alır [2].") | ||
| 539 | + res = gen.answer("olasılık nedir?") | ||
| 540 | + self.assertEqual([c["n"] for c in res.citations], [2]) | ||
| 541 | + self.assertNotIn(1, [c["n"] for c in res.citations]) | ||
| 542 | + | ||
| 543 | + def test_interval_notation_survives_in_the_shown_text(self): | ||
| 544 | + """`[0,1]` cümlenin İÇERİĞİ — kırpmak cevabı bozardı.""" | ||
| 545 | + gen, _ = self._gen("Olasılık değeri [0,1] aralığındadır [2].") | ||
| 546 | + res = gen.answer("olasılık nedir?") | ||
| 547 | + self.assertIn("[0,1]", res.text) | ||
| 548 | + | ||
| 549 | + def test_non_ascii_digit_is_not_a_citation(self): | ||
| 550 | + """`\d` + `str.isdigit()` Unicode'dur: `[١]` (Arapça-Hint) `1` sayılıyordu.""" | ||
| 551 | + from src.generate.citations import parse_citations | ||
| 552 | + self.assertEqual(parse_citations("Cevap [١].", 3), ([], [], [])) | ||
| 553 | + | ||
| 554 | + def test_regression_valid_forms_still_parse(self): | ||
| 555 | + from src.generate.citations import parse_citations | ||
| 556 | + for metin, beklenen in (("X [1,2].", [1, 2]), ("X [1][2].", [1, 2]), | ||
| 557 | + ("X [1] [2].", [1, 2]), ("X [3].", [3])): | ||
| 558 | + with self.subTest(metin): | ||
| 559 | + self.assertEqual(parse_citations(metin, 4)[0], beklenen) | ||
| 560 | + | ||
| 561 | + def test_regression_non_citations_still_ignored(self): | ||
| 562 | + from src.generate.citations import parse_citations | ||
| 563 | + for metin in ("X [-1].", "X [1.2].", "X [metin](url).", "X []."): | ||
| 564 | + with self.subTest(metin): | ||
| 565 | + self.assertEqual(parse_citations(metin, 4)[0], []) | ||
| 566 | + | ||
| 567 | + def test_one_parser_for_generator_and_summarizer(self): | ||
| 568 | + """İki ayrı kopya vardı ve yorumu 'senkron güncellenmeli' diyordu — | ||
| 569 | + böyle bir söz kodda tutulmaz (ACC-10'da tam bu şekilde ayrışmıştı).""" | ||
| 570 | + from src.generate import generator | ||
| 571 | + from src.summarize import summarizer | ||
| 572 | + self.assertIs(generator._parse_citation_ns, summarizer._parse_citation_ns) | ||
| 573 | + | ||
| 574 | + | ||
| 575 | +class PhantomCitationDisplayTests(unittest.TestCase): | ||
| 576 | + """#62 (EXP-010/ACC-12) — geçersiz `[N]` metinde duruyordu ama karşılığında | ||
| 577 | + tıklanabilir atıf kaydı yoktu; `invalid_citations` payload'a da girmiyordu.""" | ||
| 578 | + | ||
| 579 | + def test_phantom_marker_removed_from_shown_text(self): | ||
| 580 | + ds = _StubDeepSeek(text="DNA çift sarmaldır [1]. Ribozom protein üretir [9].") | ||
| 581 | + gen = _make_generator(ds, scores={"c1": 0.9, "c2": 0.85}) | ||
| 582 | + res = gen.answer("DNA nedir?") | ||
| 583 | + self.assertNotIn("[9]", res.text) | ||
| 584 | + self.assertIn("[1]", res.text) | ||
| 585 | + self.assertEqual(res.invalid_citations, [9]) | ||
| 586 | + | ||
| 587 | + def test_punctuation_is_not_left_dangling(self): | ||
| 588 | + ds = _StubDeepSeek(text="A [1]. B [9] .") | ||
| 589 | + gen = _make_generator(ds, scores={"c1": 0.9, "c2": 0.85}) | ||
| 590 | + res = gen.answer("q") | ||
| 591 | + self.assertNotIn(" ", res.text) | ||
| 592 | + self.assertFalse(res.text.endswith(" .")) | ||
| 593 | + | ||
| 594 | + def test_clean_answer_text_untouched(self): | ||
| 595 | + ds = _StubDeepSeek(text="DNA çift sarmaldır [1].") | ||
| 596 | + gen = _make_generator(ds, scores={"c1": 0.9, "c2": 0.85}) | ||
| 597 | + res = gen.answer("q") | ||
| 598 | + self.assertEqual(res.text, "DNA çift sarmaldır [1].") | ||
| 599 | + | ||
| 600 | + def test_payload_exposes_invalid_citations(self): | ||
| 601 | + """Backend `abstained/reason` dışında hayalet atıfı da görebilmeli.""" | ||
| 602 | + from src.service.handler import _answer_to_dict | ||
| 603 | + ds = _StubDeepSeek(text="A [1]. B [9].") | ||
| 604 | + gen = _make_generator(ds, scores={"c1": 0.9, "c2": 0.85}) | ||
| 605 | + payload = _answer_to_dict(gen.answer("q")) | ||
| 606 | + self.assertIn("invalid_citations", payload) | ||
| 607 | + self.assertEqual(payload["invalid_citations"], [9]) | ||
| 608 | + | ||
| 609 | + | ||
| 610 | +class AbstainDetectionTests(unittest.TestCase): | ||
| 611 | + """#58 (EXP-010/ACC-05) — `_looks_like_abstain` karakter benzerliği kullanıyordu. | ||
| 612 | + | ||
| 613 | + `SequenceMatcher` oranı ≥0,90 eşiği, Türkçede olumlu/olumsuz ayrımı tek ek | ||
| 614 | + olduğu için **anlamı ters** cümleleri de yakalıyordu. Denetimde hesaplanan | ||
| 615 | + oranlar (bu sınıf o tabloyu test hâline getirir): | ||
| 616 | + | ||
| 617 | + | cümle | eski oran | eski karar | doğru karar | | ||
| 618 | + |---|---|---|---| | ||
| 619 | + | "Kaynaklarda bu bilgi bulunamadı." | 1,0000 | çekimser | çekimser | | ||
| 620 | + | "Kaynaklarda bu bilgi bulunmaktadır." | 0,9231 | çekimser ✗ | cevap | | ||
| 621 | + | "Kaynaklarda bu bilgi bulunmaktadır [1]." | 0,9231 | çekimser ✗ | cevap | | ||
| 622 | + | "Kaynaklarda bu bilgi bulunmuyor." | 0,8710 | cevap ✗ | çekimser | | ||
| 623 | + | ||
| 624 | + Yani eşik **iki yönde de** yanlıştı. | ||
| 625 | + """ | ||
| 626 | + | ||
| 627 | + def _f(self, metin): | ||
| 628 | + from src.generate.generator import _looks_like_abstain | ||
| 629 | + return _looks_like_abstain(metin) | ||
| 630 | + | ||
| 631 | + def test_exact_abstain_sentence(self): | ||
| 632 | + from src.generate.prompt import ABSTAIN_SENTENCE | ||
| 633 | + self.assertTrue(self._f(ABSTAIN_SENTENCE)) | ||
| 634 | + | ||
| 635 | + def test_positive_sentence_is_not_abstain(self): | ||
| 636 | + self.assertFalse(self._f("Kaynaklarda bu bilgi bulunmaktadır.")) | ||
| 637 | + | ||
| 638 | + def test_positive_sentence_with_citation_is_not_abstain(self): | ||
| 639 | + self.assertFalse(self._f("Kaynaklarda bu bilgi bulunmaktadır [1].")) | ||
| 640 | + | ||
| 641 | + def test_real_abstain_variant_is_caught(self): | ||
| 642 | + self.assertTrue(self._f("Kaynaklarda bu bilgi bulunmuyor.")) | ||
| 643 | + | ||
| 644 | + def test_any_cited_answer_is_never_abstain(self): | ||
| 645 | + """Atıflı cevap tanım gereği çekimser değildir — kısa 'evet' cevapları | ||
| 646 | + eskiden bastırılıyordu (recall kaybı).""" | ||
| 647 | + self.assertFalse(self._f("Evet [1].")) | ||
| 648 | + self.assertFalse(self._f("Kaynaklarda yok değil, vardır [2].")) | ||
| 649 | + | ||
| 650 | + def test_long_real_answer_is_not_abstain(self): | ||
| 651 | + uzun = ("Mitokondri hücrenin enerji üretiminden sorumludur; iç zarındaki " | ||
| 652 | + "kristalar yüzey alanını artırır ve ATP sentezi burada gerçekleşir.") | ||
| 653 | + self.assertFalse(self._f(uzun)) | ||
| 654 | + | ||
| 655 | + def test_empty_text_is_not_abstain(self): | ||
| 656 | + self.assertFalse(self._f("")) | ||
| 657 | + self.assertFalse(self._f(" ")) | ||
| 658 | + | ||
| 659 | + def test_grounding_gate_remains_the_real_safety_net(self): | ||
| 660 | + """Bu fonksiyonun agresif olmasına gerek yok: atıfsız-dolu cevap zaten | ||
| 661 | + `ungrounded_no_citations` ile çekimser oluyor.""" | ||
| 662 | + ds = _StubDeepSeek(text="DNA çift sarmaldır ama atıf yok.") | ||
| 663 | + gen = _make_generator(ds, scores={"c1": 0.9, "c2": 0.85}) | ||
| 664 | + res = gen.answer("DNA nedir?") | ||
| 665 | + self.assertTrue(res.abstained) | ||
| 666 | + self.assertEqual(res.reason, "ungrounded_no_citations") | ||
| 667 | + | ||
| 668 | + | ||
| 506 | class CostRecorderSpyTests(unittest.TestCase): | 669 | class CostRecorderSpyTests(unittest.TestCase): |
| 507 | """DOĞRULAYICI bulgusu #7: costlog.record'a (ya da enjekte edilen | 670 | """DOĞRULAYICI bulgusu #7: costlog.record'a (ya da enjekte edilen |
| 508 | cost_recorder'a) doğru module/model/usage argümanlarıyla çağrı yapıldığını | 671 | cost_recorder'a) doğru module/model/usage argümanlarıyla çağrı yapıldığını |