push
This commit is contained in:
438
dn_ai/utils/ai_attachment_tools.py
Normal file
438
dn_ai/utils/ai_attachment_tools.py
Normal file
@@ -0,0 +1,438 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Turn uploaded files into content parts the model can actually read.
|
||||
|
||||
Deliberately free of any ``odoo`` import, like ``openai_client``: everything
|
||||
here operates on ``bytes`` plus a mimetype/name, which makes the extraction
|
||||
logic unit-testable without a database.
|
||||
|
||||
The output is always a list of *message parts*:
|
||||
|
||||
* ``{'type': 'text', 'text': ...}`` — decoded text, or a human-readable note
|
||||
explaining why the file could not be read;
|
||||
* ``{'type': 'inline_data', 'mimetype': ..., 'data': <base64>}`` — binary the
|
||||
provider can consume natively (images, PDF). Whether it is truly sent as
|
||||
multimodal content or flattened to a caption is decided later, in
|
||||
``openai_client.to_provider_messages``.
|
||||
|
||||
Office documents are parsed with the standard library only (``zipfile`` +
|
||||
``ElementTree``) instead of pulling ``python-docx``/``openpyxl`` in: OOXML and
|
||||
ODF are zip archives of XML, and the assistant only needs the running text,
|
||||
not styling.
|
||||
|
||||
PDF text extraction uses PyMuPDF when it is installed. It is optional: without
|
||||
it the file still travels as ``inline_data`` for providers that accept PDFs
|
||||
natively, and only the file name reaches text-only models.
|
||||
"""
|
||||
import base64
|
||||
import csv
|
||||
import io
|
||||
import logging
|
||||
import re
|
||||
import zipfile
|
||||
from xml.etree import ElementTree
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# Formats the model can *see*. The list mirrors what OpenAI-compatible
|
||||
# multimodal endpoints accept.
|
||||
IMAGE_EXTENSIONS = {'png', 'jpg', 'jpeg', 'webp', 'gif'}
|
||||
|
||||
# Hard caps so a stray 50 MB log file cannot blow up the request payload.
|
||||
MAX_INLINE_BYTES = 10 * 1024 * 1024 # 10 MiB sent as base64
|
||||
MAX_TEXT_CHARS = 40000 # per file, after extraction
|
||||
MAX_CSV_ROWS = 200 # spreadsheets are sampled, not dumped
|
||||
|
||||
TEXT_ENCODINGS = ('utf-8-sig', 'utf-8', 'gb18030', 'big5', 'cp1252', 'latin-1')
|
||||
|
||||
_NS = {
|
||||
'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main',
|
||||
'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
|
||||
'x': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
|
||||
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
|
||||
'table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
|
||||
}
|
||||
|
||||
|
||||
def split_extension(name):
|
||||
"""Lower-case extension of ``name`` without the dot (``''`` when absent)."""
|
||||
name = (name or '').strip()
|
||||
if '.' not in name:
|
||||
return ''
|
||||
return name.rsplit('.', 1)[-1].lower()
|
||||
|
||||
|
||||
def guess_kind(mimetype, name):
|
||||
"""Classify a file into one of the extraction strategies.
|
||||
|
||||
``mimetype`` is often wrong or missing (browsers report
|
||||
``application/octet-stream`` for drag-and-dropped files), so the extension
|
||||
is authoritative whenever the mimetype is not conclusive.
|
||||
"""
|
||||
mimetype = (mimetype or '').lower()
|
||||
extension = split_extension(name)
|
||||
|
||||
if mimetype.startswith('image/') or extension in IMAGE_EXTENSIONS:
|
||||
return 'image'
|
||||
if mimetype == 'application/pdf' or extension == 'pdf':
|
||||
return 'pdf'
|
||||
if extension in ('docx', 'doc', 'odt', 'rtf'):
|
||||
return 'word'
|
||||
if extension in ('xlsx', 'xls', 'ods', 'csv'):
|
||||
return 'sheet'
|
||||
if extension in ('pptx', 'ppt', 'odp'):
|
||||
return 'slide'
|
||||
if mimetype.startswith('text/') or extension in (
|
||||
'txt', 'md', 'markdown', 'json', 'xml', 'html', 'htm', 'py', 'js',
|
||||
'ts', 'css', 'scss', 'yml', 'yaml', 'ini', 'cfg', 'log', 'sql', 'sh',
|
||||
):
|
||||
return 'text'
|
||||
return 'unsupported'
|
||||
|
||||
|
||||
def decode_text(data):
|
||||
"""Decode ``bytes`` trying the encodings this shop actually meets.
|
||||
|
||||
Chinese Excel exports are ``gb18030`` far more often than UTF-8, and a
|
||||
plain ``utf-8`` decode would fail on them.
|
||||
"""
|
||||
if not data:
|
||||
return ''
|
||||
for encoding in TEXT_ENCODINGS:
|
||||
try:
|
||||
return data.decode(encoding)
|
||||
except (UnicodeDecodeError, LookupError):
|
||||
continue
|
||||
return data.decode('utf-8', errors='replace')
|
||||
|
||||
|
||||
def _truncate(text, limit=MAX_TEXT_CHARS):
|
||||
text = (text or '').strip()
|
||||
if len(text) <= limit:
|
||||
return text, False
|
||||
return text[:limit], True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# archive based formats (OOXML / ODF)
|
||||
# ---------------------------------------------------------------------------
|
||||
def _open_archive(data):
|
||||
try:
|
||||
return zipfile.ZipFile(io.BytesIO(data))
|
||||
except (zipfile.BadZipFile, OSError):
|
||||
return None
|
||||
|
||||
|
||||
def _xml_root(archive, member):
|
||||
try:
|
||||
with archive.open(member) as handle:
|
||||
return ElementTree.fromstring(handle.read())
|
||||
except (KeyError, ElementTree.ParseError):
|
||||
return None
|
||||
|
||||
|
||||
def _words_of(element, tag):
|
||||
"""Join the text of every ``tag`` descendant, keeping word boundaries.
|
||||
|
||||
Space matters: Word splits a sentence across many ``w:t`` runs, so joining
|
||||
them without a separator turns "Total amount" into "Totalamount".
|
||||
"""
|
||||
chunks = []
|
||||
for node in element.iter(tag):
|
||||
if node.text:
|
||||
chunks.append(node.text)
|
||||
return ''.join(chunks)
|
||||
|
||||
|
||||
def extract_docx(data):
|
||||
archive = _open_archive(data)
|
||||
if not archive:
|
||||
return None
|
||||
root = _xml_root(archive, 'word/document.xml')
|
||||
if root is None:
|
||||
return None
|
||||
paragraphs = []
|
||||
for paragraph in root.iter(f"{{{_NS['w']}}}p"):
|
||||
text = _words_of(paragraph, f"{{{_NS['w']}}}t")
|
||||
if text.strip():
|
||||
paragraphs.append(text.strip())
|
||||
return '\n'.join(paragraphs)
|
||||
|
||||
|
||||
def extract_pptx(data):
|
||||
archive = _open_archive(data)
|
||||
if not archive:
|
||||
return None
|
||||
slide_names = sorted(
|
||||
(name for name in archive.namelist()
|
||||
if re.fullmatch(r'ppt/slides/slide\d+\.xml', name)),
|
||||
key=lambda name: int(re.search(r'(\d+)', name.rsplit('/', 1)[-1]).group(1)),
|
||||
)
|
||||
slides = []
|
||||
for index, member in enumerate(slide_names, start=1):
|
||||
root = _xml_root(archive, member)
|
||||
if root is None:
|
||||
continue
|
||||
paragraphs = [
|
||||
_words_of(paragraph, f"{{{_NS['a']}}}t").strip()
|
||||
for paragraph in root.iter(f"{{{_NS['a']}}}p")
|
||||
]
|
||||
paragraphs = [text for text in paragraphs if text]
|
||||
if paragraphs:
|
||||
slides.append(f"[Slide {index}]\n" + '\n'.join(paragraphs))
|
||||
return '\n\n'.join(slides)
|
||||
|
||||
|
||||
def extract_xlsx(data):
|
||||
"""Rebuild a readable grid from a workbook, one block per sheet.
|
||||
|
||||
Shared strings are resolved manually because ``openpyxl`` is not a
|
||||
dependency of Odoo; cells carrying a literal ``<is>`` value are handled
|
||||
too, since not every generator uses the shared table.
|
||||
"""
|
||||
archive = _open_archive(data)
|
||||
if not archive:
|
||||
return None
|
||||
|
||||
shared = []
|
||||
shared_root = _xml_root(archive, 'xl/sharedStrings.xml')
|
||||
if shared_root is not None:
|
||||
for item in shared_root.iter(f"{{{_NS['x']}}}si"):
|
||||
shared.append(_words_of(item, f"{{{_NS['x']}}}t"))
|
||||
|
||||
# Sheet order/names live in workbook.xml; the relationship file maps them
|
||||
# to worksheet parts, in the same order.
|
||||
sheet_names = []
|
||||
workbook = _xml_root(archive, 'xl/workbook.xml')
|
||||
if workbook is not None:
|
||||
sheet_names = [
|
||||
node.get('name') or ''
|
||||
for node in workbook.iter(f"{{{_NS['x']}}}sheet")
|
||||
]
|
||||
|
||||
sheets = sorted(
|
||||
(name for name in archive.namelist()
|
||||
if re.fullmatch(r'xl/worksheets/sheet\d+\.xml', name)),
|
||||
key=lambda name: int(re.search(r'(\d+)', name.rsplit('/', 1)[-1]).group(1)),
|
||||
)
|
||||
|
||||
blocks = []
|
||||
for index, member in enumerate(sheets):
|
||||
root = _xml_root(archive, member)
|
||||
if root is None:
|
||||
continue
|
||||
rows = []
|
||||
for row in root.iter(f"{{{_NS['x']}}}row"):
|
||||
values = []
|
||||
for cell in row.iter(f"{{{_NS['x']}}}c"):
|
||||
kind = cell.get('t')
|
||||
if kind == 'inlineStr':
|
||||
values.append(_words_of(cell, f"{{{_NS['x']}}}t"))
|
||||
else:
|
||||
raw = cell.find(f"{{{_NS['x']}}}v")
|
||||
text = raw.text if raw is not None and raw.text else ''
|
||||
if kind == 's' and text.isdigit():
|
||||
position = int(text)
|
||||
text = shared[position] if position < len(shared) else ''
|
||||
values.append(text)
|
||||
while values and not values[-1]:
|
||||
values.pop()
|
||||
if any(value.strip() for value in values if value):
|
||||
rows.append('\t'.join(values))
|
||||
if len(rows) >= MAX_CSV_ROWS:
|
||||
rows.append('… (truncated)')
|
||||
break
|
||||
if rows:
|
||||
title = sheet_names[index] if index < len(sheet_names) else f'Sheet{index + 1}'
|
||||
blocks.append(f'[{title}]\n' + '\n'.join(rows))
|
||||
return '\n\n'.join(blocks)
|
||||
|
||||
|
||||
def extract_odf(data):
|
||||
"""OpenDocument text/spreadsheet/presentation all keep text in content.xml."""
|
||||
archive = _open_archive(data)
|
||||
if not archive:
|
||||
return None
|
||||
root = _xml_root(archive, 'content.xml')
|
||||
if root is None:
|
||||
return None
|
||||
lines = []
|
||||
for paragraph in root.iter(f"{{{_NS['text']}}}p"):
|
||||
text = ''.join(paragraph.itertext()).strip()
|
||||
if text:
|
||||
lines.append(text)
|
||||
for row in root.iter(f"{{{_NS['table']}}}table-row"):
|
||||
cells = [
|
||||
''.join(cell.itertext()).strip()
|
||||
for cell in row.iter(f"{{{_NS['table']}}}table-cell")
|
||||
]
|
||||
cells = [cell for cell in cells if cell]
|
||||
if cells:
|
||||
lines.append('\t'.join(cells))
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def extract_office_text(data, kind):
|
||||
"""Dispatch to the right archive parser; ``None`` when nothing was found."""
|
||||
if kind == 'word':
|
||||
# Legacy binary .doc is not a zip; `.odt` is.
|
||||
text = extract_docx(data)
|
||||
if text is None:
|
||||
text = extract_odf(data)
|
||||
return text
|
||||
if kind == 'slide':
|
||||
text = extract_pptx(data)
|
||||
if text is None:
|
||||
text = extract_odf(data)
|
||||
return text
|
||||
if kind == 'sheet':
|
||||
text = extract_xlsx(data)
|
||||
if text is None:
|
||||
text = extract_odf(data)
|
||||
return text
|
||||
return None
|
||||
|
||||
|
||||
def extract_csv_text(data):
|
||||
"""Render a CSV file as an aligned tab-separated sample."""
|
||||
text = decode_text(data)
|
||||
try:
|
||||
dialect = csv.Sniffer().sniff(text[:4096])
|
||||
delimiter = dialect.delimiter
|
||||
except csv.Error:
|
||||
delimiter = ','
|
||||
rows = []
|
||||
for index, row in enumerate(csv.reader(io.StringIO(text), delimiter=delimiter)):
|
||||
if index >= MAX_CSV_ROWS:
|
||||
rows.append('… (truncated)')
|
||||
break
|
||||
rows.append('\t'.join(cell.strip() for cell in row))
|
||||
return '\n'.join(rows)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# public entry point
|
||||
# ---------------------------------------------------------------------------
|
||||
def extract_pdf_text(data):
|
||||
"""Extract text (including table cell order) from a PDF via PyMuPDF.
|
||||
|
||||
Returns an empty string when PyMuPDF is absent or the PDF cannot be read;
|
||||
callers then fall back to sending the binary as-is. ``sort=True`` keeps
|
||||
text in reading order so tables stay aligned row by row.
|
||||
"""
|
||||
try:
|
||||
import pymupdf
|
||||
except ImportError:
|
||||
_logger.warning("PyMuPDF is not installed; PDF text extraction skipped.")
|
||||
return ''
|
||||
try:
|
||||
document = pymupdf.open(stream=data, filetype='pdf')
|
||||
except Exception as exc: # noqa: BLE001 - pymupdf raises several types
|
||||
_logger.warning("Could not open PDF for text extraction: %s", exc)
|
||||
return ''
|
||||
chunks = []
|
||||
try:
|
||||
for page in document:
|
||||
chunk = page.get_text('text', sort=True)
|
||||
if chunk and chunk.strip():
|
||||
chunks.append(chunk.strip())
|
||||
finally:
|
||||
document.close()
|
||||
return '\n\n'.join(chunks)
|
||||
|
||||
|
||||
def build_parts(name, mimetype, data, max_text_chars=MAX_TEXT_CHARS, pdf_as_text=False):
|
||||
"""Return the message parts describing one file.
|
||||
|
||||
Never raises: an unreadable file still yields a text part naming it, so the
|
||||
model can tell the user what went wrong instead of silently ignoring the
|
||||
upload.
|
||||
|
||||
:param pdf_as_text: when true, a PDF becomes an extracted *text* part
|
||||
instead of ``inline_data``. Used for providers without native file
|
||||
support (text-only models), where a base64 blob would be discarded.
|
||||
"""
|
||||
name = name or 'file'
|
||||
size = len(data or b'')
|
||||
kind = guess_kind(mimetype, name)
|
||||
|
||||
if not size:
|
||||
return [{'type': 'text',
|
||||
'text': f"File '{name}' is empty and could not be read."}]
|
||||
|
||||
if kind == 'image':
|
||||
if size > MAX_INLINE_BYTES:
|
||||
return [{'type': 'text',
|
||||
'text': f"Image '{name}' ({format_size(size)}) is too large to "
|
||||
f"be sent to the model; describe it instead."}]
|
||||
return [{
|
||||
'type': 'inline_data',
|
||||
'mimetype': mimetype or f"image/{split_extension(name)}",
|
||||
'data': base64.b64encode(data).decode(),
|
||||
'metadata': {'name': name, 'size': size},
|
||||
}]
|
||||
|
||||
if kind == 'pdf':
|
||||
if pdf_as_text:
|
||||
# Text-only model: send what the PDF actually says, not its bytes.
|
||||
text = extract_pdf_text(data)
|
||||
text, truncated = _truncate(text, max_text_chars)
|
||||
if not text:
|
||||
return [{'type': 'text',
|
||||
'text': f"PDF '{name}' ({format_size(size)}) contains no "
|
||||
f"readable text (it may be a scanned image)."}]
|
||||
header = f"Content of file '{name}' (application/pdf, {format_size(size)}):"
|
||||
if truncated:
|
||||
header += " (truncated, the file is longer than the limit)"
|
||||
return [{'type': 'text', 'text': f"{header}\n{text}"}]
|
||||
if size > MAX_INLINE_BYTES:
|
||||
return [{'type': 'text',
|
||||
'text': f"PDF '{name}' ({format_size(size)}) is too large to "
|
||||
f"be sent to the model."}]
|
||||
return [{
|
||||
'type': 'inline_data',
|
||||
'mimetype': 'application/pdf',
|
||||
'data': base64.b64encode(data).decode(),
|
||||
'metadata': {'name': name, 'size': size},
|
||||
}]
|
||||
|
||||
if kind == 'text':
|
||||
text = decode_text(data)
|
||||
elif kind in ('word', 'sheet', 'slide'):
|
||||
# CSV is classified as a sheet but is not an archive: it is plain text,
|
||||
# and aligning it into columns reads better than a raw dump.
|
||||
extension = split_extension(name)
|
||||
if extension == 'csv':
|
||||
text = extract_csv_text(data)
|
||||
else:
|
||||
text = extract_office_text(data, kind)
|
||||
if not text and extension in ('doc', 'xls', 'ppt'):
|
||||
return [{'type': 'text',
|
||||
'text': f"'{name}' uses the legacy binary Office format, which "
|
||||
f"cannot be read. Re-save it as .docx/.xlsx/.pptx and "
|
||||
f"upload it again."}]
|
||||
if not text:
|
||||
text = ''
|
||||
else:
|
||||
return [{'type': 'text',
|
||||
'text': f"File '{name}' ({mimetype or 'unknown type'}, "
|
||||
f"{format_size(size)}) cannot be read by the assistant."}]
|
||||
|
||||
text, truncated = _truncate(text, max_text_chars)
|
||||
if not text:
|
||||
return [{'type': 'text',
|
||||
'text': f"File '{name}' ({mimetype or 'unknown type'}, "
|
||||
f"{format_size(size)}) contains no readable text."}]
|
||||
header = f"Content of file '{name}' ({mimetype or kind}, {format_size(size)}):"
|
||||
if truncated:
|
||||
header += " (truncated, the file is longer than the limit)"
|
||||
return [{'type': 'text', 'text': f"{header}\n{text}"}]
|
||||
|
||||
|
||||
def format_size(size):
|
||||
"""Human readable file size, used in prompts and in the chat UI."""
|
||||
size = size or 0
|
||||
if size < 1024:
|
||||
return f"{size} B"
|
||||
if size < 1024 * 1024:
|
||||
return f"{size / 1024:.1f} kB"
|
||||
return f"{size / (1024 * 1024):.1f} MB"
|
||||
Reference in New Issue
Block a user