features.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. from __future__ import annotations
  2. __lazy_modules__ = {"collections", "warnings"}
  3. import collections
  4. import os
  5. import sys
  6. import warnings
  7. import PIL
  8. from . import Image
  9. TYPE_CHECKING = False
  10. if TYPE_CHECKING:
  11. from typing import IO
  12. modules = {
  13. "pil": ("PIL._imaging", "PILLOW_VERSION"),
  14. "tkinter": ("PIL._tkinter_finder", "tk_version"),
  15. "freetype2": ("PIL._imagingft", "freetype2_version"),
  16. "littlecms2": ("PIL._imagingcms", "littlecms_version"),
  17. "webp": ("PIL._webp", "webpdecoder_version"),
  18. "avif": ("PIL._avif", "libavif_version"),
  19. }
  20. def check_module(feature: str) -> bool:
  21. """
  22. Checks if a module is available.
  23. :param feature: The module to check for.
  24. :returns: ``True`` if available, ``False`` otherwise.
  25. :raises ValueError: If the module is not defined in this version of Pillow.
  26. """
  27. if feature not in modules:
  28. msg = f"Unknown module {feature}"
  29. raise ValueError(msg)
  30. module, ver = modules[feature]
  31. try:
  32. __import__(module)
  33. return True
  34. except ModuleNotFoundError:
  35. return False
  36. except ImportError as ex:
  37. warnings.warn(str(ex))
  38. return False
  39. def version_module(feature: str) -> str | None:
  40. """
  41. :param feature: The module to check for.
  42. :returns:
  43. The loaded version number as a string, or ``None`` if unknown or not available.
  44. :raises ValueError: If the module is not defined in this version of Pillow.
  45. """
  46. if not check_module(feature):
  47. return None
  48. module, ver = modules[feature]
  49. return getattr(__import__(module, fromlist=[ver]), ver)
  50. def get_supported_modules() -> list[str]:
  51. """
  52. :returns: A list of all supported modules.
  53. """
  54. return [f for f in modules if check_module(f)]
  55. codecs = {
  56. "jpg": ("jpeg", "jpeglib"),
  57. "jpg_2000": ("jpeg2k", "jp2klib"),
  58. "zlib": ("zip", "zlib"),
  59. "libtiff": ("libtiff", "libtiff"),
  60. }
  61. def check_codec(feature: str) -> bool:
  62. """
  63. Checks if a codec is available.
  64. :param feature: The codec to check for.
  65. :returns: ``True`` if available, ``False`` otherwise.
  66. :raises ValueError: If the codec is not defined in this version of Pillow.
  67. """
  68. if feature not in codecs:
  69. msg = f"Unknown codec {feature}"
  70. raise ValueError(msg)
  71. codec, lib = codecs[feature]
  72. return f"{codec}_encoder" in dir(Image.core)
  73. def version_codec(feature: str) -> str | None:
  74. """
  75. :param feature: The codec to check for.
  76. :returns:
  77. The version number as a string, or ``None`` if not available.
  78. Checked at compile time for ``jpg``, run-time otherwise.
  79. :raises ValueError: If the codec is not defined in this version of Pillow.
  80. """
  81. if not check_codec(feature):
  82. return None
  83. codec, lib = codecs[feature]
  84. version = getattr(Image.core, f"{lib}_version")
  85. if feature == "libtiff":
  86. return version.split("\n")[0].split("Version ")[1]
  87. return version
  88. def get_supported_codecs() -> list[str]:
  89. """
  90. :returns: A list of all supported codecs.
  91. """
  92. return [f for f in codecs if check_codec(f)]
  93. features: dict[str, tuple[str, str, str | None]] = {
  94. "raqm": ("PIL._imagingft", "HAVE_RAQM", "raqm_version"),
  95. "fribidi": ("PIL._imagingft", "HAVE_FRIBIDI", "fribidi_version"),
  96. "harfbuzz": ("PIL._imagingft", "HAVE_HARFBUZZ", "harfbuzz_version"),
  97. "libjpeg_turbo": ("PIL._imaging", "HAVE_LIBJPEGTURBO", "libjpeg_turbo_version"),
  98. "mozjpeg": ("PIL._imaging", "HAVE_MOZJPEG", "libjpeg_turbo_version"),
  99. "zlib_ng": ("PIL._imaging", "HAVE_ZLIBNG", "zlib_ng_version"),
  100. "libimagequant": ("PIL._imaging", "HAVE_LIBIMAGEQUANT", "imagequant_version"),
  101. "xcb": ("PIL._imaging", "HAVE_XCB", None),
  102. }
  103. def check_feature(feature: str) -> bool | None:
  104. """
  105. Checks if a feature is available.
  106. :param feature: The feature to check for.
  107. :returns: ``True`` if available, ``False`` if unavailable, ``None`` if unknown.
  108. :raises ValueError: If the feature is not defined in this version of Pillow.
  109. """
  110. if feature not in features:
  111. msg = f"Unknown feature {feature}"
  112. raise ValueError(msg)
  113. module, flag, ver = features[feature]
  114. try:
  115. imported_module = __import__(module, fromlist=["PIL"])
  116. return getattr(imported_module, flag)
  117. except ModuleNotFoundError:
  118. return None
  119. except ImportError as ex:
  120. warnings.warn(str(ex))
  121. return None
  122. def version_feature(feature: str) -> str | None:
  123. """
  124. :param feature: The feature to check for.
  125. :returns: The version number as a string, or ``None`` if not available.
  126. :raises ValueError: If the feature is not defined in this version of Pillow.
  127. """
  128. if not check_feature(feature):
  129. return None
  130. module, flag, ver = features[feature]
  131. if ver is None:
  132. return None
  133. return getattr(__import__(module, fromlist=[ver]), ver)
  134. def get_supported_features() -> list[str]:
  135. """
  136. :returns: A list of all supported features.
  137. """
  138. return [f for f in features if check_feature(f)]
  139. def check(feature: str) -> bool | None:
  140. """
  141. :param feature: A module, codec, or feature name.
  142. :returns:
  143. ``True`` if the module, codec, or feature is available,
  144. ``False`` or ``None`` otherwise.
  145. """
  146. if feature in modules:
  147. return check_module(feature)
  148. if feature in codecs:
  149. return check_codec(feature)
  150. if feature in features:
  151. return check_feature(feature)
  152. warnings.warn(f"Unknown feature '{feature}'.", stacklevel=2)
  153. return False
  154. def version(feature: str) -> str | None:
  155. """
  156. :param feature:
  157. The module, codec, or feature to check for.
  158. :returns:
  159. The version number as a string, or ``None`` if unknown or not available.
  160. """
  161. if feature in modules:
  162. return version_module(feature)
  163. if feature in codecs:
  164. return version_codec(feature)
  165. if feature in features:
  166. return version_feature(feature)
  167. return None
  168. def get_supported() -> list[str]:
  169. """
  170. :returns: A list of all supported modules, features, and codecs.
  171. """
  172. ret = get_supported_modules()
  173. ret.extend(get_supported_features())
  174. ret.extend(get_supported_codecs())
  175. return ret
  176. def pilinfo(out: IO[str] | None = None, supported_formats: bool = True) -> None:
  177. """
  178. Prints information about this installation of Pillow.
  179. This function can be called with ``python3 -m PIL``.
  180. It can also be called with ``python3 -m PIL.report`` or ``python3 -m PIL --report``
  181. to have "supported_formats" set to ``False``, omitting the list of all supported
  182. image file formats.
  183. :param out:
  184. The output stream to print to. Defaults to ``sys.stdout`` if ``None``.
  185. :param supported_formats:
  186. If ``True``, a list of all supported image file formats will be printed.
  187. """
  188. if out is None:
  189. out = sys.stdout
  190. Image.init()
  191. print("-" * 68, file=out)
  192. print(f"Pillow {PIL.__version__}", file=out)
  193. py_version_lines = sys.version.splitlines()
  194. print(f"Python {py_version_lines[0].strip()}", file=out)
  195. for py_version in py_version_lines[1:]:
  196. print(f" {py_version.strip()}", file=out)
  197. print("-" * 68, file=out)
  198. print(f"Python executable is {sys.executable or 'unknown'}", file=out)
  199. if sys.prefix != sys.base_prefix:
  200. print(f"Environment Python files loaded from {sys.prefix}", file=out)
  201. print(f"System Python files loaded from {sys.base_prefix}", file=out)
  202. print("-" * 68, file=out)
  203. print(
  204. f"Python Pillow modules loaded from {os.path.dirname(Image.__file__)}",
  205. file=out,
  206. )
  207. print(
  208. f"Binary Pillow modules loaded from {os.path.dirname(Image.core.__file__)}",
  209. file=out,
  210. )
  211. print("-" * 68, file=out)
  212. for name, feature in [
  213. ("pil", "PIL CORE"),
  214. ("tkinter", "TKINTER"),
  215. ("freetype2", "FREETYPE2"),
  216. ("littlecms2", "LITTLECMS2"),
  217. ("webp", "WEBP"),
  218. ("avif", "AVIF"),
  219. ("jpg", "JPEG"),
  220. ("jpg_2000", "OPENJPEG (JPEG2000)"),
  221. ("zlib", "ZLIB (PNG/ZIP)"),
  222. ("libtiff", "LIBTIFF"),
  223. ("raqm", "RAQM (Bidirectional Text)"),
  224. ("libimagequant", "LIBIMAGEQUANT (Quantization method)"),
  225. ("xcb", "XCB (X protocol)"),
  226. ]:
  227. if check(name):
  228. v: str | None = None
  229. if name == "jpg":
  230. libjpeg_turbo_version = version_feature("libjpeg_turbo")
  231. if libjpeg_turbo_version is not None:
  232. v = "mozjpeg" if check_feature("mozjpeg") else "libjpeg-turbo"
  233. v += " " + libjpeg_turbo_version
  234. if v is None:
  235. v = version(name)
  236. if v is not None:
  237. version_static = name in ("pil", "jpg")
  238. if name == "littlecms2":
  239. # this check is also in src/_imagingcms.c:setup_module()
  240. version_static = tuple(int(x) for x in v.split(".")) < (2, 7)
  241. t = "compiled for" if version_static else "loaded"
  242. if name == "zlib":
  243. zlib_ng_version = version_feature("zlib_ng")
  244. if zlib_ng_version is not None:
  245. v += ", compiled for zlib-ng " + zlib_ng_version
  246. elif name == "raqm":
  247. for f in ("fribidi", "harfbuzz"):
  248. v2 = version_feature(f)
  249. if v2 is not None:
  250. v += f", {f} {v2}"
  251. print("---", feature, "support ok,", t, v, file=out)
  252. else:
  253. print("---", feature, "support ok", file=out)
  254. else:
  255. print("***", feature, "support not installed", file=out)
  256. print("-" * 68, file=out)
  257. if supported_formats:
  258. extensions = collections.defaultdict(list)
  259. for ext, i in Image.EXTENSION.items():
  260. extensions[i].append(ext)
  261. for i in sorted(Image.ID):
  262. line = f"{i}"
  263. if i in Image.MIME:
  264. line = f"{line} {Image.MIME[i]}"
  265. print(line, file=out)
  266. if i in extensions:
  267. print(
  268. "Extensions: {}".format(", ".join(sorted(extensions[i]))), file=out
  269. )
  270. features = []
  271. if i in Image.OPEN:
  272. features.append("open")
  273. if i in Image.SAVE:
  274. features.append("save")
  275. if i in Image.SAVE_ALL:
  276. features.append("save_all")
  277. if i in Image.DECODERS:
  278. features.append("decode")
  279. if i in Image.ENCODERS:
  280. features.append("encode")
  281. print("Features: {}".format(", ".join(features)), file=out)
  282. print("-" * 68, file=out)