feat: sincroniza ingestão RAG incremental
This commit is contained in:
parent
6384401d8b
commit
a75c1f1708
8 changed files with 755 additions and 275 deletions
236
bin/atvctl
236
bin/atvctl
|
|
@ -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() {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue