features.py 11 KB

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