forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rag

Clone
★ 0

0 watching0 forksPython2.4 MiB184b84dAhmet Kaan Gümüş2 months ago189 commits

notes_index.py279 lines, 12.3 KiBHistoryRawDownload
1"""`rag.index` — the write path: note + attachments → chunks → vectors → the
2note index (`src/index/notes.py`), and the answer object the backend stores.
3
4WHAT ONE REQUEST DOES
5
6 1. the note's own `title` + `content` become one document (always);
7 2. each `files[]` entry is read as **bytes over its own QUIC blob stream**
8 (`BlobRequest` → `BlobResponse` header → exactly `size` raw bytes), then
9 parsed by content type — PDFs through the same canonical loader the
10 textbook corpus uses (`ingest/canonical.build_canonical`), plain text
11 decoded directly;
12 3. every document is chunked (`chunk.chunk_document`) and embedded in one
13 pass (`embed_both`: dense + sparse, the provider configured by
14 `RAG_EMBED_*`);
15 4. the note's rows replace whatever this note held before (one unit — a
16 re-index cannot duplicate);
17 5. the answer echoes `files[].id` so the backend can stamp the doc id it
18 minted onto the attachment row, and names any attachment that failed;
19 6. the answer also carries `passages` — the indexed **child** chunks with
20 their full text — so the caller can show WHAT was extracted instead of
21 only how many pieces there are (`MAX_PASSAGES`/`MAX_PASSAGES_BYTES` cap
22 the list; `passages_truncated` says whether anything was left out).
23
24A FAILED ATTACHMENT DOES NOT ABORT THE INDEX. A blob read that refuses (missing
25file, permission, unknown type) is recorded and the rest — including the note
26body — is indexed: a partly indexed note beats no note. The backend keeps the
27previous `rag_output` rows when the whole round trip fails, which is why a
28refusal must be typed rather than answered with an empty "ok".
29"""
30from __future__ import annotations
31
32import json
33import os
34import tempfile
35
36from ..bridge.contract import BlobReadRefused, RagIndexPayload
37from ..index.notes import (MAX_NOTE_FILE_BYTES, doc_id_for_bytes,
38 shared_note_index)
39
40PDF_TYPES = ("application/pdf", "application/x-pdf")
41TEXT_TYPES = ("text/plain", "text/markdown", "text/csv", "application/json")
42
43MAX_PASSAGES = 50
44"""Cevaba konan en fazla parça SAYISI."""
45
46MAX_PASSAGES_BYTES = 512 * 1024
47"""Cevabın tamamı (bütün anahtarlar) için bayt bütçesi.
48
49Bayt tavanı Çerçeve tavanından (`AI_MAX_FRAME_BYTES` = 8 MiB) çok küçük
50seçildi: 8 MiB'lık bir cevap telden geçse bile `rag_output.payload` olarak
51saklanır ve panelde bir notu açmak ~8 MiB'lık bir JSON indirmek olurdu.
52Parçaların hepsi zaten indekste duruyor — cevaptaki liste bir ÖRNEK."""
53
54
55def _json_bytes(obj) -> int:
56 """Tel biçimi (`contract.encode_frame`) ile AYNI serileştirmenin boyutu."""
57 return len(json.dumps(obj, ensure_ascii=False,
58 separators=(",", ":")).encode("utf-8"))
59
60
61def _passages(chunks, head: dict) -> tuple[list[dict], bool]:
62 """Çocuk chunk'lar → cevabın `passages` listesi + `passages_truncated`.
63
64 Sözleşme (backend/frontend bu anahtarlara göre kod yazıyor): her satır
65 `chunk_id`, `doc_id`, `text`, `page_start`, `page_end` taşır ve `text`
66 indekste duran metnin BİREBİR kendisidir (kısaltma UI'ın işi).
67
68 Bütçe cevabın TAMAMI içindir; `head` cevabın diğer anahtarlarıdır, yani
69 "512 KB" iddiası telden geçen şeyin kendisi hakkındadır. İki tavan da
70 (`MAX_PASSAGES`, `MAX_PASSAGES_BYTES`) aynı listeye bakar ve hangisi önce
71 dolarsa liste orada kesilir — kesildiyse bayrak `True`'dur.
72 """
73 out: list[dict] = []
74 used = _json_bytes({**head, "passages": [], "passages_truncated": False})
75 for chunk in chunks:
76 if len(out) >= MAX_PASSAGES:
77 return out, True
78 satir = {"chunk_id": chunk.chunk_id, "doc_id": chunk.doc_id,
79 "text": chunk.text, "page_start": chunk.page_start,
80 "page_end": chunk.page_end}
81 # JSON ilk satırdan sonra her satır için bir virgül harcar; listenin
82 # kendi köşeli parantezleri `used` içindeki boş listede ödendi.
83 boyut = _json_bytes(satir) + (1 if out else 0)
84 if used + boyut > MAX_PASSAGES_BYTES:
85 return out, True
86 out.append(satir)
87 used += boyut
88 return out, False
89
90
91def _is_pdf(name: str, content_type: str) -> bool:
92 return (content_type or "").lower() in PDF_TYPES or \
93 (name or "").lower().endswith(".pdf")
94
95
96def _text_units(doc, text: str, *, page: int = 1):
97 """`text` → canonical units (one per non-empty paragraph).
98
99 The chunker consumes `CanonicalUnit`s, so the note's own prose rides the
100 exact same pipeline as a parsed PDF page — no second chunker, no second
101 span scheme.
102 """
103 from ..ingest.canonical import CanonicalUnit, make_span_id
104 units = []
105 for n, parca in enumerate(p for p in text.split("\n") if p.strip()):
106 units.append(CanonicalUnit(
107 span_id=make_span_id(doc.doc_id, page, n), doc_id=doc.doc_id,
108 sinif=doc.sinif, ders=doc.ders, kaynak_turu=doc.kaynak_turu,
109 page=page, bbox=(0.0, 0.0, 0.0, 0.0), block_no=n,
110 kind="paragraph", text=parca.strip(), page_visual="low_visual",
111 retrieval_disi=False))
112 return units
113
114
115def _body_doc(payload: RagIndexPayload):
116 """The note's own title + content — doc id is the note's own record key,
117 so a re-index replaces rows instead of piling up new ones."""
118 from ..ingest.canonical import CanonicalDoc
119 doc = CanonicalDoc(source_path="", doc_id=payload.course_note,
120 source_version=payload.course_note, sinif="", ders="",
121 kaynak_turu="konu_ozeti", page_count=1)
122 doc.units = _text_units(doc, f"{payload.title}\n{payload.content}")
123 return doc
124
125
126def _plain_doc(name: str, data: bytes, *, doc_id: str):
127 from ..ingest.canonical import CanonicalDoc
128 metin = data.decode("utf-8", errors="replace")
129 doc = CanonicalDoc(source_path=name, doc_id=doc_id,
130 source_version=doc_id, sinif="", ders="",
131 kaynak_turu="konu_ozeti", page_count=1)
132 doc.units = _text_units(doc, metin)
133 return doc
134
135
136def _pdf_doc(name: str, data: bytes, *, doc_id: str):
137 """PDF bytes → canonical document, through the corpus's own loader.
138
139 `build_canonical` reads a path, so the bytes land in a temp file first; the
140 doc id is computed from the bytes here (not from the temp path) so it stays
141 the content hash the citation resolver expects.
142 """
143 from ..ingest.canonical import build_canonical
144 fd, yol = tempfile.mkstemp(suffix=".pdf", prefix="not-eki-")
145 try:
146 with os.fdopen(fd, "wb") as f:
147 f.write(data)
148 doc = build_canonical(yol, sinif="", ders="", kaynak_turu="konu_ozeti")
149 doc.source_path = name
150 doc.doc_id = doc_id # sha256 of the same bytes
151 for unit in doc.units:
152 unit.doc_id = doc_id
153 unit.span_id = unit.span_id.replace(doc.doc_id, doc_id, 0) \
154 if unit.span_id.startswith(doc.doc_id) else unit.span_id
155 return doc
156 finally:
157 try:
158 os.unlink(yol)
159 except OSError:
160 pass
161
162
163def _chunks_for(doc, course_note: str):
164 """Children only, note-scoped ids (two notes sharing one PDF must not
165 collide), no parent links (no parent rows are stored)."""
166 from ..chunk import chunk_document
167 out = []
168 for chunk in chunk_document(doc):
169 if chunk.level != "child":
170 continue
171 chunk.chunk_id = f"{course_note}:{chunk.chunk_id}"
172 chunk.parent_id = None
173 out.append(chunk)
174 return out
175
176
177def index_course_note(payload: RagIndexPayload, *, school: str,
178 blob_reader=None, note_index=None, embedder=None) -> dict:
179 """Index one course note and return the answer object the backend stores."""
180 index = note_index if note_index is not None else shared_note_index()
181 if embedder is None:
182 from ..embed.provider import build_embedder
183 embedder = build_embedder()
184
185 docs = [_body_doc(payload)]
186 indexed_files, failed_files = [], []
187
188 for meta in payload.files:
189 try:
190 header, data = _read_file(meta, school=school,
191 author=payload.author, blob_reader=blob_reader)
192 except BlobReadRefused as exc:
193 failed_files.append({"id": meta.id, "name": meta.name,
194 "code": exc.code, "message": exc.message})
195 continue
196 name = str(header.get("name") or meta.name or "")
197 content_type = str(header.get("content_type") or meta.content_type or "")
198 doc_id = doc_id_for_bytes(data)
199 try:
200 if _is_pdf(name, content_type):
201 doc = _pdf_doc(name, data, doc_id=doc_id)
202 elif (content_type or "").lower() in TEXT_TYPES or \
203 name.lower().endswith((".txt", ".md", ".csv", ".json")):
204 doc = _plain_doc(name, data, doc_id=doc_id)
205 else:
206 raise BlobReadRefused("unsupported_type",
207 f"'{content_type or 'bilinmeyen'}' türü "
208 "indekslenemiyor")
209 except BlobReadRefused as exc:
210 failed_files.append({"id": meta.id, "name": name,
211 "code": exc.code, "message": exc.message})
212 continue
213 except Exception as exc: # noqa: BLE001
214 failed_files.append({"id": meta.id, "name": name, "code": "parse_failed",
215 "message": f"{type(exc).__name__}: {exc}"})
216 continue
217 docs.append(doc)
218 indexed_files.append({"id": meta.id, "doc_id": doc_id, "name": name})
219
220 chunks = []
221 for doc in docs:
222 chunks.extend(_chunks_for(doc, payload.course_note))
223 rows = []
224 if chunks:
225 texts = [c.text for c in chunks]
226 vecs, sparse = embedder.embed_both(texts, batch_size=16)
227 rows = [(chunk, vec, sp) for chunk, vec, sp in zip(chunks, vecs, sparse)]
228 n = index.replace_note(school, payload.course_note, rows)
229
230 head = {
231 "course_note": payload.course_note,
232 "chunks": n,
233 "files": indexed_files,
234 "failed": failed_files,
235 "summary": _summary(payload.title, n, indexed_files, failed_files),
236 }
237 # Parça listesi indeksin KENDİSİ değil, ondan bir örnektir: buradaki
238 # herhangi bir arıza cevabı düşürmez, yalnız listeyi boşaltır (`chunks`
239 # yine tam sayıyı söyler). Backend eski `rag_output` satırını ancak TÜM
240 # tur düşerse korur — parça üretimi yüzünden reddetmek, indekslenmiş bir
241 # notu kaybettirirdi.
242 try:
243 passages, truncated = _passages(chunks, head)
244 except Exception: # noqa: BLE001
245 passages, truncated = [], True
246
247 return {**head, "passages": passages, "passages_truncated": truncated}
248
249
250def _read_file(meta, *, school: str, author: str, blob_reader):
251 """One attachment's bytes over its own blob stream.
252
253 The request shape is the bridge's (`protocol.rs::BlobRequest`): the file's
254 record id, the school uuid, and the note's author as `on_behalf_of` — the
255 `ai` principal can view no course, so a read as itself always earns
256 `forbidden`.
257 """
258 if blob_reader is None:
259 raise BlobReadRefused("blob_unavailable",
260 "bu servis örnekte blob okuma yolu yok")
261 if int(meta.size or 0) > MAX_NOTE_FILE_BYTES:
262 raise BlobReadRefused("too_large",
263 f"ek {meta.size} bayt: sınır {MAX_NOTE_FILE_BYTES}")
264 return blob_reader.read({"id": meta.id, "school": school, "file": meta.id,
265 "on_behalf_of": author},
266 max_bytes=MAX_NOTE_FILE_BYTES)
267
268
269def _summary(title: str, chunks: int, indexed_files, failed_files) -> str:
270 """One or two Turkish sentences — the human is the reader of this payload."""
271 baslik = (title or "").strip() or "Ders notu"
272 ek = (f", {len(indexed_files)} ek dosyayla" if indexed_files else "")
273 metin = (f"'{baslik}' notu indekslendi: {chunks} metin parçası{ek}. "
274 "Bu not artık sorularda kaynak olarak kullanılabilir.")
275 if failed_files:
276 adlar = ", ".join(str(f.get("name") or f.get("id")) for f in failed_files)
277 metin += (f" Şu ekler okunamadı ve indekslenemedi: {adlar} — "
278 "notun kendi metni yine de indekslendi.")
279 return metin