from fastapi import UploadFile MAX_UPLOAD_BYTES = 10 * 1024 * 1024 # 10 MB — statements are a few hundred KB async def read_pdf_upload( file: UploadFile, max_bytes: int = MAX_UPLOAD_BYTES ) -> bytes: """Read an uploaded PDF with a size cap and magic-byte check. Raises ValueError with a user-readable, filename-prefixed message — upload endpoints surface these in their per-file `errors` list. """ filename = file.filename or "unknown.pdf" data = await file.read(max_bytes + 1) if len(data) > max_bytes: raise ValueError( f"{filename}: file exceeds the {max_bytes // (1024 * 1024)} MB limit" ) if not data.startswith(b"%PDF"): raise ValueError(f"{filename}: not a PDF file") return data