feat: sincroniza ingestão RAG incremental

This commit is contained in:
Bruno Viana 2026-10-23 19:01:06 -03:00
parent 6384401d8b
commit a75c1f1708
8 changed files with 755 additions and 275 deletions

View file

@ -94,240 +94,8 @@ reset_apply() {
ingest_python() {
require_project_python
"$PROJECT_PYTHON" - "$ROOT" "$QDRANT_URL" "$OLLAMA_URL" "$EMBED_MODEL" "$NEW_COLLECTION" "$1" <<'PY'
import sys
import os
import json
import hashlib
import uuid
import subprocess
from pathlib import Path
import requests
ROOT = Path(sys.argv[1])
QDRANT_URL = sys.argv[2].rstrip("/")
OLLAMA_URL = sys.argv[3].rstrip("/")
MODEL = sys.argv[4]
COLLECTION = sys.argv[5]
MODE = sys.argv[6]
CHUNK_SIZE = 1200
OVERLAP = 200
BATCH = 16
VECTOR_SIZE = 768
if not ROOT.is_dir():
raise SystemExit(f"Diretório não encontrado: {ROOT}")
session = requests.Session()
session.headers.update({"Content-Type": "application/json"})
def fail(msg):
raise SystemExit("[ERRO] " + msg)
def get_collection():
r = session.get(f"{QDRANT_URL}/collections/{COLLECTION}", timeout=30)
if r.status_code != 200:
fail(f"Collection {COLLECTION} não encontrada.")
r.raise_for_status()
return r.json()["result"]
def extract(path):
if path.suffix.lower() == ".pdf":
try:
result = subprocess.run(
["pdftotext", "-layout", str(path), "-"],
capture_output=True,
text=True,
check=True,
)
return result.stdout
except Exception as e:
fail(f"Falha lendo PDF {path}: {e}")
return path.read_text(encoding="utf-8", errors="replace")
def sector(path):
rel = path.relative_to(ROOT)
if len(rel.parts) > 1:
return rel.parts[0]
return "00_GLOBAL"
def chunks(text):
text = text.replace("\x00", "").strip()
if not text:
return []
out = []
start = 0
n = len(text)
while start < n:
end = min(start + CHUNK_SIZE, n)
piece = text[start:end].strip()
if piece:
out.append(piece)
if end >= n:
break
start = end - OVERLAP
return out
def point_id(doc_sha, index):
return str(uuid.uuid5(
uuid.NAMESPACE_URL,
f"ativa-ia:{doc_sha}:{index}"
))
# ---------- validações ----------
info = get_collection()
cfg = info.get("config", {})
params = cfg.get("params", {})
vectors = params.get("vectors", {})
if isinstance(vectors, dict) and "size" in vectors:
if vectors["size"] != VECTOR_SIZE:
fail(f"Collection usa vetor {vectors['size']}; esperado {VECTOR_SIZE}.")
print(f"[OK] Collection: {COLLECTION}")
print(f"[OK] Vetor: {VECTOR_SIZE}")
print(f"[OK] Modelo: {MODEL}")
files = sorted(
p for p in ROOT.rglob("*")
if p.is_file() and p.suffix.lower() in {".md", ".pdf"}
)
if not files:
fail("Nenhum .md/.pdf encontrado.")
documents = []
total_chunks = 0
for path in files:
text = extract(path)
raw = text.encode("utf-8")
sha = hashlib.sha256(raw).hexdigest()
cs = chunks(text)
documents.append({
"path": path,
"relative": str(path.relative_to(ROOT)),
"sector": sector(path),
"sha256": sha,
"chars": len(text),
"chunks": cs,
})
total_chunks += len(cs)
print(f"[OK] Documentos: {len(documents)}")
print(f"[OK] Chunks: {total_chunks}")
if MODE == "dry-run":
for d in documents:
print(f" {d['relative']} | chars={d['chars']} | chunks={len(d['chunks'])}")
print()
print("DRY-RUN concluído. Nenhum vetor enviado.")
raise SystemExit(0)
# ---------- ingestão ----------
sent = 0
for d in documents:
cs = d["chunks"]
for batch_start in range(0, len(cs), BATCH):
batch = cs[batch_start:batch_start+BATCH]
r = session.post(
f"{OLLAMA_URL}/api/embed",
json={
"model": MODEL,
"input": batch,
},
timeout=300,
)
r.raise_for_status()
data = r.json()
if data.get("error"):
fail(f"Ollama: {data['error']}")
embeddings = data.get("embeddings")
if not embeddings:
fail("Ollama não retornou embeddings.")
if len(embeddings) != len(batch):
fail(
f"Ollama retornou {len(embeddings)} embeddings "
f"para {len(batch)} textos."
)
points = []
for j, (text, vector) in enumerate(zip(batch, embeddings)):
if len(vector) != VECTOR_SIZE:
fail(
f"Dimensão inválida no chunk "
f"{batch_start+j}: {len(vector)}"
)
index = batch_start + j
payload = {
"source": d["relative"],
"path": d["relative"],
"sector": d["sector"],
"sha256": d["sha256"],
"chunk_index": index,
"text": text,
"chars": len(text),
"embedding_model": MODEL,
}
points.append({
"id": point_id(d["sha256"], index),
"vector": vector,
"payload": payload,
})
r = session.put(
f"{QDRANT_URL}/collections/{COLLECTION}/points",
params={"wait": "true"},
json={"points": points},
timeout=300,
)
r.raise_for_status()
result = r.json().get("result", {})
if result.get("status") not in (None, "ok", "completed"):
fail(f"Qdrant rejeitou lote: {result}")
sent += len(points)
print(
f"[OK] {sent}/{total_chunks} chunks | "
f"{d['relative']}"
)
print()
print("======================================")
print("INGESTÃO CONCLUÍDA")
print("======================================")
print(f"Collection : {COLLECTION}")
print(f"Documentos : {len(documents)}")
print(f"Chunks : {total_chunks}")
print(f"Enviados : {sent}")
print(f"Modelo : {MODEL}")
print("======================================")
PY
"$PROJECT_PYTHON" "$SCRIPT_DIR/atvctl_ingest.py" \
"$ROOT" "$QDRANT_URL" "$OLLAMA_URL" "$EMBED_MODEL" "$NEW_COLLECTION" "$1"
}
ingest_dry_run() {

503
bin/atvctl_ingest.py Normal file
View file

@ -0,0 +1,503 @@
#!/usr/bin/env python3
"""Offline-testable RAG document synchronization used by bin/atvctl."""
from __future__ import annotations
import hashlib
import os
import subprocess
import sys
import uuid
from dataclasses import dataclass
from pathlib import Path
from typing import Any
CHUNK_SIZE = 1200
OVERLAP = 200
BATCH_SIZE = 16
VECTOR_SIZE = 768
SCROLL_PAGE_SIZE = 256
DELETE_BATCH_SIZE = 256
MANAGED_BY = "atvctl"
class IngestError(RuntimeError):
pass
@dataclass(frozen=True)
class Document:
relative: str
sector: str
sha256: str
document_id: str
chunks: tuple[str, ...]
@dataclass(frozen=True)
class SyncAction:
relative: str
status: str
document: Document | None
existing_points: tuple[dict[str, Any], ...]
expected_ids: frozenset[str]
def chunk_text(text: str) -> tuple[str, ...]:
text = text.replace("\x00", "").strip()
if not text:
return ()
result: list[str] = []
start = 0
while start < len(text):
end = min(start + CHUNK_SIZE, len(text))
piece = text[start:end].strip()
if piece:
result.append(piece)
if end >= len(text):
break
start = end - OVERLAP
return tuple(result)
def stable_document_id(relative: str) -> str:
return str(uuid.uuid5(uuid.NAMESPACE_URL, f"ativa-ia:document:{relative}"))
def point_id(document_id: str, chunk_index: int) -> str:
return str(uuid.uuid5(
uuid.NAMESPACE_URL,
f"ativa-ia:point:{document_id}:{chunk_index}",
))
def legacy_point_id(doc_sha: str, chunk_index: int) -> str:
"""Recognize only IDs generated by the previous atvctl implementation."""
return str(uuid.uuid5(
uuid.NAMESPACE_URL,
f"ativa-ia:{doc_sha}:{chunk_index}",
))
def _extract(path: Path) -> str:
if path.suffix.lower() == ".pdf":
try:
result = subprocess.run(
["pdftotext", "-layout", str(path), "-"],
capture_output=True,
text=True,
check=True,
)
except (OSError, subprocess.CalledProcessError) as exc:
raise IngestError(f"Falha lendo PDF {path}: {exc}") from exc
return result.stdout
return path.read_text(encoding="utf-8", errors="replace")
def discover_documents(root: Path) -> list[Document]:
root = root.resolve()
if not root.is_dir():
raise IngestError(f"Diretório de conhecimento não encontrado: {root}")
paths: list[Path] = []
for path in root.rglob("*"):
if path.is_symlink() or not path.is_file():
continue
if path.suffix.lower() not in {".md", ".pdf"}:
continue
try:
path.resolve().relative_to(root)
except ValueError:
continue
paths.append(path)
paths.sort(key=lambda item: item.relative_to(root).as_posix())
if not paths:
raise IngestError(
"Nenhum .md/.pdf encontrado; sincronização cancelada "
"para evitar limpeza acidental."
)
documents: list[Document] = []
for path in paths:
relative = path.relative_to(root).as_posix()
text = _extract(path)
digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
pieces = chunk_text(text)
sector = path.relative_to(root).parts[0]
if len(path.relative_to(root).parts) == 1:
sector = "00_GLOBAL"
documents.append(Document(
relative=relative,
sector=sector,
sha256=digest,
document_id=stable_document_id(relative),
chunks=pieces,
))
return documents
def _is_managed_point(point: dict[str, Any]) -> bool:
payload = point.get("payload") or {}
if payload.get("managed_by") == MANAGED_BY:
return True
source = payload.get("source")
digest = payload.get("sha256")
chunk_index = payload.get("chunk_index")
return (
isinstance(source, str)
and isinstance(digest, str)
and isinstance(chunk_index, int)
and str(point.get("id")) == legacy_point_id(digest, chunk_index)
)
def group_managed_points(
points: list[dict[str, Any]],
) -> dict[str, tuple[dict[str, Any], ...]]:
groups: dict[str, list[dict[str, Any]]] = {}
for point in points:
if not _is_managed_point(point):
continue
payload = point.get("payload") or {}
source = payload.get("source")
if not isinstance(source, str) or not source:
raise IngestError(
f"Ponto gerenciado sem source; sincronização cancelada: {point.get('id')}"
)
groups.setdefault(source, []).append(point)
return {key: tuple(value) for key, value in groups.items()}
def build_plan(
documents: list[Document],
points: list[dict[str, Any]],
) -> list[SyncAction]:
grouped = group_managed_points(points)
current = {document.relative: document for document in documents}
actions: list[SyncAction] = []
for relative, document in sorted(current.items()):
existing = grouped.get(relative, ())
expected_ids = frozenset(
point_id(document.document_id, index)
for index in range(len(document.chunks))
)
expected_indexes = {
point_id(document.document_id, index): index
for index in range(len(document.chunks))
}
current_points = [
point for point in existing
if str(point.get("id")) in expected_ids
and (point.get("payload") or {}).get("document_id") == document.document_id
and (point.get("payload") or {}).get("document_hash") == document.sha256
and (point.get("payload") or {}).get("chunk_index")
== expected_indexes.get(str(point.get("id")))
]
unchanged = (
len(existing) == len(expected_ids)
and len(current_points) == len(expected_ids)
)
if unchanged or (not existing and not document.chunks):
status = "unchanged"
else:
status = "modified" if existing else "new"
actions.append(SyncAction(
relative=relative,
status=status,
document=document,
existing_points=existing,
expected_ids=expected_ids,
))
for relative, existing in sorted(grouped.items()):
if relative not in current:
actions.append(SyncAction(
relative=relative,
status="removed",
document=None,
existing_points=existing,
expected_ids=frozenset(),
))
return actions
def _raise_for_status(response: Any) -> None:
response.raise_for_status()
def _collection_info(
session: Any,
qdrant_url: str,
collection: str,
) -> dict[str, Any]:
response = session.get(
f"{qdrant_url.rstrip('/')}/collections/{collection}",
timeout=30,
)
_raise_for_status(response)
data = response.json().get("result", {})
vectors = data.get("config", {}).get("params", {}).get("vectors")
if not isinstance(vectors, dict) or vectors.get("size") != VECTOR_SIZE:
raise IngestError(
f"Collection precisa usar vetor simples de {VECTOR_SIZE} dimensões."
)
return data
def _scroll_points(
session: Any,
qdrant_url: str,
collection: str,
) -> list[dict[str, Any]]:
endpoint = (
f"{qdrant_url.rstrip('/')}/collections/{collection}/points/scroll"
)
offset: Any = None
seen_offsets: set[str] = set()
points: list[dict[str, Any]] = []
while True:
body: dict[str, Any] = {
"limit": SCROLL_PAGE_SIZE,
"with_payload": [
"managed_by", "source", "path", "document_id",
"document_hash", "sha256", "chunk_index",
],
"with_vector": False,
}
if offset is not None:
body["offset"] = offset
response = session.post(endpoint, json=body, timeout=60)
_raise_for_status(response)
result = response.json().get("result", {})
page = result.get("points", [])
if not isinstance(page, list):
raise IngestError("Resposta inválida ao percorrer pontos do Qdrant.")
points.extend(page)
next_offset = result.get("next_page_offset")
if next_offset is None:
break
token = str(next_offset)
if token in seen_offsets:
raise IngestError("Paginação do Qdrant repetiu o cursor.")
seen_offsets.add(token)
offset = next_offset
return points
def _embeddings(
session: Any,
ollama_url: str,
model: str,
texts: list[str],
) -> list[list[float]]:
response = session.post(
f"{ollama_url.rstrip('/')}/api/embed",
json={"model": model, "input": texts},
timeout=300,
)
_raise_for_status(response)
data = response.json()
if data.get("error"):
raise IngestError(f"Ollama: {data['error']}")
vectors = data.get("embeddings")
if not isinstance(vectors, list) or len(vectors) != len(texts):
raise IngestError(
f"Ollama retornou {len(vectors or [])} embeddings para {len(texts)} textos."
)
for index, vector in enumerate(vectors):
if not isinstance(vector, list) or len(vector) != VECTOR_SIZE:
size = len(vector) if isinstance(vector, list) else "inválida"
raise IngestError(
f"Dimensão inválida no chunk {index}: {size}; esperado {VECTOR_SIZE}."
)
return vectors
def _upsert(
session: Any,
qdrant_url: str,
collection: str,
points: list[dict[str, Any]],
) -> None:
endpoint = (
f"{qdrant_url.rstrip('/')}/collections/{collection}/points"
)
response = session.put(
endpoint,
params={"wait": "true"},
json={"points": points},
timeout=300,
)
_raise_for_status(response)
result = response.json().get("result", {})
if result.get("status") not in (None, "ok", "completed"):
raise IngestError(f"Qdrant rejeitou upsert: {result}")
def _delete_ids(
session: Any,
qdrant_url: str,
collection: str,
point_ids: list[Any],
) -> None:
if not point_ids:
return
endpoint = (
f"{qdrant_url.rstrip('/')}/collections/{collection}/points/delete"
)
for start in range(0, len(point_ids), DELETE_BATCH_SIZE):
response = session.post(
endpoint,
params={"wait": "true"},
json={"points": point_ids[start:start + DELETE_BATCH_SIZE]},
timeout=300,
)
_raise_for_status(response)
def _apply_document(
session: Any,
document: Document,
qdrant_url: str,
ollama_url: str,
collection: str,
model: str,
stale_ids: list[Any],
) -> None:
for start in range(0, len(document.chunks), BATCH_SIZE):
texts = list(document.chunks[start:start + BATCH_SIZE])
vectors = _embeddings(session, ollama_url, model, texts)
points = []
for offset, (text, vector) in enumerate(zip(texts, vectors)):
index = start + offset
points.append({
"id": point_id(document.document_id, index),
"vector": vector,
"payload": {
"managed_by": MANAGED_BY,
"document_id": document.document_id,
"document_hash": document.sha256,
"source": document.relative,
"path": document.relative,
"sector": document.sector,
"sha256": document.sha256,
"chunk_index": index,
"text": text,
"chars": len(text),
"embedding_model": model,
},
})
_upsert(session, qdrant_url, collection, points)
# Remove old-generation or excess chunks only after the replacement chunks
# for this document have been embedded and accepted by Qdrant.
_delete_ids(session, qdrant_url, collection, stale_ids)
def synchronize(
root: Path,
session: Any,
qdrant_url: str,
ollama_url: str,
model: str,
collection: str,
mode: str,
) -> list[SyncAction]:
if mode not in {"dry-run", "apply"}:
raise IngestError(f"Modo inválido: {mode}")
_collection_info(session, qdrant_url, collection)
documents = discover_documents(root)
existing = _scroll_points(session, qdrant_url, collection)
plan = build_plan(documents, existing)
if mode == "dry-run":
return plan
grouped = group_managed_points(existing)
for action in plan:
if action.status == "unchanged":
continue
if action.document is None:
stale_ids = [point.get("id") for point in action.existing_points]
_delete_ids(session, qdrant_url, collection, stale_ids)
continue
expected_ids = {
point_id(action.document.document_id, index)
for index in range(len(action.document.chunks))
}
stale_ids = [
point.get("id")
for point in grouped.get(action.relative, ())
if str(point.get("id")) not in expected_ids
]
_apply_document(
session,
action.document,
qdrant_url,
ollama_url,
collection,
model,
stale_ids,
)
return plan
def _print_plan(actions: list[SyncAction], mode: str) -> None:
totals = {status: 0 for status in ("new", "modified", "unchanged", "removed")}
for action in actions:
totals[action.status] += 1
chunk_count = len(action.document.chunks) if action.document else 0
print(f"[{action.status.upper()}] {action.relative} | chunks={chunk_count}")
print(
"Resumo: "
+ ", ".join(f"{key}={value}" for key, value in totals.items())
)
if mode == "dry-run":
print("DRY-RUN concluído. Nenhum vetor foi escrito ou removido.")
else:
print("Sincronização concluída.")
def main(argv: list[str] | None = None) -> int:
argv = list(sys.argv[1:] if argv is None else argv)
if len(argv) != 6:
print(
"Uso interno: atvctl_ingest.py ROOT QDRANT_URL OLLAMA_URL "
"MODEL COLLECTION dry-run|apply",
file=sys.stderr,
)
return 2
root, qdrant_url, ollama_url, model, collection, mode = argv
if mode == "apply" and os.environ.get("CONFIRM") != "YES":
print("[ERRO] Use CONFIRM=YES para autorizar ingestão --apply.", file=sys.stderr)
return 2
try:
import requests
except ImportError as exc:
print(f"[ERRO] requests ausente no ambiente do projeto: {exc}", file=sys.stderr)
return 1
session = requests.Session()
session.headers.update({"Content-Type": "application/json"})
try:
plan = synchronize(
Path(root), session, qdrant_url, ollama_url, model, collection, mode
)
except (IngestError, OSError) as exc:
print(f"[ERRO] {exc}", file=sys.stderr)
return 1
_print_plan(plan, mode)
return 0
if __name__ == "__main__":
raise SystemExit(main())