Production SMB->Onyx sync sidecar (public ingestion + admin APIs only; no Onyx source changes; upgrade-safe). Verified end-to-end against a live Onyx v4.5.2. Core (app/sync.py): per-cycle reconcile — upsert new/changed (stable url-safe document ids so updates replace in place), delete files removed from the share, plus manifest-independent reconcile against Onyx's own doc list. Content-hash change detection; per-source + per-file failure isolation. Self-provisioning (app/onyx_client.py): create/cache API key (admin bootstrap) and one connector/cc_pair per source via connector-with-mock-credential; idempotent reuse via the grouped indexing-status lookup. Multi-source (app/config.py): JSON SMB_SOURCES or indexed SMB_SOURCE_N_*; logical path mapping (mount -> \\company\share) shown in citations. Extraction (app/extract.py): pdf/docx/xlsx/csv/txt/md/html, light deps. State manifest (atomic), entrypoint loop w/ graceful shutdown + retry/backoff. Dockerfile, compose snippet, .env.example, README. Bugs caught + fixed during live E2E (missed by code review + stub tests): - Onyx URL-encodes document ids -> switched to url-safe ids + store Onyx's returned canonical id, so delete/reconcile match. - connector listing endpoint + provision-response parsing corrected (indexing-status is grouped by source; StatusResponse.data = cc_pair_id). - Documented: auto API-key creation needs LICENSE_ENFORCEMENT_ENABLED=false (the /admin/api-key endpoint is EE-tier-gated); ingestion + connector creation are not. E2E results (live Onyx): ingest 2 docs w/ logical paths; change->update-in-place with stable ids; remove->delete synced; auto-provision create + idempotent reuse; multi- source config both styles.
99 lines
2.7 KiB
Python
99 lines
2.7 KiB
Python
"""Text extraction for the file types typically found on an SMB share.
|
|
|
|
Kept intentionally small and dependency-light (this is the "basic extraction"
|
|
scope of Phase 1). Unsupported/binary files return an empty string and are
|
|
skipped by the sync engine rather than ingested as noise.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import csv
|
|
import io
|
|
import logging
|
|
import os
|
|
|
|
logger = logging.getLogger("smb.extract")
|
|
|
|
|
|
def _txt(data: bytes) -> str:
|
|
for enc in ("utf-8", "utf-16", "latin-1"):
|
|
try:
|
|
return data.decode(enc)
|
|
except UnicodeDecodeError:
|
|
continue
|
|
return data.decode("utf-8", errors="replace")
|
|
|
|
|
|
def _pdf(data: bytes) -> str:
|
|
from pypdf import PdfReader # lazy import so a missing dep only breaks one type
|
|
|
|
reader = PdfReader(io.BytesIO(data))
|
|
return "\n\n".join((page.extract_text() or "") for page in reader.pages)
|
|
|
|
|
|
def _docx(data: bytes) -> str:
|
|
import docx # python-docx
|
|
|
|
document = docx.Document(io.BytesIO(data))
|
|
parts = [p.text for p in document.paragraphs]
|
|
for table in document.tables:
|
|
for row in table.rows:
|
|
parts.append("\t".join(cell.text for cell in row.cells))
|
|
return "\n".join(parts)
|
|
|
|
|
|
def _xlsx(data: bytes) -> str:
|
|
from openpyxl import load_workbook
|
|
|
|
wb = load_workbook(io.BytesIO(data), read_only=True, data_only=True)
|
|
out: list[str] = []
|
|
for ws in wb.worksheets:
|
|
out.append(f"# {ws.title}")
|
|
for row in ws.iter_rows(values_only=True):
|
|
out.append("\t".join("" if c is None else str(c) for c in row))
|
|
return "\n".join(out)
|
|
|
|
|
|
def _csv(data: bytes) -> str:
|
|
text = _txt(data)
|
|
rows = csv.reader(io.StringIO(text))
|
|
return "\n".join("\t".join(r) for r in rows)
|
|
|
|
|
|
def _html(data: bytes) -> str:
|
|
import re
|
|
|
|
text = _txt(data)
|
|
text = re.sub(r"(?is)<(script|style).*?</\1>", " ", text)
|
|
text = re.sub(r"(?s)<[^>]+>", " ", text)
|
|
return re.sub(r"\s+\n", "\n", text).strip()
|
|
|
|
|
|
_HANDLERS = {
|
|
"pdf": _pdf,
|
|
"docx": _docx,
|
|
"txt": _txt,
|
|
"md": _txt,
|
|
"csv": _csv,
|
|
"xlsx": _xlsx,
|
|
"html": _html,
|
|
"htm": _html,
|
|
}
|
|
|
|
|
|
def supported_extensions() -> set[str]:
|
|
return set(_HANDLERS)
|
|
|
|
|
|
def extract_text(path: str, data: bytes) -> str:
|
|
ext = os.path.splitext(path)[1].lower().lstrip(".")
|
|
handler = _HANDLERS.get(ext)
|
|
if handler is None:
|
|
# .doc/.xls (legacy binary) and others aren't handled by the light deps.
|
|
logger.debug("No extractor for .%s (%s) — skipping", ext, path)
|
|
return ""
|
|
try:
|
|
return (handler(data) or "").strip()
|
|
except Exception as exc: # never let one bad file stop the whole sync
|
|
logger.warning("Extraction failed for %s: %s", path, exc)
|
|
return ""
|