Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

features.py 9.4KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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", "tk_version"),
  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. msg = f"Unknown module {feature}"
  23. raise ValueError(msg)
  24. module, ver = modules[feature]
  25. try:
  26. __import__(module)
  27. return True
  28. except ModuleNotFoundError:
  29. return False
  30. except ImportError as ex:
  31. warnings.warn(str(ex))
  32. return False
  33. def version_module(feature):
  34. """
  35. :param feature: The module to check for.
  36. :returns:
  37. The loaded version number as a string, or ``None`` if unknown or not available.
  38. :raises ValueError: If the module is not defined in this version of Pillow.
  39. """
  40. if not check_module(feature):
  41. return None
  42. module, ver = modules[feature]
  43. if ver is None:
  44. return None
  45. return getattr(__import__(module, fromlist=[ver]), ver)
  46. def get_supported_modules():
  47. """
  48. :returns: A list of all supported modules.
  49. """
  50. return [f for f in modules if check_module(f)]
  51. codecs = {
  52. "jpg": ("jpeg", "jpeglib"),
  53. "jpg_2000": ("jpeg2k", "jp2klib"),
  54. "zlib": ("zip", "zlib"),
  55. "libtiff": ("libtiff", "libtiff"),
  56. }
  57. def check_codec(feature):
  58. """
  59. Checks if a codec is available.
  60. :param feature: The codec to check for.
  61. :returns: ``True`` if available, ``False`` otherwise.
  62. :raises ValueError: If the codec is not defined in this version of Pillow.
  63. """
  64. if feature not in codecs:
  65. msg = f"Unknown codec {feature}"
  66. raise ValueError(msg)
  67. codec, lib = codecs[feature]
  68. return codec + "_encoder" in dir(Image.core)
  69. def version_codec(feature):
  70. """
  71. :param feature: The codec to check for.
  72. :returns:
  73. The version number as a string, or ``None`` if not available.
  74. Checked at compile time for ``jpg``, run-time otherwise.
  75. :raises ValueError: If the codec is not defined in this version of Pillow.
  76. """
  77. if not check_codec(feature):
  78. return None
  79. codec, lib = codecs[feature]
  80. version = getattr(Image.core, lib + "_version")
  81. if feature == "libtiff":
  82. return version.split("\n")[0].split("Version ")[1]
  83. return version
  84. def get_supported_codecs():
  85. """
  86. :returns: A list of all supported codecs.
  87. """
  88. return [f for f in codecs if check_codec(f)]
  89. features = {
  90. "webp_anim": ("PIL._webp", "HAVE_WEBPANIM", None),
  91. "webp_mux": ("PIL._webp", "HAVE_WEBPMUX", None),
  92. "transp_webp": ("PIL._webp", "HAVE_TRANSPARENCY", None),
  93. "raqm": ("PIL._imagingft", "HAVE_RAQM", "raqm_version"),
  94. "fribidi": ("PIL._imagingft", "HAVE_FRIBIDI", "fribidi_version"),
  95. "harfbuzz": ("PIL._imagingft", "HAVE_HARFBUZZ", "harfbuzz_version"),
  96. "libjpeg_turbo": ("PIL._imaging", "HAVE_LIBJPEGTURBO", "libjpeg_turbo_version"),
  97. "libimagequant": ("PIL._imaging", "HAVE_LIBIMAGEQUANT", "imagequant_version"),
  98. "xcb": ("PIL._imaging", "HAVE_XCB", None),
  99. }
  100. def check_feature(feature):
  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):
  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():
  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):
  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):
  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():
  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=None, supported_formats=True):
  174. """
  175. Prints information about this installation of Pillow.
  176. This function can be called with ``python3 -m PIL``.
  177. :param out:
  178. The output stream to print to. Defaults to ``sys.stdout`` if ``None``.
  179. :param supported_formats:
  180. If ``True``, a list of all supported image file formats will be printed.
  181. """
  182. if out is None:
  183. out = sys.stdout
  184. Image.init()
  185. print("-" * 68, file=out)
  186. print(f"Pillow {PIL.__version__}", file=out)
  187. py_version = sys.version.splitlines()
  188. print(f"Python {py_version[0].strip()}", file=out)
  189. for py_version in py_version[1:]:
  190. print(f" {py_version.strip()}", file=out)
  191. print("-" * 68, file=out)
  192. print(
  193. f"Python modules loaded from {os.path.dirname(Image.__file__)}",
  194. file=out,
  195. )
  196. print(
  197. f"Binary modules loaded from {os.path.dirname(Image.core.__file__)}",
  198. file=out,
  199. )
  200. print("-" * 68, file=out)
  201. for name, feature in [
  202. ("pil", "PIL CORE"),
  203. ("tkinter", "TKINTER"),
  204. ("freetype2", "FREETYPE2"),
  205. ("littlecms2", "LITTLECMS2"),
  206. ("webp", "WEBP"),
  207. ("transp_webp", "WEBP Transparency"),
  208. ("webp_mux", "WEBPMUX"),
  209. ("webp_anim", "WEBP Animation"),
  210. ("jpg", "JPEG"),
  211. ("jpg_2000", "OPENJPEG (JPEG2000)"),
  212. ("zlib", "ZLIB (PNG/ZIP)"),
  213. ("libtiff", "LIBTIFF"),
  214. ("raqm", "RAQM (Bidirectional Text)"),
  215. ("libimagequant", "LIBIMAGEQUANT (Quantization method)"),
  216. ("xcb", "XCB (X protocol)"),
  217. ]:
  218. if check(name):
  219. if name == "jpg" and check_feature("libjpeg_turbo"):
  220. v = "libjpeg-turbo " + version_feature("libjpeg_turbo")
  221. else:
  222. v = version(name)
  223. if v is not None:
  224. version_static = name in ("pil", "jpg")
  225. if name == "littlecms2":
  226. # this check is also in src/_imagingcms.c:setup_module()
  227. version_static = tuple(int(x) for x in v.split(".")) < (2, 7)
  228. t = "compiled for" if version_static else "loaded"
  229. if name == "raqm":
  230. for f in ("fribidi", "harfbuzz"):
  231. v2 = version_feature(f)
  232. if v2 is not None:
  233. v += f", {f} {v2}"
  234. print("---", feature, "support ok,", t, v, file=out)
  235. else:
  236. print("---", feature, "support ok", file=out)
  237. else:
  238. print("***", feature, "support not installed", file=out)
  239. print("-" * 68, file=out)
  240. if supported_formats:
  241. extensions = collections.defaultdict(list)
  242. for ext, i in Image.EXTENSION.items():
  243. extensions[i].append(ext)
  244. for i in sorted(Image.ID):
  245. line = f"{i}"
  246. if i in Image.MIME:
  247. line = f"{line} {Image.MIME[i]}"
  248. print(line, file=out)
  249. if i in extensions:
  250. print(
  251. "Extensions: {}".format(", ".join(sorted(extensions[i]))), file=out
  252. )
  253. features = []
  254. if i in Image.OPEN:
  255. features.append("open")
  256. if i in Image.SAVE:
  257. features.append("save")
  258. if i in Image.SAVE_ALL:
  259. features.append("save_all")
  260. if i in Image.DECODERS:
  261. features.append("decode")
  262. if i in Image.ENCODERS:
  263. features.append("encode")
  264. print("Features: {}".format(", ".join(features)), file=out)
  265. print("-" * 68, file=out)