ativa-ia/bin/atvctl_ingest.py

723 lines
24 KiB
Python

#!/usr/bin/env python3
"""Offline-testable RAG document synchronization used by bin/atvctl."""
from __future__ import annotations
import hashlib
from html.parser import HTMLParser
import os
import posixpath
import re
import subprocess
import sys
import uuid
import zipfile
import xml.etree.ElementTree as ET
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
CHUNK_SIZE = 1200
OVERLAP = 200
BATCH_SIZE = 16
VECTOR_SIZE = 768
SUPPORTED_SUFFIXES = {".md", ".pdf", ".txt", ".docx", ".xlsx", ".html", ".htm"}
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, ...]
chunk_metadata: tuple[dict[str, Any], ...]
@dataclass(frozen=True)
class TextSegment:
text: str
section: str | None = None
page: int | None = None
@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 _group_sectioned_lines(lines: list[tuple[str | None, str]]) -> list[TextSegment]:
segments: list[TextSegment] = []
current_section: str | None = None
current_lines: list[str] = []
for section, text in lines:
text = text.strip()
if not text:
continue
if section is not None:
if current_lines:
segments.append(TextSegment("\n".join(current_lines), current_section))
current_lines = []
current_section = section
current_lines.append(section)
else:
current_lines.append(text)
if current_lines:
segments.append(TextSegment("\n".join(current_lines), current_section))
return segments
class _HTMLTextParser(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.lines: list[tuple[str | None, str]] = []
self.current_tag: str | None = None
self.current_text: list[str] = []
self.skip_depth = 0
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag in {"script", "style", "noscript"}:
self.skip_depth += 1
if self.skip_depth:
return
if tag in {"h1", "h2", "h3", "h4", "h5", "h6", "p", "li", "tr"}:
self._finish()
self.current_tag = tag
self.current_text = []
def handle_endtag(self, tag: str) -> None:
if tag in {"script", "style", "noscript"} and self.skip_depth:
self.skip_depth -= 1
return
if not self.skip_depth and tag == self.current_tag:
self._finish()
def handle_data(self, data: str) -> None:
if not self.skip_depth:
value = " ".join(data.split())
if value:
if self.current_tag:
self.current_text.append(value)
else:
self.lines.append((None, value))
def _finish(self) -> None:
value = " ".join(self.current_text).strip()
if value:
heading = self.current_tag in {"h1", "h2", "h3", "h4", "h5", "h6"}
self.lines.append((self.current_tag if heading else None, value))
self.current_tag = None
self.current_text = []
def _extract_docx(path: Path) -> list[TextSegment]:
ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
try:
with zipfile.ZipFile(path) as archive:
root = ET.fromstring(archive.read("word/document.xml"))
except (OSError, KeyError, zipfile.BadZipFile, ET.ParseError) as exc:
raise IngestError(f"Falha lendo DOCX {path}: {exc}") from exc
lines: list[tuple[str | None, str]] = []
for paragraph in root.findall(".//w:p", ns):
text = "".join(node.text or "" for node in paragraph.findall(".//w:t", ns)).strip()
if not text:
continue
style = paragraph.find("./w:pPr/w:pStyle", ns)
style_id = style.get(f"{{{ns['w']}}}val", "") if style is not None else ""
section = text if re.fullmatch(r"Heading[1-6]", style_id, re.IGNORECASE) else None
lines.append((section, text))
return _group_sectioned_lines(lines)
def _extract_xlsx(path: Path) -> list[TextSegment]:
ns = {
"main": "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
"rel": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
"pkg": "http://schemas.openxmlformats.org/package/2006/relationships",
}
try:
with zipfile.ZipFile(path) as archive:
workbook = ET.fromstring(archive.read("xl/workbook.xml"))
rels = ET.fromstring(archive.read("xl/_rels/workbook.xml.rels"))
targets = {
rel.get("Id"): rel.get("Target", "")
for rel in rels.findall("pkg:Relationship", ns)
}
shared: list[str] = []
if "xl/sharedStrings.xml" in archive.namelist():
shared_root = ET.fromstring(archive.read("xl/sharedStrings.xml"))
shared = [
"".join(node.text or "" for node in item.findall(".//main:t", ns))
for item in shared_root.findall("main:si", ns)
]
segments: list[TextSegment] = []
for sheet in workbook.findall(".//main:sheet", ns):
name = sheet.get("name") or "Planilha"
rel_id = sheet.get(f"{{{ns['rel']}}}id")
target = targets.get(rel_id or "")
if not target:
continue
target = target.lstrip("/")
sheet_path = posixpath.normpath(
target if target.startswith("xl/") else posixpath.join("xl", target)
)
if sheet_path.startswith("../") or sheet_path not in archive.namelist():
continue
sheet_root = ET.fromstring(archive.read(sheet_path))
rows: list[str] = []
for row in sheet_root.findall(".//main:sheetData/main:row", ns):
values: list[str] = []
for cell in row.findall("main:c", ns):
value = cell.find("main:v", ns)
if cell.get("t") == "inlineStr":
text = "".join(node.text or "" for node in cell.findall(".//main:t", ns))
elif value is not None:
text = value.text or ""
if cell.get("t") == "s":
try:
text = shared[int(text)]
except (ValueError, IndexError):
text = ""
else:
text = ""
if text:
values.append(text)
if values:
rows.append(" | ".join(values))
if rows:
segments.append(TextSegment("\n".join(rows), section=name))
return segments
except (OSError, KeyError, zipfile.BadZipFile, ET.ParseError) as exc:
raise IngestError(f"Falha lendo XLSX {path}: {exc}") from exc
def _extract_segments(path: Path) -> list[TextSegment]:
suffix = path.suffix.lower()
if suffix == ".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 [
TextSegment(text.strip(), page=index)
for index, text in enumerate(result.stdout.split("\f"), start=1)
if text.strip()
]
if suffix in {".docx"}:
return _extract_docx(path)
if suffix == ".xlsx":
return _extract_xlsx(path)
if suffix in {".html", ".htm"}:
parser = _HTMLTextParser()
parser.feed(path.read_text(encoding="utf-8", errors="replace"))
parser.close()
lines = [
(text if tag in {"h1", "h2", "h3", "h4", "h5", "h6"} else None, text)
for tag, text in parser.lines
]
return _group_sectioned_lines(lines)
text = path.read_text(encoding="utf-8", errors="replace")
if suffix == ".md":
lines = []
for line in text.splitlines():
heading = re.match(r"^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$", line)
lines.append((heading.group(1).strip() if heading else None, line))
return _group_sectioned_lines(lines)
return [TextSegment(text)]
def _extract(path: Path) -> str:
"""Compatibility helper returning extracted text without segment metadata."""
return "\n\n".join(segment.text for segment in _extract_segments(path))
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] = []
unsupported: list[str] = []
for path in root.rglob("*"):
if path.is_symlink() or not path.is_file():
continue
if path.suffix.lower() not in SUPPORTED_SUFFIXES:
unsupported.append(path.relative_to(root).as_posix())
continue
try:
path.resolve().relative_to(root)
except ValueError:
continue
paths.append(path)
if unsupported:
preview = ", ".join(sorted(unsupported)[:10])
more = " ..." if len(unsupported) > 10 else ""
raise IngestError(
"Formatos não suportados encontrados; nenhuma sincronização será "
f"executada: {preview}{more}"
)
paths.sort(key=lambda item: item.relative_to(root).as_posix())
if not paths:
raise IngestError(
"Nenhum documento suportado encontrado; sincronização cancelada "
"para evitar limpeza acidental."
)
documents: list[Document] = []
for path in paths:
relative = path.relative_to(root).as_posix()
segments = _extract_segments(path)
text = "\n\n".join(segment.text for segment in segments)
digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
pieces: list[str] = []
chunk_metadata: list[dict[str, Any]] = []
for segment in segments:
for piece in chunk_text(segment.text):
pieces.append(piece)
metadata: dict[str, Any] = {}
if segment.section:
metadata["section"] = segment.section
if segment.page is not None:
metadata["page"] = segment.page
chunk_metadata.append(metadata)
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=tuple(pieces),
chunk_metadata=tuple(chunk_metadata),
))
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:
indexed_at = datetime.now(timezone.utc).isoformat()
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,
"file_type": Path(document.relative).suffix.lower().lstrip("."),
"document_version": document.sha256[:16],
"document_status": "active",
"indexed_at": indexed_at,
**document.chunk_metadata[index],
},
})
_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())