feat: adiciona formatos e metadados ao RAG
This commit is contained in:
parent
e7850f0416
commit
c2c2fc716c
10 changed files with 400 additions and 21 deletions
|
|
@ -4,11 +4,17 @@
|
|||
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
|
||||
|
||||
|
|
@ -16,6 +22,7 @@ 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"
|
||||
|
|
@ -32,6 +39,14 @@ class Document:
|
|||
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)
|
||||
|
|
@ -80,8 +95,155 @@ def legacy_point_id(doc_sha: str, chunk_index: int) -> str:
|
|||
))
|
||||
|
||||
|
||||
def _extract(path: Path) -> str:
|
||||
if path.suffix.lower() == ".pdf":
|
||||
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), "-"],
|
||||
|
|
@ -91,8 +253,38 @@ def _extract(path: Path) -> str:
|
|||
)
|
||||
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")
|
||||
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]:
|
||||
|
|
@ -101,10 +293,12 @@ def discover_documents(root: Path) -> list[Document]:
|
|||
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 {".md", ".pdf"}:
|
||||
if path.suffix.lower() not in SUPPORTED_SUFFIXES:
|
||||
unsupported.append(path.relative_to(root).as_posix())
|
||||
continue
|
||||
try:
|
||||
path.resolve().relative_to(root)
|
||||
|
|
@ -112,19 +306,38 @@ def discover_documents(root: Path) -> list[Document]:
|
|||
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 .md/.pdf encontrado; sincronização cancelada "
|
||||
"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()
|
||||
text = _extract(path)
|
||||
segments = _extract_segments(path)
|
||||
text = "\n\n".join(segment.text for segment in segments)
|
||||
digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
|
||||
pieces = chunk_text(text)
|
||||
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"
|
||||
|
|
@ -133,7 +346,8 @@ def discover_documents(root: Path) -> list[Document]:
|
|||
sector=sector,
|
||||
sha256=digest,
|
||||
document_id=stable_document_id(relative),
|
||||
chunks=pieces,
|
||||
chunks=tuple(pieces),
|
||||
chunk_metadata=tuple(chunk_metadata),
|
||||
))
|
||||
return documents
|
||||
|
||||
|
|
@ -370,6 +584,7 @@ def _apply_document(
|
|||
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)
|
||||
|
|
@ -391,6 +606,11 @@ def _apply_document(
|
|||
"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)
|
||||
|
|
|
|||
|
|
@ -5,9 +5,11 @@ Código/configuração e smoke tests somente de leitura revisados em 23/10/2026;
|
|||
## Ingestão atual
|
||||
`atvctl ingest --dry-run` calcula o plano (novos, alterados, inalterados e removidos) após leitura paginada dos pontos da coleção. Não grava vetores; ainda lê documentos e consulta Qdrant. `CONFIRM=YES atvctl ingest --apply` envia embeddings e faz upsert de pontos por documento; depois de aceitar os novos chunks remove IDs antigos/excedentes daquele documento. A identidade é derivada do caminho relativo, evitando colisão entre documentos com conteúdo idêntico. Pontos do formato anterior de `atvctl` são reconhecidos pelo ID legado e substituídos após upsert. Pontos sem marcador/ID legado correspondente são preservados.
|
||||
|
||||
O fluxo está em `bin/atvctl_ingest.py`, chamado por `bin/atvctl`; testes locais com Qdrant/Ollama simulados em `tests/test_atvctl_ingest.py`. Suporte a fontes permanece Markdown/PDF via `pdftotext`.
|
||||
O fluxo está em `bin/atvctl_ingest.py`, chamado por `bin/atvctl`; testes locais com Qdrant/Ollama simulados em `tests/test_atvctl_ingest.py`. A extração local suporta MD, PDF (via `pdftotext`), TXT, DOCX, XLSX, HTML e HTM. As fixtures offline cobrem texto simples/HTML, DOCX/XLSX e PDF simulado. Markdown/DOCX/HTML registram seção quando detectada; PDF preserva número de página. Cada ponto recebe formato, estado `active`, versão derivada do hash e timestamp UTC de indexação.
|
||||
|
||||
`rag-api/source_metadata.py` mantém nas referências retornadas o formato, seção, página e identidade/posição do chunk quando esses campos existem no payload. Metadados ausentes não são inventados. A integração completa pelo endpoint FastAPI ainda depende de teste de contrato com suas dependências e de acesso ao runtime.
|
||||
|
||||
## Limites
|
||||
A implementação de ingestão não foi executada contra serviços reais. Smoke test sintético confirmou Ollama `/api/embed` (768D) e busca somente de leitura no Qdrant; nenhuma ingestão foi feita. Apply pode concluir parcialmente se houver falha de rede; a repetição replaneja pelo estado lido e reenvia chunks que faltam. Não execute ingestão real, reset ou consultas operacionais como teste genérico. Ainda faltam os formatos TXT/DOCX/XLSX/HTML, extração de seção/página e agendamento cron/systemd. O estado do runtime e da coleção continua não verificado.
|
||||
A implementação de ingestão não foi executada contra serviços reais. Smoke test sintético anterior confirmou Ollama `/api/embed` (768D) e busca somente de leitura no Qdrant; nenhuma ingestão foi feita. Apply pode concluir parcialmente se houver falha de rede; a repetição replaneja pelo estado lido e reenvia chunks que faltam. Não execute ingestão real, reset ou consultas operacionais como teste genérico. Permanecem pendentes: validação dos parsers com documentos representativos autorizados, contrato HTTP completo da API, runtime ativo e agendamento cron/systemd. A porta 8090 do serviço de preview em `192.168.0.103` recusou conexão a partir do sandbox; a API em `192.168.0.153:8090` não respondeu. Não instalar dependências para forçar teste de integração neste ambiente.
|
||||
|
||||
Ver [reconciliação de conformidade](../status/conformity-review.md) e [roadmap](../status/roadmap.md).
|
||||
|
|
|
|||
|
|
@ -12,8 +12,8 @@ A coluna “snapshot → atual” separa o estado escrito na matriz (baseado na
|
|||
| C01 — Fonte oficial `/mnt/media/ATIVA_IA/knowledge` | Implementado → **Confirmado no código; runtime não verificado** | `bin/atvctl:12`; `scripts/backup.sh:32`. O caminho está fixo, não vem de configuração central. | Centralizar a origem e aceitar o caminho por configuração. Teste local prova que todos os comandos usam a fonte configurada; host/caminho vivo só em tarefa autorizada. | P1; config central (C24). |
|
||||
| C02 — Qdrant, `ativa_knowledge`, `nomic-embed-text`, 768D | Implementado no snapshot, aceitação parcial → **Parcial; conectividade/schema e busca smoke confirmados** | GET da coleção em 23/10 retornou `green`, 129 pontos e vetor 768D/Cosine; embedding sintético `nomic-embed-text` e busca Qdrant read-only retornaram HTTP 200. API HTTP continua indisponível. | Não comprova ingestão, conteúdo correto, compatibilidade de todos os pontos ou disponibilidade contínua. Aceite funcional: validar consulta pelo RAG API e fontes com dados sintéticos/autorizados, sem expor payload. | P1; resolver API e manter teste local. |
|
||||
| C03 — Domínios por metadados | Parcial → **Parcial** | `discover_documents()` em `bin/atvctl_ingest.py` define setor pela primeira pasta ou `00_GLOBAL`. | Não há validação da lista/domínios permitidos. Aceite: catálogo versionado e fixtures para raiz, pastas conhecidas e desconhecidas. | P1; C05. |
|
||||
| C04 — PDF, MD, TXT, DOCX, XLSX, HTML | Ausente para quatro formatos → **Parcial** | `discover_documents()` e `_extract()` em `bin/atvctl_ingest.py` aceitam `.md` e `.pdf`; PDF usa `pdftotext`. | Implementar e testar os seis formatos; extensão inválida deve falhar claramente, sem indexação parcial silenciosa. | P0; usar fixtures/mocks locais do MVP-03, sem depender de serviços. |
|
||||
| C05 — Metadados mínimos dos chunks | Parcial → **Parcial** | `bin/atvctl_ingest.py`: source/path/sector, hash, document_id estável, índice/texto/tamanho/modelo. | Faltam tipo/formato, estado/versão, seção/página quando disponível e timestamp; verificar propagação até a API. | P0; MVP-02. |
|
||||
| C04 — PDF, MD, TXT, DOCX, XLSX, HTML | Ausente para quatro formatos → **Implementado localmente; validação por fixtures offline concluída** | `discover_documents()`/`_extract_segments()` em `bin/atvctl_ingest.py`; PDF usa `pdftotext`, pacote OOXML é lido com biblioteca padrão; 15 testes offline passam, incluindo fixtures sintéticas e PDF simulado. | Validar documentos representativos autorizados e confirmar dependência/runtime do `pdftotext`; testes não consultam serviços reais nem cobrem todos os recursos dos formatos. | P0; implementação MVP-02 feita; validação operacional pendente. |
|
||||
| C05 — Metadados mínimos dos chunks | Parcial → **Implementado localmente; propagação de referência testada** | `bin/atvctl_ingest.py` grava formato, estado, versão/hash, timestamp UTC e seção/página quando disponíveis; `rag-api/source_metadata.py` propaga localização e identidade do chunk. Testes offline validam payload e helper de referência. | Testar contrato real da FastAPI com fixture/mock HTTP e validar respostas com os campos novos; documentos sem localização continuam sem seção/página inventadas. | P0; implementação MVP-02 feita; contrato de API no MVP-03. |
|
||||
| C06 — Ingestão incremental de novos/modificados | Parcial → **Confirmado no módulo e testes mockados; runtime não verificado** | `bin/atvctl_ingest.py` cria plano comparando arquivos/hash/IDs com pontos paginados; `tests/test_atvctl_ingest.py` prova novos, alterados, inalterados e repetição. | Ainda lê e calcula hash/chunks de todos os arquivos; desempenho e comportamento do Qdrant ativo não foram medidos. Aceite operacional: dry-run e apply autorizados em ambiente isolado sem reenvio de inalterados. | P0 — MVP-01. |
|
||||
| C07 — Remoção de chunks alterados/removidos | Ausente → **Parcial; alteração/remoção individual implementada e testada** | `bin/atvctl_ingest.py` remove IDs obsoletos após upsert aceito e remove pontos de um arquivo excluído; teste também prova preservação de outro documento. | Diretório inteiro sem documentos falha fechado, portanto a exclusão de todas as fontes em uma única execução não é suportada; não houve teste operacional. Definir override seguro e validar em ambiente isolado. | P0 — MVP-01. |
|
||||
| C08 — Idempotência | Parcial → **Confirmado no módulo e testes mockados; runtime não verificado** | `bin/atvctl_ingest.py` deriva ID do documento do caminho relativo e ID do ponto do documento/índice; suite prova conteúdo idêntico em caminhos diferentes e segunda execução sem novas escritas. IDs legados reconhecidos só pelo padrão do `atvctl`. | Não comprova compatibilidade com outros fluxos que escrevam na mesma coleção nem execução contra a coleção ativa. Aceite operacional separado e autorizado. | P0 — MVP-01. |
|
||||
|
|
|
|||
|
|
@ -20,3 +20,6 @@ Frontend web inicial criado em 23/10/2026 no checkout de desenvolvimento. Nenhum
|
|||
Gate FE-01 permanece aberto. Em 23/10/2026, nova tentativa de `GET http://192.168.0.153:8090/health` expirou após 4 s, mesmo com rede habilitada. O responsável corrigiu o alias SSH para `docker`; a tentativa com esse alias também não foi resolvida neste sandbox. O responsável informou que o preview Apache usa `ProxyPreserveHost On` e encaminha `/` a `http://192.168.0.103:8090/`. Um GET direto a esse upstream recebeu conexão recusada no sandbox; `GET https://app.ativa.rio.br/` expirou após 12 s sem resposta. Esses resultados não atestam indisponibilidade vista do acesso remoto do responsável. Não houve chamadas à API de chat nem alterações em host/serviços.
|
||||
|
||||
Antes de integrar o frontend, fazer diagnóstico somente de leitura no host acessado pelo alias SSH `docker` ou pela console de administração autorizada: estado do container, listener 8090 e `curl` local em `/health`; não ler `.env` nem exibir segredos. Em seguida, validar o caminho de rede autorizado e definir o proxy HTTPS com autenticação de usuário e injeção server-side da chave. Critérios de aceite e controles estão em [frontend MVP](../frontend/mvp.md). Não aplicar mudanças no Apache/ISPConfig nesta fase.
|
||||
|
||||
## Desenvolvimento local — MVP-02
|
||||
Em 23/10/2026, `bin/atvctl_ingest.py` passou a extrair MD, PDF, TXT, DOCX, XLSX e HTML/HTM sem dependências Python adicionais; localização por seção/página é preservada quando o formato fornece essa estrutura. Formatos não suportados agora falham antes de montar plano parcial. Os pontos passam a incluir formato, estado, versão do conteúdo e timestamp UTC. A API inclui esses metadados disponíveis nas referências. `PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -v` passou com 15 testes, todos locais/mockados. Não houve instalação de dependências, ingestão nem chamada a Ollama/Qdrant. Próxima prioridade local: testes de contrato FastAPI offline (auth, health, query/chat, erros e fontes), sem substituir o gate operacional do preview.
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
Backlog reconciliado em 23/10/2026 com a matriz versionada em [reference](../reference/ATIVA_IA_Matriz_Conformidade_v0.2.0_2026-10-20.md), a revisão [C01–C28](conformity-review.md) e o estado atual do código. Smoke tests somente de leitura de Ollama/Qdrant estão registrados em [integrações](../integrations/overview.md); nenhum serviço foi alterado.
|
||||
|
||||
1. **MVP-01 — núcleo da ingestão incremental (P0, implementação local feita; operação pendente):** C06–C09, C15. IDs determinísticos por caminho, planejamento de novos/alterados/inalterados/removidos, dry-run sem escrita, upsert antes da remoção, limpeza de chunks obsoletos e proteção de pontos alheios estão cobertos por testes mockados. Limite conhecido: diretório sem documentos falha fechado. Próximo complemento: documentar/validar execução manual e propor agendamento; não configurar produção nesta etapa.
|
||||
2. **MVP-02 — formatos, metadados e fontes (P0):** C03–C05, C14. Fixtures para seis formatos, classificação setorial validada e campos de origem/tipo/seção/página quando disponíveis preservados até a resposta da API.
|
||||
2. **MVP-02 — formatos, metadados e fontes (P0):** C03–C05, C14. Implementação local concluída para MD/PDF/TXT/DOCX/XLSX/HTML (HTM aceito como extensão HTML), com metadados de tipo/estado/versão/timestamp e localização quando disponível; referências da API propagam tipo/seção/página/ID do chunk. 15 testes offline passam. Pendente: validar contrato completo da FastAPI e parsers com amostras representativas autorizadas; não houve ingestão real.
|
||||
3. **MVP-03 — testes da API e avaliação do RAG (P0):** C10–C13, C21–C23. Ampliar a suíte offline para contratos, auth, erros, streaming e rastreabilidade; dataset pequeno com fontes esperadas, gabarito, abstenção e métricas. Teste Open WebUI só em tarefa operacional autorizada.
|
||||
4. **MVP-04 — configuração e segurança operacional (P0):** C11, C16–C18, C20, C24, C27. Não executar `scripts/backup.sh` antes de corrigir destino dentro do checkout, filtragem de segredos e permissões; centralizar configuração e fixar dependências.
|
||||
5. **MVP-05 — backup, restore e rollback (P0):** C18–C19, C26. Ensaiar restore em ambiente isolado com dados sintéticos e documentar retorno.
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ WORKDIR /app
|
|||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY app.py .
|
||||
COPY app.py source_metadata.py ./
|
||||
|
||||
RUN useradd --system --uid 10001 ativa-rag && \
|
||||
chown -R 10001:10001 /app
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ from fastapi import FastAPI, Header, HTTPException
|
|||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from source_metadata import source_reference
|
||||
|
||||
|
||||
QDRANT_URL = os.getenv("QDRANT_URL", "http://192.168.0.153:6333").rstrip("/")
|
||||
OLLAMA_URL = os.getenv("OLLAMA_URL", "http://192.168.0.106:11434").rstrip("/")
|
||||
|
|
@ -129,12 +131,7 @@ def build_context(results: list[dict[str, Any]]) -> tuple[str, list[dict[str, An
|
|||
context_parts.append(block)
|
||||
used_chars += len(block)
|
||||
|
||||
sources.append(
|
||||
{
|
||||
"source": source,
|
||||
"score": round(float(item.get("score", 0.0)), 6),
|
||||
}
|
||||
)
|
||||
sources.append(source_reference(payload, item.get("score", 0.0)))
|
||||
|
||||
return "\n---\n".join(context_parts), sources
|
||||
|
||||
|
|
|
|||
21
rag-api/source_metadata.py
Normal file
21
rag-api/source_metadata.py
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
"""Helpers to expose Qdrant source metadata without inventing citations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
SOURCE_FIELDS = ("file_type", "section", "page", "document_id", "chunk_index")
|
||||
|
||||
|
||||
def source_reference(payload: dict[str, Any], score: Any) -> dict[str, Any]:
|
||||
source = payload.get("source") or payload.get("path") or "fonte_desconhecida"
|
||||
reference: dict[str, Any] = {
|
||||
"source": source,
|
||||
"score": round(float(score or 0.0), 6),
|
||||
}
|
||||
for field in SOURCE_FIELDS:
|
||||
value = payload.get(field)
|
||||
if value is not None:
|
||||
reference[field] = value
|
||||
return reference
|
||||
|
|
@ -1,8 +1,10 @@
|
|||
import hashlib
|
||||
import zipfile
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO_ROOT / "bin"))
|
||||
|
|
@ -187,6 +189,97 @@ class IngestTests(unittest.TestCase):
|
|||
self.assertEqual(self.session.upsert_calls, [])
|
||||
self.assertEqual(self.session.delete_calls, [])
|
||||
|
||||
def test_supported_plain_and_html_formats_preserve_sections(self):
|
||||
(self.root / "nota.txt").write_text("Texto simples", encoding="utf-8")
|
||||
(self.root / "pagina.html").write_text(
|
||||
"<html><body><h1>Atendimento</h1><p>Horário da recepção.</p>"
|
||||
"<script>segredo que não deve ser indexado</script></body></html>",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
documents = ingest.discover_documents(self.root)
|
||||
|
||||
self.assertEqual([document.relative for document in documents], ["nota.txt", "pagina.html"])
|
||||
html_doc = documents[1]
|
||||
self.assertIn("Horário da recepção", html_doc.chunks[0])
|
||||
self.assertNotIn("segredo", " ".join(html_doc.chunks))
|
||||
self.assertEqual(html_doc.chunk_metadata[0]["section"], "Atendimento")
|
||||
|
||||
def test_docx_and_xlsx_extract_text_and_section_metadata(self):
|
||||
docx = self.root / "manual.docx"
|
||||
with zipfile.ZipFile(docx, "w") as archive:
|
||||
archive.writestr(
|
||||
"word/document.xml",
|
||||
"""<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
|
||||
<w:body><w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr>
|
||||
<w:r><w:t>Cadastro</w:t></w:r></w:p><w:p><w:r><w:t>Dados necessários</w:t></w:r></w:p>
|
||||
</w:body></w:document>""",
|
||||
)
|
||||
xlsx = self.root / "dados.xlsx"
|
||||
with zipfile.ZipFile(xlsx, "w") as archive:
|
||||
archive.writestr(
|
||||
"xl/workbook.xml",
|
||||
"""<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
|
||||
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
|
||||
<sheets><sheet name="Unidades" sheetId="1" r:id="rId1"/></sheets></workbook>""",
|
||||
)
|
||||
archive.writestr(
|
||||
"xl/_rels/workbook.xml.rels",
|
||||
"""<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Id="rId1" Target="worksheets/sheet1.xml"/></Relationships>""",
|
||||
)
|
||||
archive.writestr(
|
||||
"xl/worksheets/sheet1.xml",
|
||||
"""<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
|
||||
<sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>Unidade A</t></is></c>
|
||||
<c r="B1" t="inlineStr"><is><t>Centro</t></is></c></row></sheetData></worksheet>""",
|
||||
)
|
||||
|
||||
documents = ingest.discover_documents(self.root)
|
||||
by_name = {document.relative: document for document in documents}
|
||||
|
||||
self.assertIn("Dados necessários", " ".join(by_name["manual.docx"].chunks))
|
||||
self.assertEqual(by_name["manual.docx"].chunk_metadata[0]["section"], "Cadastro")
|
||||
self.assertIn("Unidade A | Centro", " ".join(by_name["dados.xlsx"].chunks))
|
||||
self.assertEqual(by_name["dados.xlsx"].chunk_metadata[0]["section"], "Unidades")
|
||||
|
||||
@patch.object(ingest.subprocess, "run")
|
||||
def test_pdf_pages_are_preserved_as_chunk_metadata(self, run):
|
||||
run.return_value.stdout = "Página um\fPágina dois\f"
|
||||
run.return_value.check_returncode = lambda: None
|
||||
(self.root / "manual.pdf").write_bytes(b"%PDF-mock")
|
||||
|
||||
document = ingest.discover_documents(self.root)[0]
|
||||
|
||||
self.assertEqual(document.chunks, ("Página um", "Página dois"))
|
||||
self.assertEqual([item["page"] for item in document.chunk_metadata], [1, 2])
|
||||
|
||||
def test_unsupported_only_root_fails_closed(self):
|
||||
(self.root / "imagem.png").write_bytes(b"not indexed")
|
||||
with self.assertRaisesRegex(ingest.IngestError, "Formatos não suportados"):
|
||||
ingest.discover_documents(self.root)
|
||||
|
||||
def test_mixed_supported_and_unsupported_files_fail_before_partial_plan(self):
|
||||
(self.root / "documento.md").write_text("conteúdo válido", encoding="utf-8")
|
||||
(self.root / "imagem.png").write_bytes(b"not indexed")
|
||||
|
||||
with self.assertRaisesRegex(ingest.IngestError, "imagem.png"):
|
||||
self.run_sync("dry-run")
|
||||
|
||||
self.assertEqual(self.session.upsert_calls, [])
|
||||
self.assertEqual(self.session.delete_calls, [])
|
||||
|
||||
def test_file_type_version_and_status_are_written_to_qdrant_payload(self):
|
||||
(self.root / "nota.txt").write_text("Texto indexável", encoding="utf-8")
|
||||
|
||||
self.run_sync("apply")
|
||||
|
||||
payload = next(iter(self.session.points.values()))["payload"]
|
||||
self.assertEqual(payload["file_type"], "txt")
|
||||
self.assertEqual(payload["document_version"], payload["document_hash"][:16])
|
||||
self.assertEqual(payload["document_status"], "active")
|
||||
self.assertRegex(payload["indexed_at"], r"^\d{4}-\d\d-\d\dT.*\+00:00$")
|
||||
|
||||
def test_unowned_points_are_preserved(self):
|
||||
(self.root / "a.md").write_text("conteúdo novo", encoding="utf-8")
|
||||
self.session.points["foreign-id"] = {
|
||||
|
|
|
|||
43
tests/test_rag_source_metadata.py
Normal file
43
tests/test_rag_source_metadata.py
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO_ROOT / "rag-api"))
|
||||
|
||||
from source_metadata import source_reference
|
||||
|
||||
|
||||
class SourceMetadataTests(unittest.TestCase):
|
||||
def test_reference_preserves_available_location_metadata(self):
|
||||
reference = source_reference(
|
||||
{
|
||||
"source": "manual.pdf",
|
||||
"file_type": "pdf",
|
||||
"page": 3,
|
||||
"section": "Cadastro",
|
||||
"document_id": "doc-1",
|
||||
"chunk_index": 2,
|
||||
},
|
||||
0.87654321,
|
||||
)
|
||||
|
||||
self.assertEqual(reference, {
|
||||
"source": "manual.pdf",
|
||||
"score": 0.876543,
|
||||
"file_type": "pdf",
|
||||
"section": "Cadastro",
|
||||
"page": 3,
|
||||
"document_id": "doc-1",
|
||||
"chunk_index": 2,
|
||||
})
|
||||
|
||||
def test_missing_metadata_is_not_fabricated(self):
|
||||
self.assertEqual(
|
||||
source_reference({"path": "readme.md"}, None),
|
||||
{"source": "readme.md", "score": 0.0},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Add table
Add a link
Reference in a new issue