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)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue