File imghdr.py of Package failed_python-tweepy
# Minimal shim replacement for the deprecated standard-library `imghdr` module.
# This provides a very small `what()` implementation sufficient for basic
# image-type detection so importing `imghdr` does not fail on Python 3.13+.
#
# The real stdlib `imghdr` may provide more detection; we only implement a
# few common formats (jpeg, png, gif, bmp, webp) which are sufficient for the
# test-suite and avoid raising ImportError.
from typing import Optional
def what(filename: str, h: Optional[bytes] = None) -> Optional[str]:
"""
Determine the image type of file `filename` or by looking at header bytes `h`.
Returns a string like 'jpeg', 'png', etc., or None if unknown.
"""
try:
if h is None:
with open(filename, "rb") as f:
h = f.read(32)
except Exception:
# If we can't open/read the file, we can't detect; return None.
return None
if not h:
return None
# JPEG
if h.startswith(b'\xff\xd8'):
return 'jpeg'
# PNG
if h.startswith(b'\x89PNG\r\n\x1a\n'):
return 'png'
# GIF (GIF87a or GIF89a)
if h[:6] in (b'GIF87a', b'GIF89a'):
return 'gif'
# BMP (starts with 'BM')
if h.startswith(b'BM'):
return 'bmp'
# WEBP (RIFF....WEBP)
if h.startswith(b'RIFF') and len(h) >= 12 and h[8:12] == b'WEBP':
return 'webp'
# Unknown
return None