Corpus, chunking and evaluation set
Before building the retriever, build a way to measure it. Ingest a research corpus of papers cited in the syllabus and your notes, chunk it using several strategies, and use the local LLM to generate questions with reference passages for manual verification.
After this lesson you can
- Extract PDF and HTML text while retaining sections, approximate formulas, and metadata.
- Implement structural and overlapping token chunking and compare their statistics.
- Generate candidate questions with the LLM and manually verify at least 150 against their reference passages.
- Separate development and test sets and freeze the test set before iteration.
Before you start
A search is only as good as its evidence
A query asks about a paper’s result. The passage explaining it exists in the PDF, but extraction mixed two columns; then chunking separated the number from its unit. The retriever cannot return a passage that the index never received in readable form. Before comparing algorithms, we need to know which documents entered, where they were cut, and what evidence each question should find.
In the previous lesson you set up a local model and distinguished output validity from content correctness. Now that model will propose questions, but a person will check each candidate against the document. A question must not be counted as verified merely because the model returns valid JSON. The goal is a traceable corpus and at least 150 manually reviewed questions, with evidence and a development/test split, before choosing the retriever.
The question to watch is not just “how many chunks are there?” In the figure, the four references are intervals annotated for this demonstration; they are not search results or part of the lab’s 150 questions. R3 is the interesting one: “our models” only makes sense with the preceding sentence, so its evidence crosses a sentence boundary. Initially (40 words, overlap 8) the fixed window happens to preserve it because its second window starts exactly where the reference starts; sentence packing produces three clean chunks, one per sentence, and splits it in two. Respecting sentences is not enough: a clean cut between two complete sentences can lose their relationship. To keep them together they must fit together (size at least 62) and overlap must carry the entire second sentence (at least 27), at the cost of duplicated text: watch the repeated-text readout. Very large chunks reduce splits but consume more generator budget and dilute evidence with irrelevant text. We will choose using statistics and verified questions, not a supposedly universal length.
From document to text with provenance
This project’s corpus brings together papers cited in the syllabus and personal notes the reader chooses to include. Start with a manifest, not a folder of anonymous text: stable identifier, title, authors where available, URL, version, retrieval date, known license or permission, and file fingerprint. A URL may point to a new version; a content hash detects changes but does not itself prove the source reliable. For local notes record an identifier and version or fingerprint without turning a private path into a public URL. If a license is missing, record it as unknown and check terms before reusing or distributing the document. Availability on arXiv does not mean all papers have the same license. Consult the arXiv licenses and each source’s terms.
The arXiv API manual describes metadata queries. A search should save the exact identifier and version subsequently downloaded, distinguish a network failure from a nonexistent source, and respect service policies. If multiple links point to one paper, deduplicate by identity and version, not title alone: similar titles may belong to different documents. Downloading does not automatically make a document verified material or authorize uploading personal notes to an external service.
A PDF contains presentation instructions and can store text in an order different from its visual order. In two-column papers, reading blocks without inspecting coordinates can interleave sentences. The PyMuPDF extraction documentation explains that reading order may need additional handling. Extract pages and blocks with coordinates; when the order is doubtful, return to the original page. Detect empty or sparse text and flag a possible scanned document: do not confuse empty extraction with an empty page. OCR can produce searchable text but requires review, particularly for formulas, subscripts, signs, and tables.
A table has relationships between rows and columns. Flattening it into a string can assign one method’s number to another. Retain headers and labels alongside values where possible, save the source page, and flag tables requiring visual checking. For formulas, preserve a retrievable textual approximation and its location; if the extractor loses signs or structure, record that limitation rather than presenting the transcription as exact. The quality goal is for the passage to lead back to the original, not to pretend every PDF becomes perfect mathematics.
HTML requires another strategy: identify the title and heading hierarchy, extract main content, and remove repeated navigation without accidentally discarding code blocks or tables. Web text extraction and heuristic filters help select material, but a rule like “remove short paragraphs” can also erase an important result. Compare samples of extracted text with the original. Save a versioned derived copy and record extractor version and options to reproduce an index.
Chunking without losing the map
A useful chunk needs text and location. A record can contain doc_id, version or hash, page or section, chunk identifier, range in normalized text, text, and chunking method. Use half-open intervals : they include the starting position and exclude the end, so measures length. The index unit must be explicit: UTF-8 bytes, character positions, and token positions are not interchangeable. Later normalization can invalidate offsets unless a map to the original is saved. Two overlapping chunks are distinct units even when they share text; their citations should lead to the same source.
By structure, group paragraphs under headings and separate sections before applying a size limit. Retaining a section title adds context, but repeating it in every chunk also changes indexed text. A long section still needs subdivision; a short one may be combined with another only if provenance distinctions are preserved. A table and its caption often require special handling so values are not separated from labels. Structure obtained from PDF is a hypothesis to audit, especially when headings are detected by typography.
By tokens, encode text with an identified tokenizer, cut a window of maximum size , and advance , where is overlap and . BPE encoding illustrates why a word is not always one token. Counts vary with tokenizer, language, and symbols; compression metrics help comparison but do not replace the actual counter of the model receiving context. The retriever tokenizer may differ from the generator’s: record which measures each stage’s limit.
For fixed windows that do not respect sentences and a nonempty document of tokens, if the last window stops upon reaching the end, the number of chunks is
Window (counting from ) starts at and ends at ; the process stops at the first reaching the end, namely the smallest with . If , ; otherwise , and the number of windows is . For an empty document define . Do not apply this formula to a chunker that adjusts cuts to sentences or sections: those boundaries change the advance and thus chunk count. The cell checks the formula against simulation in one thousand random cases and distinguishes the final window’s size from the maximum.
import math
import random
def fixed_windows(n, size, overlap):
if n < 0 or size <= 0 or not 0 <= overlap < size:
raise ValueError("Parámetros inválidos")
if n == 0:
return []
out, start = [], 0
while True:
end = min(n, start + size)
out.append((start, end))
if end == n:
return out
start += size - overlap
def count_formula(n, size, overlap):
return 0 if n == 0 else 1 + math.ceil(max(0, n - size) / (size - overlap))
windows = fixed_windows(5000, 400, 50)
print("fragmentos:", len(windows), "fórmula:", count_formula(5000, 400, 50))
print("último intervalo:", windows[-1], "longitud:", windows[-1][1] - windows[-1][0])
rnd = random.Random(0)
casos = []
for _ in range(1000):
s = rnd.randint(1, 600)
casos.append((rnd.randint(0, 3000), s, rnd.randint(0, s - 1)))
print("discrepancias en", len(casos), "casos:", sum(len(fixed_windows(*c)) != count_formula(*c) for c in casos))A sentence-respecting cut chooses a sentence end within budget and uses a suffix of complete sentences as overlap. It can lose more or less context than the desired nominal token count. If one sentence exceeds budget, choose an explicit policy: reject it for review, split it with a recorded exception, or increase the limit. Rejecting it makes the chunker easy to audit; silently omitting it loses evidence. Also guarantee progress when overlap includes every sentence in the window, and decide whether separators and headings count toward the budget.
Compare strategies using length distributions, chunk count, repeated-text proportion, and coverage of reference intervals. If is evidence, strict coverage by a single chunk exists when some satisfies and . This only says the text could be retrieved intact: it does not predict that the retriever will rank it among the first results. Conversely, an answer may require several passages, so covering one piece of evidence is not the same as answering a multi-hop question. Later measure the retriever on the same collection version.
Questions before optimizing search
The RAG formulation separates retrieval and generation. Lewis and colleagues combine a dense Wikipedia index with a generative model and compare sequence-level and token-level conditioning. That architecture motivates evaluating evidence before asking for a final answer: failure can come from extraction, passage selection, or the generator. Do not attribute a wrong answer to the retriever without checking what the generator received and whether the evidence was in the index.
In BEIR, Thakur and colleagues assemble 18 public datasets from diverse tasks and domains and evaluate 10 retrieval systems (lexical, sparse, dense, late-interaction, and reranking); their abstract highlights BM25’s strength as a baseline and the good average performance of reranking and late interaction in their evaluation, at greater computational cost. This is a result for that battery, not a promise that a method will win on your corpus. The methodological lesson is that diversity of domains and questions matters: a single question type can accidentally favor a particular strategy.
A candidate should store the question, expected answer or answer criterion, evidence text, document and version, page or section, and locatable range. Add labels for question type, need for one or multiple sources, difficulty, and review decision. The previous lesson’s LLM can propose candidates with structured output, but the schema only validates fields. The initial state is pendiente (pending), not verificada (verified). A reviewer opens the original document, checks that the passage exists, answers the question without hidden context, and that the answer does not contradict another part of the source. Accept, correct, or reject with a reason; record who reviewed and when without inventing that review.
Seek variety with definition, comparison, result interpretation, limitations, and cross-source synthesis questions. A question can have several valid pieces of evidence; do not mark a correct passage irrelevant merely because it is not the first annotated one. Also save cases unanswerable from the corpus if abstention will be measured, separate from questions with evidence. For multi-hop questions enumerate every necessary piece of evidence and check whether the criterion requires all or allows alternatives. The accuracy of judgments conditions every subsequent metric.
Questions generated from the same passage tend to reuse its vocabulary: this can favor lexical matches without demonstrating that actual user queries have that distribution. It is not a universal law or proof that a dense retriever is better. Compare with independently written questions, reviewed paraphrases, and real queries you may use with permission. Do not change a test question after seeing which system fails it. To compare different cuts, first locate evidence in the original document, then determine which chunks of each index cover it; avoid treating a single chunk identifier created by one strategy as ground truth.
Freezing the test without freezing learning
The development/test split assigns questions before tuning the system. Use development to select size, overlap, and parameters; retain test for final evaluation with fixed configuration. If you repeatedly inspect test failures and change decisions to fix them, the test becomes development. This is a form of validation overfitting even if you never train weights.
The split should match the claim you want to test. Splitting by question measures new questions about known documents, but near-duplicate questions can land on both sides. Grouping by document or version family studies generalization to held-out documents and reduces leakage among paraphrases of the same passage. If test documents are indexed but their questions are hidden during tuning, this evaluates retrieval in those documents; if you also want to generalize to unindexed documents, first incorporate them into the index at evaluation time. Document what information is available at each phase.
Freezing means saving an immutable version of documents, labels, assignments, and criteria, with fingerprints and cutoff date. Extraction changes can move offsets, so a new version requires rebuilding the mapping and, if evidence is affected, renewed review. Keep the record of rejected candidates and reasons: they do not enter as verified questions, but explain selection biases. Reserve a new test if the existing one has already been used for iteration. With one reviewer record the limitation; an independent second review and discussion of disagreements improve auditability but must not be claimed if they did not happen.
Lab: from corpus to review queue
The lab builds a source manifest, extracts PDF and HTML, compares cuts, and prepares candidates. It retains originals and produces derived records with provenance. For the goal of 150 questions, the review interface must let the reader open the original passage, accept, correct, or reject, and save the decision. An automatic run can generate and validate candidates, but must not mark them reviewed or replace inspection. Count pending, rejected, and accepted separately; freeze the test only when the reviewed set actually exists.
The lab uses requests, beautifulsoup4, pypdf, jsonschema, tokenizers, and huggingface_hub; install them in the Python environment before running it. It needs connections to arXiv and the tokenizer repository, plus the local Ollama server with phi3:mini from the previous lesson. Download the arXiv papers cited in the module, pin the version, and separately retain available PDF and HTML views. PDF extraction saves page number but does not reconstruct columns or preserve coordinates. HTML extraction selects headings and text blocks; it can omit table or formula structures. Failures are logged and both views require inspection against the original before use as evidence.
Everything the lab produces goes into your own directory: p05-l02 inside the folder indicated by environment variable ATLAS_LAB_DIR (default ~/atlas-lab, the same folder used by subsequent lessons). Later lessons use its chunks (chunks.jsonl) and frozen set (evaluacion-congelada.json). When run as a cell, every run creates a new ejecucion-… subdirectory, downloads and ingests the corpus, fixes the document split, and generates up to 150 candidates; it never reviews or freezes. To resume an interrupted run, set P05_L02_REANUDAR to that subdirectory; the program checks manifest fingerprints before continuing. If the GPU runs out of memory, generation waits 90 s and retries, at most three attempts per chunk; final failures remain in errores-generacion.jsonl. The model can answer in a language different from the source text or mix languages: also check this during review. Attach each question’s literal input chunk as candidate evidence, not as proof the answer is correct. Invalid responses and failures are retained; no candidate becomes reviewed merely by appearing in the file. Review needs an interactive terminal, not the notebook: copy the cell to a file, for example laboratorio.py, and run from the repository root (or any folder inside it) python laboratorio.py --out "RUTA_IMPRESA" review, replacing the path with the one printed by the run. This step allows acceptance, correction, or rejection, requires identification and a note, and cannot be replaced by an automatic check. Then python laboratorio.py --out "RUTA_IMPRESA" freeze creates a frozen evaluation only if there are at least 150 accepted decisions and both splits are represented. Since you will reject some candidates, expand the queue before freezing with python laboratorio.py --out "RUTA_IMPRESA" generate --target 220 (the target is the total number of candidates: it generates only those missing and leaves reviewed ones untouched). The code does not verify the identity of the reviewer signing a review: the signature is an accountability record, not authentication.
"""Corpus RAG: ingesta, fragmentación, candidatos y revisión humana.
Ejecutar dentro del repositorio (lee los enlaces arXiv del JSON del módulo).
Dependencias: pypdf, beautifulsoup4, requests, jsonschema, tokenizers y
huggingface_hub. Salida en ATLAS_LAB_DIR/p05-l02 (por defecto ~/atlas-lab/p05-l02).
Como celda del cuaderno prepara el corpus y genera candidatas en un subdirectorio
nuevo. Como programa, con la celda guardada por ejemplo en laboratorio.py:
python laboratorio.py --out RUTA prepare --notes RUTA_OPCIONAL
python laboratorio.py --out RUTA generate --target 150
python laboratorio.py --out RUTA review
python laboratorio.py --out RUTA freeze
El modelo genera candidatos, nunca verificaciones. El resultado de `freeze`
solo existe si una persona acepta al menos 150 y hay documentos en ambas
particiones. El ensayo no se ejecuta al importar este módulo.
"""
from __future__ import annotations
import argparse
import hashlib
import itertools
import json
import os
from pathlib import Path
import re
import statistics
import sys
import time
from datetime import datetime, timezone
import requests
from bs4 import BeautifulSoup
from huggingface_hub import hf_hub_download
from jsonschema import validate
from jsonschema.exceptions import ValidationError
from pypdf import PdfReader
from pypdf.errors import PdfReadError
from tokenizers import Tokenizer
def find_root():
current = Path.cwd().resolve()
for candidate in (current, *current.parents):
if (candidate / 'src/content/modules/p05-agente-rag-local.json').is_file():
return candidate
raise FileNotFoundError('No se encuentra la raíz del repositorio entre los directorios padres')
ROOT = find_root()
MODULE = ROOT / 'src/content/modules/p05-agente-rag-local.json'
LAB_DIR = Path(os.environ.get('ATLAS_LAB_DIR', Path.home() / 'atlas-lab')).expanduser() / 'p05-l02'
DEFAULT_OUT = LAB_DIR / 'corpus-evaluacion'
TOKENIZER_REPO = 'microsoft/Phi-3-mini-128k-instruct'
TOKENIZER_REV = 'f3c06aed622e14ca0abf5115094e4fc9a9948f36'
TOKENIZER_SHA = '072ab882d6c7192a42f78790945d16c064691321a73251a4b18f6a380f0fbe39'
MODEL = 'phi3:mini'
BASE = 'http://127.0.0.1:11434'
SIZE = 384
OVERLAP = 64
SCHEMA = {
'type': 'object', 'additionalProperties': False,
'properties': {'pregunta': {'type': 'string', 'minLength': 1},
'respuesta': {'type': 'string', 'minLength': 1}},
'required': ['pregunta', 'respuesta'],
}
def sha(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def canonical(value) -> bytes:
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8')
def now() -> str:
return datetime.now(timezone.utc).isoformat()
def write_json(path: Path, value, *, exclusive=False):
with path.open('x' if exclusive else 'w', encoding='utf-8', newline='\n') as f:
json.dump(value, f, ensure_ascii=False, indent=2)
f.write('\n')
def append_jsonl(path: Path, value):
with path.open('a', encoding='utf-8', newline='\n') as f:
f.write(json.dumps(value, ensure_ascii=False, sort_keys=True) + '\n')
def read_jsonl(path: Path):
if not path.exists():
return []
with path.open(encoding='utf-8') as f:
return [json.loads(line) for line in f if line.strip()]
def tokenizer():
path = Path(hf_hub_download(TOKENIZER_REPO, 'tokenizer.json', revision=TOKENIZER_REV))
if sha(path.read_bytes()) != TOKENIZER_SHA:
raise ValueError('El tokenizer.json no coincide con el SHA256 fijado')
return Tokenizer.from_file(str(path))
def extract_pdf(path: Path):
reader = PdfReader(str(path))
result = []
section = '(sin sección identificada)'
for page_no, page in enumerate(reader.pages, 1):
text = page.extract_text() or ''
# La sección es una heurística y se conserva como tal, no como verdad editorial.
for para in re.split(r'\n\s*\n', text):
para = para.strip()
if not para:
continue
first = para.splitlines()[0].strip()
if len(first) <= 100 and re.match(r'^\d+(?:\.\d+)*\s+[A-Z][A-Za-z ]+$', first):
section = first
result.append({'page': page_no, 'section': section, 'text': para})
return result
def extract_html(text: str):
soup = BeautifulSoup(text, 'html.parser')
root = soup.find('article') or soup.find('main') or soup.body or soup
for element in root.select('script, style, nav, footer'):
element.decompose()
result = []
section = '(sin sección identificada)'
for tag in root.find_all(['h1', 'h2', 'h3', 'h4', 'p', 'li', 'pre']):
if tag.name in ('p', 'pre') and tag.find_parent(['li', 'pre']):
continue
value = tag.get_text(' ', strip=True)
if not value:
continue
if tag.name.startswith('h'):
section = value
result.append({'page': None, 'section': section, 'text': value})
return result
def assemble(blocks):
parts, spans = [], []
cursor = 0
for block in blocks:
text = block['text']
if parts:
parts.append('\n\n')
cursor += 2
begin = cursor
parts.append(text)
cursor += len(text)
spans.append({'start': begin, 'end': cursor, 'page': block['page'], 'section': block['section']})
return ''.join(parts), spans
def offsets_for(text, tok):
return [tuple(x) for x in tok.encode(text, add_special_tokens=False).offsets if x[1] > x[0]]
def make_windows(offsets, text, size, overlap, char_base=0):
if not 0 <= overlap < size:
raise ValueError('Se requiere 0 <= solapamiento < tamaño')
chunks = []
for i in range(0, len(offsets), size - overlap):
end = min(i + size, len(offsets))
a, b = offsets[i][0] + char_base, offsets[end - 1][1] + char_base
chunks.append({'start': a, 'end': b, 'token_count': end - i, 'text': text[a:b]})
if end == len(offsets):
break
return chunks
def chunk_tokens(text, tok, size=SIZE, overlap=OVERLAP):
return make_windows(offsets_for(text, tok), text, size, overlap)
def chunk_structure(text, spans, tok, size=SIZE, overlap=OVERLAP):
# Una región es una secuencia de bloques consecutivos con la misma sección.
regions = []
for span in spans:
if regions and regions[-1]['section'] == span['section']:
regions[-1]['end'] = span['end']
else:
regions.append({'start': span['start'], 'end': span['end'], 'section': span['section']})
result = []
for region in regions:
a, b = region['start'], region['end']
result.extend(make_windows(offsets_for(text[a:b], tok), text, size, overlap, a))
return result
def sources_for(chunk, spans):
return [{'page': s['page'], 'section': s['section']} for s in spans
if s['start'] < chunk['end'] and chunk['start'] < s['end']]
def stats(chunks):
counts = sorted(c['token_count'] for c in chunks)
if not counts:
return {'count': 0}
return {'count': len(counts), 'min_tokens': counts[0],
'median_tokens': statistics.median(counts), 'max_tokens': counts[-1],
'sum_tokens_including_overlap': sum(counts)}
def get(session, url):
response = session.get(url, timeout=(10, 90), allow_redirects=True)
response.raise_for_status()
return response
def arxiv_doc(session, arxiv_id):
metadata_response = get(session, f'https://arxiv.org/abs/{arxiv_id}')
soup = BeautifulSoup(metadata_response.content, 'html.parser')
def meta(name):
return [x.get('content', '') for x in soup.find_all('meta', attrs={'name': name})]
title = (meta('citation_title') or [arxiv_id])[0]
authors = meta('citation_author')
licenses = [a.get('href') for a in soup.select('a[href]') if 'creativecommons.org/licenses/' in a.get('href', '')]
versions = []
for link in soup.select('a[href]'):
found = re.search(r'/abs/' + re.escape(arxiv_id) + r'v(\d+)(?:$|[?#])', link.get('href', ''))
if found:
versions.append(int(found.group(1)))
if not versions:
raise ValueError(f'No se pudo fijar la versión arXiv de {arxiv_id}')
versioned_id = f'{arxiv_id}v{max(versions)}'
attempts, variants = [], []
for kind in ('html', 'pdf'):
url = f'https://arxiv.org/{kind}/{versioned_id}'
try:
response = session.get(url, timeout=(10, 90), allow_redirects=True)
attempts.append({'url': url, 'status': response.status_code, 'final_url': response.url})
response.raise_for_status()
content = response.content
if kind == 'pdf' and not content.startswith(b'%PDF-'):
raise ValueError('La respuesta no es un PDF')
if kind == 'html' and b'<html' not in content[:3000].lower():
raise ValueError('La respuesta no es HTML')
variants.append({'kind': kind, 'source_url': response.url, 'source_sha256': sha(content), 'data': content})
except (requests.RequestException, ValueError) as exc:
if not attempts or attempts[-1]['url'] != url:
attempts.append({'url': url, 'error': str(exc)})
else:
attempts[-1]['error'] = str(exc)
if not variants:
raise RuntimeError(json.dumps(attempts, ensure_ascii=False))
# Las dos vistas comparten documento y versión, pero nunca comparten offsets.
preferred = next((v for v in variants if v['kind'] == 'html'), variants[0])
return {'id': f'arxiv:{versioned_id}', 'title': title, 'authors': authors,
'source_url': preferred['source_url'], 'abstract_url': metadata_response.url,
'license_url': licenses[0] if licenses else None,
'license_note': 'Comprueba la licencia en la fuente; un enlace ausente no concede derechos.',
'retrieved_at': now(), 'kind': preferred['kind'], 'source_sha256': preferred['source_sha256'],
'fetch_attempts': attempts}, variants
def local_docs(directory):
if directory is None:
return
path = Path(directory)
if not path.is_dir():
raise ValueError(f'No existe el directorio de notas: {path}')
for source in sorted(path.rglob('*')):
if not source.is_file() or source.suffix.lower() not in ('.pdf', '.html', '.htm', '.txt', '.md'):
continue
data = source.read_bytes()
kind = 'pdf' if source.suffix.lower() == '.pdf' else 'html' if source.suffix.lower() in ('.html', '.htm') else 'text'
meta = {'id': f'nota:{source.relative_to(path).as_posix()}', 'title': source.name,
'authors': [], 'source_url': None, 'original_path': str(source), 'license_url': None,
'license_note': 'Documento local; revisa sus permisos de uso.', 'retrieved_at': now(),
'kind': kind, 'source_sha256': sha(data)}
yield meta, [{'kind': kind, 'source_url': None, 'source_sha256': sha(data), 'data': data}]
def add_document(meta, variants, out, tok):
views = {}
source_records = []
for variant in variants:
kind, data = variant['kind'], variant['data']
raw = out / 'fuentes' / (variant['source_sha256'] + '.' + kind)
raw.write_bytes(data)
source_record = {k: v for k, v in variant.items() if k != 'data'}
source_record['source_file'] = str(raw.relative_to(out))
source_records.append(source_record)
try:
if kind == 'pdf':
blocks = extract_pdf(raw)
elif kind == 'html':
blocks = extract_html(data.decode('utf-8', errors='replace'))
else:
blocks = [{'page': None, 'section': '(nota)', 'text': data.decode('utf-8')}]
text_view, spans_view = assemble(blocks)
if not text_view.strip():
raise ValueError('La extracción no produjo texto; puede necesitar OCR')
views[kind] = {'text': text_view, 'spans': spans_view,
'text_sha256': sha(text_view.encode('utf-8')),
'source_file': source_record['source_file']}
except (ValueError, OSError, PdfReadError, UnicodeError) as exc:
source_record['extraction_error'] = str(exc)
if not views:
raise ValueError('Ninguna vista produjo texto: ' + json.dumps(source_records, ensure_ascii=False))
primary_kind = 'html' if 'html' in views else next(iter(views))
primary = views[primary_kind]
text, spans = primary['text'], primary['spans']
selected = next(x for x in source_records if x['kind'] == primary_kind)
meta.update({'sources': source_records, 'kind': primary_kind, 'source_url': selected['source_url'],
'source_sha256': selected['source_sha256']})
digest = sha(text.encode('utf-8'))
doc = {'metadata': meta, 'source_file': primary['source_file'], 'text_sha256': digest,
'text': text, 'spans': spans, 'views': views}
fixed = chunk_tokens(text, tok)
structural = chunk_structure(text, spans, tok)
for strategy, chunks in (('tokens', fixed), ('estructura', structural)):
for chunk in chunks:
chunk.update({'doc_id': meta['id'], 'strategy': strategy, 'sources': sources_for(chunk, spans)})
chunk['id'] = sha(canonical([meta['id'], strategy, chunk['start'], chunk['end'], digest]))
return doc, fixed, structural
def load_manifest(out):
path = out / 'manifiesto.json'
manifest = json.loads(path.read_text(encoding='utf-8'))
stored = (out / 'manifiesto.sha256').read_text(encoding='utf-8').strip()
if sha(canonical(manifest)) != stored:
raise ValueError('El manifiesto cambió después de fijar la partición')
for doc in manifest['documents']:
for source in doc['metadata']['sources']:
if sha((out / source['source_file']).read_bytes()) != source['source_sha256']:
raise ValueError(f"Cambió la fuente: {doc['metadata']['id']} {source['kind']}")
for name in ('documentos.jsonl', 'chunks.jsonl'):
if sha((out / name).read_bytes()) != manifest['artifacts'][name]:
raise ValueError(f'Cambió el archivo {name}')
return manifest, stored
def prepare(out, notes):
if not MODULE.exists():
raise FileNotFoundError('Ejecuta desde la raíz del repositorio para localizar el JSON del módulo')
if (out / 'manifiesto.json').exists():
raise FileExistsError('Ya existe un manifiesto: usa otro directorio para construir otro corpus')
out.mkdir(parents=True, exist_ok=True)
(out / 'fuentes').mkdir(exist_ok=True)
tok = tokenizer()
module_text = MODULE.read_text(encoding='utf-8')
ids = sorted(set(re.findall(r'arxiv\.org/(?:abs|pdf|html)/(\d{4}\.\d{4,5})(?:v\d+)?', module_text)))
if not ids:
raise ValueError('No se encontraron referencias arXiv en el módulo')
docs, fixed_all, structural_all, failures, seen = [], [], [], [], set()
with requests.Session() as session:
session.headers['User-Agent'] = 'Atlas-corpus-educativo/1.0'
for arxiv_id in ids:
try:
meta, variants = arxiv_doc(session, arxiv_id)
doc, fixed, structural = add_document(meta, variants, out, tok)
if doc['text_sha256'] in seen:
raise ValueError('Documento duplicado por hash del texto extraído')
seen.add(doc['text_sha256']); docs.append(doc); fixed_all.extend(fixed); structural_all.extend(structural)
print(meta['id'], len(doc['text']), 'caracteres', flush=True)
except (requests.RequestException, ValueError, RuntimeError, OSError, PdfReadError) as exc:
failures.append({'id': arxiv_id, 'error': str(exc)})
print('No ingerido:', arxiv_id, str(exc), flush=True)
time.sleep(1)
for meta, variants in local_docs(notes):
try:
doc, fixed, structural = add_document(meta, variants, out, tok)
if doc['text_sha256'] in seen:
raise ValueError('Documento duplicado por hash del texto extraído')
seen.add(doc['text_sha256']); docs.append(doc); fixed_all.extend(fixed); structural_all.extend(structural)
except (ValueError, OSError, PdfReadError) as exc:
failures.append({'id': meta['id'], 'error': str(exc)})
if len(docs) < 2:
raise RuntimeError('Se necesitan al menos dos documentos distintos; revisa los errores y usa otro directorio')
# Partición reproducible por documento, no por fragmento. Al menos uno en cada grupo.
ordered = sorted(docs, key=lambda d: sha(d['metadata']['id'].encode('utf-8')))
n_test = max(1, len(ordered) // 5)
test_ids = {d['metadata']['id'] for d in ordered[:n_test]}
for doc in docs:
doc['split'] = 'test' if doc['metadata']['id'] in test_ids else 'dev'
split_by_id = {d['metadata']['id']: d['split'] for d in docs}
for chunk in fixed_all + structural_all:
chunk['split'] = split_by_id[chunk['doc_id']]
for filename, records in (('documentos.jsonl', docs), ('chunks.jsonl', fixed_all + structural_all)):
path = out / filename
if path.exists():
raise FileExistsError(f'Ya existe {path}; usa otro directorio')
for record in records:
append_jsonl(path, record)
manifest = {'created_at': now(), 'module_sha256': sha(module_text.encode('utf-8')),
'tokenizer': {'repo': TOKENIZER_REPO, 'revision': TOKENIZER_REV, 'sha256': TOKENIZER_SHA},
'chunking': {'size': SIZE, 'overlap': OVERLAP},
'documents': [{k: v for k, v in d.items() if k not in ('text', 'spans', 'views')} for d in docs],
'artifacts': {name: sha((out / name).read_bytes()) for name in ('documentos.jsonl', 'chunks.jsonl')},
'stats': {'tokens': stats(fixed_all), 'estructura': stats(structural_all)}, 'failures': failures}
digest = sha(canonical(manifest))
write_json(out / 'manifiesto.json', manifest, exclusive=True)
(out / 'manifiesto.sha256').write_text(digest + '\n', encoding='utf-8')
print('Manifiesto SHA256:', digest)
print('Estadísticas:', json.dumps(manifest['stats'], ensure_ascii=False))
print('Documentos dev/test:', len(docs) - n_test, n_test, 'fallos:', len(failures))
def round_robin(chunks):
groups = {}
for chunk in chunks:
groups.setdefault(chunk['doc_id'], []).append(chunk)
queues = [iter(groups[key]) for key in sorted(groups)]
return [item for row in itertools.zip_longest(*queues) for item in row if item is not None]
def no_frozen(out):
if (out / 'evaluacion-congelada.json').exists():
raise ValueError('Evaluación congelada: no se pueden añadir candidatos ni revisiones aquí')
def generate(out, target):
no_frozen(out)
_, manifest_sha = load_manifest(out)
if target < 1:
raise ValueError('target debe ser positivo')
candidates_path = out / 'candidatos.jsonl'
existing = read_jsonl(candidates_path)
completed = {row['chunk_id'] for row in existing}
chunks = round_robin([c for c in read_jsonl(out / 'chunks.jsonl') if c['strategy'] == 'estructura'])
docs = {d['metadata']['id']: d for d in read_jsonl(out / 'documentos.jsonl')}
with requests.Session() as session:
tags = get(session, BASE + '/api/tags').json().get('models', [])
match = next((m for m in tags if m.get('name') == MODEL), None)
if not match or not match.get('digest'):
raise RuntimeError('No se encuentra phi3:mini con digest: descarga y verifica la etiqueta antes de generar')
digest = match['digest']
for chunk in chunks:
if len(existing) >= target:
break
if chunk['id'] in completed:
continue
prompt = ('Write one specific question and a short answer supported by this passage. '
'Return only the required JSON fields. Do not invent facts.\n\n' + chunk['text'])
payload = {'model': MODEL, 'stream': False, 'format': SCHEMA, 'truncate': False, 'shift': False,
'messages': [{'role': 'user', 'content': prompt}],
'options': {'temperature': 0, 'num_ctx': 2048, 'num_batch': 128, 'num_predict': 256},
'keep_alive': '10s'}
for attempt in range(1, 4):
record = {'chunk_id': chunk['id'], 'attempt': attempt, 'at': now(), 'request': payload,
'model_digest': digest, 'http_status': None, 'response': None}
oom = False
retryable = False
try:
response = session.post(BASE + '/api/chat', json=payload, timeout=(10, 180))
record['http_status'] = response.status_code
record['response'] = response.text
response.raise_for_status()
result = response.json()
value = json.loads(result['message']['content'])
validate(value, SCHEMA)
if result.get('done_reason') == 'length':
raise ValueError('Respuesta truncada')
if not value['pregunta'].strip() or not value['respuesta'].strip():
raise ValueError('Pregunta o respuesta vacía')
a, b = chunk['start'], chunk['end']
doc = docs[chunk['doc_id']]
if doc['text'][a:b] != chunk['text']:
raise ValueError('El pasaje no coincide con la vista fuente en sus offsets')
candidate = {'id': sha(canonical([manifest_sha, chunk['id'], value])), 'chunk_id': chunk['id'],
'doc_id': chunk['doc_id'], 'split': chunk['split'], 'manifest_sha256': manifest_sha,
'question': value['pregunta'], 'answer': value['respuesta'], 'evidence': chunk['text'],
'evidence_start': a, 'evidence_end': b,
'sources': sources_for({'start': a, 'end': b}, doc['spans']),
'source_view': doc['metadata']['kind'], 'model': MODEL, 'model_digest': digest,
'created_at': now(), 'status': 'pendiente'}
append_jsonl(candidates_path, candidate)
existing.append(candidate); completed.add(chunk['id'])
record['candidate_id'] = candidate['id']
print('Candidato pendiente', len(existing), chunk['split'], chunk['doc_id'], flush=True)
except (requests.RequestException, ValueError, KeyError, TypeError, ValidationError) as exc:
record['error'] = str(exc)
detail = (str(exc) + ' ' + (record['response'] or '')).lower()
oom = ('out of memory' in detail or 'cuda_error_out_of_memory' in detail
or 'not enough memory' in detail or ('cuda' in detail and 'allocat' in detail))
retryable = oom or isinstance(exc, (requests.ConnectionError, requests.Timeout))
record['retryable'] = retryable
print('Intento fallido:', chunk['id'], attempt, str(exc), flush=True)
finally:
append_jsonl(out / 'intentos-generacion.jsonl', record)
if 'candidate_id' in record:
break
if not retryable:
break
if attempt < 3 and oom:
print('La GPU se ha quedado sin memoria: espera 90 s antes de reintentar.', flush=True)
time.sleep(90)
if chunk['id'] not in completed:
append_jsonl(out / 'errores-generacion.jsonl', {'chunk_id': chunk['id'], 'error': record.get('error'),
'attempts': attempt, 'at': now()})
print('Candidatos pendientes totales:', len(existing), 'de objetivo', target)
def review(out):
no_frozen(out)
_, manifest_sha = load_manifest(out)
if not sys.stdin.isatty():
raise RuntimeError('La revisión requiere una persona en una terminal interactiva')
reviewer = input('Nombre o identificador del revisor: ').strip()
if not reviewer:
raise ValueError('El revisor debe identificarse')
decisions = {r['candidate_id'] for r in read_jsonl(out / 'revisiones.jsonl')}
docs = {d['metadata']['id']: d for d in read_jsonl(out / 'documentos.jsonl')}
for candidate in read_jsonl(out / 'candidatos.jsonl'):
if candidate['id'] in decisions:
continue
if candidate['manifest_sha256'] != manifest_sha:
raise ValueError('Candidato generado para otro manifiesto')
doc = docs[candidate['doc_id']]
a, b = candidate['evidence_start'], candidate['evidence_end']
if doc['text'][a:b] != candidate['evidence']:
raise ValueError('La evidencia ya no coincide con los offsets del documento')
print('\nDocumento:', doc['metadata']['title'], 'URL:', doc['metadata']['source_url'])
print('Partición:', candidate['split'], 'páginas y secciones:', candidate['sources'])
print('Contexto:', doc['text'][max(0, a - 500):min(len(doc['text']), b + 500)])
print('Pregunta:', candidate['question'], '\nRespuesta:', candidate['answer'], '\nPasaje:', candidate['evidence'])
print('El fragmento es una evidencia candidata: comprueba si realmente responde a la pregunta.')
print('Comprueba respuesta, claridad, utilidad y evidencia en el documento fuente. [a]ceptar [c]orregir y aceptar [r]echazar [s]altar [q]salir')
action = input('Decisión: ').strip().lower()
if action == 'q':
break
if action not in ('a', 'c', 'r'):
continue
corrections = None
if action in ('a', 'c'):
question, answer = candidate['question'], candidate['answer']
start, end = a, b
if action == 'c':
question = input('Pregunta corregida (vacío conserva la original): ').strip() or question
answer = input('Respuesta corregida (vacío conserva la original): ').strip() or answer
interval = input(f'Subintervalo de evidencia, inicio y fin exclusivo relativos a 0..{b - a} (vacío conserva): ').strip()
if interval:
try:
relative_start, relative_end = (int(x) for x in interval.split())
if not 0 <= relative_start < relative_end <= b - a:
raise ValueError('intervalo fuera del pasaje')
start, end = a + relative_start, a + relative_end
if not doc['text'][start:end].strip():
raise ValueError('evidencia vacía')
except ValueError as exc:
print('Intervalo inválido, no se guardó ninguna decisión:', exc)
continue
corrections = {'question': question, 'answer': answer, 'evidence_start': start, 'evidence_end': end,
'evidence': doc['text'][start:end],
'sources': sources_for({'start': start, 'end': end}, doc['spans'])}
print('Evidencia final:', corrections['evidence'])
note = input('Nota de revisión (obligatoria): ').strip()
if not note:
print('Sin nota no se guarda ninguna decisión.')
continue
append_jsonl(out / 'revisiones.jsonl', {'candidate_id': candidate['id'],
'decision': 'aceptada_manualmente' if action in ('a', 'c') else 'rechazada_manualmente',
'reviewer': reviewer, 'note': note, 'corrections': corrections,
'at': now(), 'manifest_sha256': manifest_sha})
def freeze(out):
no_frozen(out)
manifest, digest = load_manifest(out)
candidates = {c['id']: c for c in read_jsonl(out / 'candidatos.jsonl')}
reviews = read_jsonl(out / 'revisiones.jsonl')
if len({r['candidate_id'] for r in reviews}) != len(reviews):
raise ValueError('Hay decisiones duplicadas para un candidato')
verified = []
docs = {d['metadata']['id']: d for d in read_jsonl(out / 'documentos.jsonl')}
for review in reviews:
if review['decision'] != 'aceptada_manualmente':
continue
candidate = candidates[review['candidate_id']]
if candidate['manifest_sha256'] != digest or review['manifest_sha256'] != digest:
raise ValueError('La revisión no pertenece al manifiesto actual')
doc = docs[candidate['doc_id']]
if doc['text'][candidate['evidence_start']:candidate['evidence_end']] != candidate['evidence']:
raise ValueError('El pasaje no coincide con el documento')
corrected = review.get('corrections')
if not corrected or not review.get('reviewer', '').strip() or not review.get('note', '').strip():
raise ValueError('La aceptación requiere revisor, nota y contenido final')
a, b = corrected['evidence_start'], corrected['evidence_end']
if not (candidate['evidence_start'] <= a < b <= candidate['evidence_end']):
raise ValueError('La evidencia corregida debe ser un subintervalo del fragmento original')
if doc['text'][a:b] != corrected['evidence'] or not corrected['evidence'].strip():
raise ValueError('La evidencia corregida no coincide literalmente con el documento')
if not corrected['question'].strip() or not corrected['answer'].strip():
raise ValueError('La pregunta y la respuesta corregidas no pueden estar vacías')
if corrected['sources'] != sources_for({'start': a, 'end': b}, doc['spans']):
raise ValueError('Las ubicaciones de la evidencia corregida no coinciden con el documento')
verified.append({'candidate': candidate, 'review': review, 'final': corrected})
if len(verified) < 150:
raise ValueError(f'Solo hay {len(verified)} aceptadas manualmente; hacen falta al menos 150')
if {v['candidate']['split'] for v in verified} != {'dev', 'test'}:
raise ValueError('Se necesita al menos una pregunta verificada en cada partición')
doc_splits = {d['metadata']['id']: d['split'] for d in manifest['documents']}
if any(doc_splits[v['candidate']['doc_id']] != v['candidate']['split'] for v in verified):
raise ValueError('La partición de alguna pregunta no coincide con el documento congelado')
snapshot = {'created_at': now(), 'manifest_sha256': digest, 'questions': verified,
'candidates_sha256': sha((out / 'candidatos.jsonl').read_bytes()),
'reviews_sha256': sha((out / 'revisiones.jsonl').read_bytes())}
write_json(out / 'evaluacion-congelada.json', snapshot, exclusive=True)
print('Evaluación congelada SHA256:', sha(canonical(snapshot)), 'preguntas:', len(verified))
print('No mires ni ajustes el recuperador con las preguntas de test.')
def automatic(out=DEFAULT_OUT, notes=None, target=150):
"""Prepara y genera candidatos sin solicitar entrada; no revisa ni congela."""
out = Path(out)
if not (out / 'manifiesto.json').exists():
prepare(out, notes)
generate(out, target)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--out', type=Path, default=DEFAULT_OUT, help='Directorio de salida del experimento')
commands = parser.add_subparsers(dest='command', required=True)
build = commands.add_parser('prepare')
build.add_argument('--notes', type=Path, help='Directorio opcional con notas PDF, HTML o TXT')
gen = commands.add_parser('generate')
gen.add_argument('--target', type=int, default=150, help='Número total deseado de candidatos, no verificaciones')
commands.add_parser('review')
commands.add_parser('freeze')
args = parser.parse_args()
if args.command == 'prepare': prepare(args.out, args.notes)
elif args.command == 'generate': generate(args.out, args.target)
elif args.command == 'review': review(args.out)
else: freeze(args.out)
def run_cell():
"""Ejecución desde el cuaderno: ejecución nueva o reanudación comprobada; sin revisión."""
import tempfile
target_base = LAB_DIR.resolve()
target_base.mkdir(parents=True, exist_ok=True)
resume = os.environ.get('P05_L02_REANUDAR')
if resume:
run_dir = Path(resume).resolve()
if target_base not in run_dir.parents:
raise ValueError('El directorio de reanudación debe estar dentro de ' + str(target_base))
manifest, digest = load_manifest(run_dir)
print('Manifiesto comprobado:', digest, 'Estadísticas:', json.dumps(manifest['stats'], ensure_ascii=False))
else:
run_dir = Path(tempfile.mkdtemp(prefix='ejecucion-', dir=str(target_base)))
print('Directorio de esta ejecución:', run_dir, flush=True)
automatic(out=run_dir, target=150)
def launched_as_program():
# python laboratorio.py ORDEN: el fichero ejecutado es este módulo. En un cuaderno no hay __file__.
path = globals().get('__file__')
return path is not None and Path(sys.argv[0]).resolve() == Path(path).resolve()
if __name__ == '__main__':
if launched_as_program():
main()
else:
run_cell()npm run lab and open the connection link.When comparing summaries, check document and chunk counts, token sizes, missing sources, and splits. Window length is calculated using the pinned tokenizer and its offsets; a character- or word-based counter would not be equivalent. Do not compare HTML view ranges with PDF view ranges as if they were the same string. The program does not itself detect duplicate, trivial, or ambiguous questions or certify that a chunk answers them: review must check this. Generated candidates form a work queue; the set of 150 verified questions is what you obtain after finishing review and running freeze, which writes evaluacion-congelada.json with manifest, candidate, and review fingerprints.
As a reference for what you should see, a complete ingestion and generation run with this same code (Ollama with phi3:mini, size 384 and overlap 64 with the Phi-3 tokenizer) ingested the 20 arXiv papers cited in the module without failures: 19 by HTML view and 1 only in PDF. The document split left 16 in development and 4 in test. Fixed windows produced 1212 chunks (median 384 tokens, minimum 72) and structural chunking 1460 (also median 384, but 85 chunks under 64 tokens: short sections and section remainders create small pieces). The 150 candidates were split 121 development and 29 test. The model mixed languages: 110 questions came out in Spanish and 40 in English, although instructions and passages were in English. Your numbers may differ if arXiv publishes new versions or the model tag changes; the manifest therefore records versions and fingerprints.
In that same run, one candidate attributed a significant performance increase at high recall on highly clustered data to HNSW’s “separation of scales.” The original paper’s abstract attributes that improvement to an additional neighbor-selection heuristic; separation of scales and search from the top layer are described separately. The saved chunk was literal, but the answer’s association was wrong. An automatic check that evidence appears in the document would have accepted it: this is exactly the kind of error your review should reject or correct.
Exercises
def chunk_by_tokens(text, size, overlap, tokenizer):
passEvidence must survive extraction and chunking with a verifiable path to the original. Candidate questions become an evaluation only when answers and passages are reviewed, versioned, and the test is reserved before tuning the system.