Files
Athena-Deck/chat_media.py
T

136 lines
8.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Bounded inline chat media; no filesystem paths, remote fetches or model work."""
import base64
import binascii
from copy import deepcopy
import io
import math
from pathlib import PurePosixPath
import re
import stat
import zipfile
MIB=1024**2
LIMITS=dict(request_bytes=64*MIB,attachment_bytes=32*MIB,document_bytes=16*MIB,video_bytes=32*MIB,attachments=8,document_pages=600,video_frames=128,video_fps=2)
DOCUMENTS={'.pdf':'application/pdf','.docx':'application/vnd.openxmlformats-officedocument.wordprocessingml.document','.pptx':'application/vnd.openxmlformats-officedocument.presentationml.presentation','.xlsx':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','.txt':'text/plain','.md':'text/markdown','.csv':'text/csv','.json':'application/json','.yaml':'application/yaml','.yml':'application/yaml','.xml':'application/xml'}
VIDEO_TYPES={'video/mp4','video/webm','video/quicktime','video/x-matroska'}
IMAGE_TYPES={'image/png','image/jpeg','image/webp'}
class MediaError(ValueError):
def __init__(self,message,status=400,code='invalid_media'):
super().__init__(message);self.status=status;self.code=code
def profile_capabilities(worker,profile):
"""Configuration/installed vs loaded are explicit; never ensure/load here."""
fn=getattr(type(worker),'capabilities',None)
value=fn(worker,profile) if callable(fn) else {}
if not isinstance(value,dict):value={}
return {**value,'runtime':profile.get('parameters',{}).get('chat_runtime','llama'),'limits':dict(LIMITS),'available':list(value.get('available',[])),'capabilities':list(value.get('capabilities',[]))}
def pages(value):
if not isinstance(value,str) or len(value)>256 or not re.fullmatch(r'[0-9,-]+',value):raise MediaError('PDF-Seiten als Bereiche wie 1-5,8 angeben.')
selected=set()
for token in value.split(','):
fields=token.split('-')
if not 1<=len(fields)<=2 or any(not x for x in fields):raise MediaError('Ungültiger PDF-Seitenbereich.')
first=int(fields[0]);last=int(fields[-1])
if not 1<=first<=last<=LIMITS['document_pages']:raise MediaError('PDF-Seiten müssen zwischen 1 und 600 liegen.')
selected.update(range(first,last+1))
return value
def inline(value,types,maximum):
if not isinstance(value,str):raise MediaError('Eingebettete Datei als Base64-Daten-URL erforderlich.')
match=re.match(r'^data:([^;,]+);base64,',value)
if not match or match[1].lower() not in types:raise MediaError('Nur unterstützte eingebettete Dateien; keine Pfade, Datei-IDs oder externen URLs.')
data=value[match.end():]
if len(data)>4*((maximum+2)//3):raise MediaError('Eingebettete Datei überschreitet das Größenlimit.',413,'media_too_large')
try:raw=base64.b64decode(data,validate=True)
except (ValueError,binascii.Error):raise MediaError('Ungültige Base64-Dateikodierung.') from None
if not raw or len(raw)>maximum:raise MediaError('Datei leer oder zu groß.',413,'media_too_large')
return match[1].lower(),raw
def filename(value):
if not isinstance(value,str) or not 1<=len(value)<=160 or value in ('.','..') or any(ord(c)<32 or ord(c)==127 for c in value) or '/' in value or '\\' in value or PurePosixPath(value).name!=value:raise MediaError('Ein einfacher Dateiname ohne Pfad ist erforderlich.')
suffix=PurePosixPath(value).suffix.lower()
if suffix not in DOCUMENTS:raise MediaError('Unterstützt werden PDF, DOCX, PPTX, XLSX und UTF-8-Textdateien.')
return suffix
def office(raw,suffix):
"""Inspect bounded ZIP metadata only, never extract a client archive."""
try:
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
members=archive.infolist();total=0
if len(members)>2048:raise MediaError('Office-Datei enthält zu viele Archiveinträge.')
for entry in members:
path=PurePosixPath(entry.filename)
if path.is_absolute() or '..' in path.parts or '\\' in entry.filename or entry.flag_bits&1 or stat.S_ISLNK(entry.external_attr>>16):raise MediaError('Unsicherer oder verschlüsselter Office-Archiveintrag.')
total+=entry.file_size
if entry.file_size>16*MIB or total>64*MIB:raise MediaError('Entpacktes Office-Dokument überschreitet das Sicherheitslimit.',413,'media_too_large')
required={'.docx':'word/document.xml','.pptx':'ppt/presentation.xml','.xlsx':'xl/workbook.xml'}[suffix]
if required not in archive.namelist() or '[Content_Types].xml' not in archive.namelist():raise MediaError('Datei ist kein passendes Office-Open-XML-Dokument.')
except zipfile.BadZipFile:raise MediaError('Office-Datei ist kein gültiges ZIP-Dokument.') from None
def validate_messages(messages,profile,features=()):
"""Validate in place without changing payload; count all history attachments."""
if not isinstance(messages,list) or not messages or any(not isinstance(m,dict) for m in messages):raise MediaError('messages muss eine nichtleere Liste sein.')
available=set(features);vision=bool(profile.get('parameters',{}).get('vision_projector'));count=total=0
for message in messages:
content=message.get('content')
if not isinstance(content,list):continue
for part in content:
if not isinstance(part,dict):raise MediaError('Ungültiger Nachrichteninhalt.')
kind=part.get('type')
if kind=='text':
if set(part)!={'type','text'} or not isinstance(part.get('text'),str):raise MediaError('Textteile benötigen ausschließlich type und text.')
continue
if message.get('role') in ('system','developer','assistant'):raise MediaError('Anhänge sind nur in Nutzer- oder Werkzeugnachrichten erlaubt.')
count+=1
if count>LIMITS['attachments']:raise MediaError('Höchstens acht Anhänge im gesamten Chatverlauf.')
if kind=='image_url':
if not vision:raise MediaError('Für Bilder einen Vision-Projektor im Profil aktivieren.')
obj=part.get('image_url')
if set(part)!={'type','image_url'} or not isinstance(obj,dict) or set(obj)-{'url','detail'} or obj.get('detail','auto') not in ('auto','low','high'):raise MediaError('Ungültiger Bildteil.')
_,raw=inline(obj.get('url'),IMAGE_TYPES,LIMITS['attachment_bytes'])
elif kind=='file':
if 'documents' not in available:raise MediaError('Dokumente benötigen eine installierte dokumentfähige Basalt-Laufzeit.',501,'documents_unavailable')
obj=part.get('file')
if set(part)!={'type','file'} or not isinstance(obj,dict) or set(obj)-{'filename','file_data','pages'} or not {'filename','file_data'}<=set(obj):raise MediaError('Dateiteile benötigen filename und file_data; keine Datei-IDs oder URLs.')
suffix=filename(obj['filename']);mime,raw=inline(obj['file_data'],{DOCUMENTS[suffix]},LIMITS['document_bytes'])
if suffix=='.pdf':
if b'%PDF-' not in raw[:1024]:raise MediaError('PDF-Kennung fehlt.')
if 'pages' in obj:pages(obj['pages'])
else:
if 'pages' in obj:raise MediaError('Seitenauswahl wird nur für PDFs unterstützt.')
if suffix in ('.docx','.pptx','.xlsx'):office(raw,suffix)
else:
try:raw.decode('utf-8')
except UnicodeError:raise MediaError('Textdateien müssen UTF-8-kodiert sein.') from None
elif kind in ('video_url','input_video'):
if 'video' not in available or not vision:raise MediaError('Video benötigt Basalt-Videounterstützung, FFmpeg und einen Vision-Projektor.',501,'video_unavailable')
obj=part.get(kind)
if set(part)-{'type',kind,'fps','max_frames'} or not isinstance(obj,dict) or set(obj)!={'url'}:raise MediaError('Ungültiger Videoteil; nur eingebettetes Video und begrenzte Abtastung.')
_,raw=inline(obj.get('url'),VIDEO_TYPES,LIMITS['video_bytes'])
fps=part.get('fps',LIMITS['video_fps']);frames=part.get('max_frames',LIMITS['video_frames'])
if type(fps) not in (int,float) or not math.isfinite(fps) or not 0<fps<=LIMITS['video_fps'] or type(frames) is not int or not 4<=frames<=LIMITS['video_frames']:raise MediaError('Video-Abtastung: höchstens 2 Bilder/s und 4–128 Frames.')
else:raise MediaError('Nicht unterstützter Nachrichteninhalt.')
total+=len(raw)
if total>LIMITS['attachment_bytes']:raise MediaError('Anhänge des gesamten Verlaufs überschreiten 32 MiB.',413,'media_too_large')
return {'attachments':count,'attachment_bytes':total}
def normalize_messages(messages,profile,features=()):
"""Preserve the caller while imposing the same bounded defaults upstream."""
result=deepcopy(messages);info=validate_messages(result,profile,features)
for message in result:
if not isinstance(message.get('content'),list):continue
for part in message['content']:
if part.get('type') in ('video_url','input_video'):
part.setdefault('fps',LIMITS['video_fps']);part.setdefault('max_frames',LIMITS['video_frames'])
return result,info