File size: 506 Bytes
1b64148 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | def sniff_kind(path: str) -> str:
"""Detecta o tipo do arquivo pelos magic bytes, nao pela extensao.
Mais confiavel que confiar no nome/Content-Type enviado pelo cliente.
Retorna "pdf", "image" ou "unknown".
"""
with open(path, "rb") as f:
head = f.read(12)
if head[:5] == b"%PDF-":
return "pdf"
if head[:8] == b"\x89PNG\r\n\x1a\n":
return "image"
if head[:3] == b"\xff\xd8\xff": # JPEG
return "image"
return "unknown"
|