#!/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())