"""Deterministic source-bound chunks for an explicitly synthetic developer API.""" import hashlib import json import re from load_documents import IngestionError, load_documents CONFIGS={ 'fixed-char':{'strategy':'fixed-char','version':1,'max_chars':80}, 'paragraph':{'strategy':'paragraph','version':1,'max_chars':None}, 'heading-aware':{'strategy':'heading-aware','version':1,'max_chars':220}, } def digest(value): return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':'),ensure_ascii=False).encode('utf-8')).hexdigest() def sha(text):return hashlib.sha256(text.encode('utf-8')).hexdigest() def config_checked(config): try: supported=isinstance(config,dict) and any(digest(config)==digest(c) for c in CONFIGS.values()) except (TypeError,ValueError,OverflowError): supported=False if not supported:raise IngestionError('unsupported_chunk_config') return dict(config) def sections(document): text=document['text'];headings=list(re.finditer(r'^#{1,6} (.+)(?:\n|$)',text,re.MULTILINE)) if not headings or headings[0].start()!=0:raise IngestionError('heading_required') for position,heading in enumerate(headings): start=heading.end();end=headings[position+1].start() if position+165536 or not doc['text'].strip() or '\x00' in doc['text'] or '\r\n' in doc['text']:raise ValueError() if re.fullmatch('[0-9a-f]{64}',doc['sha256']) is None:raise ValueError() if doc.get('normalized_text_sha256')!=sha(doc['text']):raise ValueError() if doc['document_revision']!=digest({key:value for key,value in doc.items() if key not in ('text','document_revision')}):raise ValueError() if digest(index)!=digest(index_from_documents(documents,config)):raise ValueError() except (ValueError,KeyError,TypeError,UnicodeError,OverflowError) as error: raise IngestionError('invalid_chunk_index') from error return index