from fastapi import UploadFile from app.core.exceptions import ValidationError async def validate_pdf(upload: UploadFile, max_size_bytes: int) -> bytes: """Read and validate a PDF once. The returned bytes are ready for the provider.""" if not upload.filename or not upload.filename.lower().endswith(".pdf"): raise ValidationError("Upload a file with the .pdf extension.") if upload.content_type not in {"application/pdf", "application/x-pdf"}: raise ValidationError("Upload a PDF file.") content = await upload.read(max_size_bytes + 1) if not content: raise ValidationError("The PDF file is empty.") if len(content) > max_size_bytes: raise ValidationError("The PDF exceeds the allowed file size.") if not content.startswith(b"%PDF"): raise ValidationError("The uploaded file is not a valid PDF.") return content