features.py 8.8 KB

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