Files
Atrium/backend/app/services/attachments.py
T
tobayahandClaude Opus 5.5 bf46fb5724 Czat: załączniki (PDF, DOCX, TXT/MD/CSV) jako źródła pytania
POST /chat/attachments zwraca tekst pliku i niczego nie zapisuje (audyt: nazwa i rozmiar,
bez treści). PDF przez pypdf (BSD-3), DOCX biblioteką standardową z odmową DTD, tekst
UTF-8 albo cp1250. Konsola: spinacz i upuszczenie pliku na stronie głównej, etykiety
plików, każdy plik jako ponumerowane źródło (przypis [n], sprawdzanie cytatów). Tekst
przycinany do pamięci modelu (context_window z listy modeli) z uczciwym „do strony X z Y”.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqL6AphKDyHPDToUMin
2026-11-18 15:07:19 +01:00

118 lines
5.2 KiB
Python

"""A file attached to a Home chat question: its text, and nothing kept.
The bytes arrive, the text goes back, and neither is stored: the console holds the text for the
conversation and sends it to the model as one more source, the way it sends a contract or a matter.
So the privacy of an attachment is the privacy of the question itself (the provider's policy decides
where it may go), and there is no file anywhere to delete afterwards.
PDF through pypdf (BSD-3, pure Python), DOCX through the standard library (it is a ZIP of XML),
plain text decoded as UTF-8 and, failing that, as Windows-1250, which is what Polish text files
from older Office installations are. Every page of a PDF is marked `[strona N]` so the model can say
where it read something.
"""
from __future__ import annotations
import io
import zipfile
from xml.etree import ElementTree
from ..errors import ValidationError
MAX_BYTES = 10 * 1024 * 1024
MAX_PAGES = 300
MAX_CHARS = 400_000 # more than any model here reads; the console trims to the model's budget
_MAX_XML = 50 * 1024 * 1024 # word/document.xml unpacked: a ZIP bomb stops here, not in memory
TEXT_TYPES = (".txt", ".md", ".csv")
_W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
def _refuse(code: str, pl: str, en: str) -> ValidationError:
return ValidationError(pl, {"code": code, "en": en})
def _pdf(data: bytes) -> tuple[str, int]:
from pypdf import PdfReader
from pypdf.errors import PdfReadError
try:
reader = PdfReader(io.BytesIO(data))
if reader.is_encrypted and not reader.decrypt(""):
raise _refuse("attachment_encrypted", "Plik PDF jest zabezpieczony hasłem.",
"The PDF is password-protected.")
pages = reader.pages
if len(pages) > MAX_PAGES:
raise _refuse("attachment_too_long", f"Plik ma więcej niż {MAX_PAGES} stron.",
f"The file has more than {MAX_PAGES} pages.")
parts, total = [], 0
for n, page in enumerate(pages, 1):
text = (page.extract_text() or "").strip()
parts.append(f"[strona {n}]\n{text}")
total += len(text)
if total > MAX_CHARS:
break
except PdfReadError as exc:
raise _refuse("attachment_unreadable", "Nie da się odczytać tego pliku PDF.",
"This PDF cannot be read.") from exc
if not total:
raise _refuse("attachment_no_text",
"Ten PDF nie ma warstwy tekstu (to skan). Potrzebne jest rozpoznanie tekstu (OCR).",
"This PDF has no text layer (a scan). It needs OCR.")
return "\n\n".join(parts), len(pages)
def _docx(data: bytes) -> str:
try:
with zipfile.ZipFile(io.BytesIO(data)) as z:
info = z.getinfo("word/document.xml")
if info.file_size > _MAX_XML:
raise _refuse("attachment_too_long", "Dokument jest za duży.", "The document is too large.")
xml = z.read(info)
# Word never writes a DTD; without one there are no entities to expand (XXE, billion laughs).
if b"<!DOCTYPE" in xml or b"<!ENTITY" in xml:
raise _refuse("attachment_unreadable", "Nie da się odczytać tego pliku DOCX.",
"This DOCX cannot be read.")
root = ElementTree.fromstring(xml)
except (zipfile.BadZipFile, KeyError, ElementTree.ParseError) as exc:
raise _refuse("attachment_unreadable", "Nie da się odczytać tego pliku DOCX.",
"This DOCX cannot be read.") from exc
lines = []
for p in root.iter(f"{_W}p"):
bits = []
for el in p.iter():
if el.tag == f"{_W}t":
bits.append(el.text or "")
elif el.tag == f"{_W}tab":
bits.append("\t")
elif el.tag in (f"{_W}br", f"{_W}cr"):
bits.append("\n")
lines.append("".join(bits))
return "\n".join(lines).strip()
def _plain(data: bytes) -> str:
try:
return data.decode("utf-8-sig")
except UnicodeDecodeError:
return data.decode("cp1250", errors="replace")
def extract(name: str, data: bytes) -> dict:
"""`{name, kind, pages, chars, text}` of one attached file, or a 422 saying why not."""
if len(data) > MAX_BYTES:
raise _refuse("attachment_too_large", "Plik jest większy niż 10 MB.", "The file is larger than 10 MB.")
lower = name.lower()
pages = None
if lower.endswith(".pdf") and data.startswith(b"%PDF"):
kind = "pdf"
text, pages = _pdf(data)
elif lower.endswith(".docx") and data.startswith(b"PK"):
kind, text = "docx", _docx(data)
elif lower.endswith(TEXT_TYPES) and b"\x00" not in data[:4096]:
kind, text = "text", _plain(data)
else:
raise _refuse("attachment_type", "Ten rodzaj pliku nie jest obsługiwany. Dołącz PDF, DOCX, TXT, MD albo CSV.",
"This kind of file is not supported. Attach a PDF, DOCX, TXT, MD or CSV.")
text = text.strip()
if not text:
raise _refuse("attachment_empty", "W pliku nie ma tekstu.", "The file has no text.")
return {"name": name, "kind": kind, "pages": pages, "chars": len(text), "text": text[:MAX_CHARS]}