ZTWHHH commited on
Commit
f98611c
·
verified ·
1 Parent(s): 844cd9c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. evalkit_internvl/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_asin.h +44 -0
  2. evalkit_internvl/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_erfc.h +44 -0
  3. evalkit_internvl/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_gru_cell_compositeexplicitautograd_dispatch.h +24 -0
  4. evalkit_internvl/lib/python3.10/site-packages/torch/include/ATen/ops/nanquantile_compositeimplicitautograd_dispatch.h +28 -0
  5. evalkit_internvl/lib/python3.10/site-packages/torch/include/ATen/ops/new_full.h +97 -0
  6. evalkit_internvl/lib/python3.10/site-packages/torch/include/ATen/ops/scatter_meta_dispatch.h +38 -0
  7. evalkit_internvl/lib/python3.10/site-packages/torch/include/ATen/ops/special_log_ndtr.h +39 -0
  8. evalkit_tf437/lib/python3.10/site-packages/PIL/BdfFontFile.py +133 -0
  9. evalkit_tf437/lib/python3.10/site-packages/PIL/BmpImagePlugin.py +489 -0
  10. evalkit_tf437/lib/python3.10/site-packages/PIL/BufrStubImagePlugin.py +76 -0
  11. evalkit_tf437/lib/python3.10/site-packages/PIL/CurImagePlugin.py +75 -0
  12. evalkit_tf437/lib/python3.10/site-packages/PIL/FontFile.py +134 -0
  13. evalkit_tf437/lib/python3.10/site-packages/PIL/GribStubImagePlugin.py +76 -0
  14. evalkit_tf437/lib/python3.10/site-packages/PIL/IcoImagePlugin.py +360 -0
  15. evalkit_tf437/lib/python3.10/site-packages/PIL/ImImagePlugin.py +374 -0
  16. evalkit_tf437/lib/python3.10/site-packages/PIL/ImageCms.py +1127 -0
  17. evalkit_tf437/lib/python3.10/site-packages/PIL/ImageFilter.py +604 -0
  18. evalkit_tf437/lib/python3.10/site-packages/PIL/ImageMode.py +92 -0
  19. evalkit_tf437/lib/python3.10/site-packages/PIL/ImagePalette.py +284 -0
  20. evalkit_tf437/lib/python3.10/site-packages/PIL/ImagePath.py +20 -0
  21. evalkit_tf437/lib/python3.10/site-packages/PIL/ImageShow.py +363 -0
  22. evalkit_tf437/lib/python3.10/site-packages/PIL/ImageTk.py +284 -0
  23. evalkit_tf437/lib/python3.10/site-packages/PIL/ImageTransform.py +135 -0
  24. evalkit_tf437/lib/python3.10/site-packages/PIL/ImageWin.py +238 -0
  25. evalkit_tf437/lib/python3.10/site-packages/PIL/ImtImagePlugin.py +103 -0
  26. evalkit_tf437/lib/python3.10/site-packages/PIL/JpegPresets.py +242 -0
  27. evalkit_tf437/lib/python3.10/site-packages/PIL/PalmImagePlugin.py +229 -0
  28. evalkit_tf437/lib/python3.10/site-packages/PIL/PcfFontFile.py +254 -0
  29. evalkit_tf437/lib/python3.10/site-packages/PIL/PngImagePlugin.py +1489 -0
  30. evalkit_tf437/lib/python3.10/site-packages/PIL/PyAccess.py +381 -0
  31. evalkit_tf437/lib/python3.10/site-packages/PIL/SpiderImagePlugin.py +325 -0
  32. evalkit_tf437/lib/python3.10/site-packages/PIL/TiffTags.py +555 -0
  33. evalkit_tf437/lib/python3.10/site-packages/PIL/WalImageFile.py +124 -0
  34. evalkit_tf437/lib/python3.10/site-packages/PIL/XVThumbImagePlugin.py +81 -0
  35. evalkit_tf437/lib/python3.10/site-packages/PIL/__init__.py +86 -0
  36. evalkit_tf437/lib/python3.10/site-packages/PIL/_binary.py +112 -0
  37. evalkit_tf437/lib/python3.10/site-packages/PIL/_imaging.pyi +30 -0
  38. evalkit_tf437/lib/python3.10/site-packages/PIL/_imagingft.pyi +69 -0
  39. evalkit_tf437/lib/python3.10/site-packages/PIL/_tkinter_finder.py +21 -0
  40. evalkit_tf437/lib/python3.10/site-packages/flash_attn/__pycache__/__init__.cpython-310.pyc +0 -0
  41. evalkit_tf437/lib/python3.10/site-packages/flash_attn/__pycache__/bert_padding.cpython-310.pyc +0 -0
  42. evalkit_tf437/lib/python3.10/site-packages/flash_attn/__pycache__/fused_softmax.cpython-310.pyc +0 -0
  43. evalkit_tf437/lib/python3.10/site-packages/flash_attn/losses/__init__.py +0 -0
  44. evalkit_tf437/lib/python3.10/site-packages/flash_attn/losses/__pycache__/__init__.cpython-310.pyc +0 -0
  45. evalkit_tf437/lib/python3.10/site-packages/flash_attn/losses/__pycache__/cross_entropy.cpython-310.pyc +0 -0
  46. evalkit_tf437/lib/python3.10/site-packages/flash_attn/losses/cross_entropy.py +84 -0
  47. evalkit_tf437/lib/python3.10/site-packages/flash_attn/models/__pycache__/__init__.cpython-310.pyc +0 -0
  48. evalkit_tf437/lib/python3.10/site-packages/flash_attn/models/__pycache__/baichuan.cpython-310.pyc +0 -0
  49. evalkit_tf437/lib/python3.10/site-packages/flash_attn/models/__pycache__/bigcode.cpython-310.pyc +0 -0
  50. evalkit_tf437/lib/python3.10/site-packages/flash_attn/models/__pycache__/btlm.cpython-310.pyc +0 -0
evalkit_internvl/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_asin.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/_foreach_asin_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_foreach_asin(Tensor[] self) -> Tensor[]
26
+ inline ::std::vector<at::Tensor> _foreach_asin(at::TensorList self) {
27
+ return at::_ops::_foreach_asin::call(self);
28
+ }
29
+
30
+ // aten::_foreach_asin_(Tensor(a!)[] self) -> ()
31
+ inline void _foreach_asin_(at::TensorList self) {
32
+ return at::_ops::_foreach_asin_::call(self);
33
+ }
34
+
35
+ // aten::_foreach_asin.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
36
+ inline void _foreach_asin_out(at::TensorList out, at::TensorList self) {
37
+ return at::_ops::_foreach_asin_out::call(self, out);
38
+ }
39
+ // aten::_foreach_asin.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
40
+ inline void _foreach_asin_outf(at::TensorList self, at::TensorList out) {
41
+ return at::_ops::_foreach_asin_out::call(self, out);
42
+ }
43
+
44
+ }
evalkit_internvl/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_erfc.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/_foreach_erfc_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_foreach_erfc(Tensor[] self) -> Tensor[]
26
+ inline ::std::vector<at::Tensor> _foreach_erfc(at::TensorList self) {
27
+ return at::_ops::_foreach_erfc::call(self);
28
+ }
29
+
30
+ // aten::_foreach_erfc_(Tensor(a!)[] self) -> ()
31
+ inline void _foreach_erfc_(at::TensorList self) {
32
+ return at::_ops::_foreach_erfc_::call(self);
33
+ }
34
+
35
+ // aten::_foreach_erfc.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
36
+ inline void _foreach_erfc_out(at::TensorList out, at::TensorList self) {
37
+ return at::_ops::_foreach_erfc_out::call(self, out);
38
+ }
39
+ // aten::_foreach_erfc.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
40
+ inline void _foreach_erfc_outf(at::TensorList self, at::TensorList out) {
41
+ return at::_ops::_foreach_erfc_out::call(self, out);
42
+ }
43
+
44
+ }
evalkit_internvl/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_gru_cell_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> _thnn_fused_gru_cell_out(at::Tensor & out0, at::Tensor & out1, const at::Tensor & input_gates, const at::Tensor & hidden_gates, const at::Tensor & hx, const c10::optional<at::Tensor> & input_bias={}, const c10::optional<at::Tensor> & hidden_bias={});
21
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> _thnn_fused_gru_cell_outf(const at::Tensor & input_gates, const at::Tensor & hidden_gates, const at::Tensor & hx, const c10::optional<at::Tensor> & input_bias, const c10::optional<at::Tensor> & hidden_bias, at::Tensor & out0, at::Tensor & out1);
22
+
23
+ } // namespace compositeexplicitautograd
24
+ } // namespace at
evalkit_internvl/lib/python3.10/site-packages/torch/include/ATen/ops/nanquantile_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor nanquantile(const at::Tensor & self, const at::Tensor & q, c10::optional<int64_t> dim=c10::nullopt, bool keepdim=false, c10::string_view interpolation="linear");
21
+ TORCH_API at::Tensor & nanquantile_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & q, c10::optional<int64_t> dim=c10::nullopt, bool keepdim=false, c10::string_view interpolation="linear");
22
+ TORCH_API at::Tensor & nanquantile_outf(const at::Tensor & self, const at::Tensor & q, c10::optional<int64_t> dim, bool keepdim, c10::string_view interpolation, at::Tensor & out);
23
+ TORCH_API at::Tensor nanquantile(const at::Tensor & self, double q, c10::optional<int64_t> dim=c10::nullopt, bool keepdim=false, c10::string_view interpolation="linear");
24
+ TORCH_API at::Tensor & nanquantile_out(at::Tensor & out, const at::Tensor & self, double q, c10::optional<int64_t> dim=c10::nullopt, bool keepdim=false, c10::string_view interpolation="linear");
25
+ TORCH_API at::Tensor & nanquantile_outf(const at::Tensor & self, double q, c10::optional<int64_t> dim, bool keepdim, c10::string_view interpolation, at::Tensor & out);
26
+
27
+ } // namespace compositeimplicitautograd
28
+ } // namespace at
evalkit_internvl/lib/python3.10/site-packages/torch/include/ATen/ops/new_full.h ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/new_full_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ namespace symint {
26
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
27
+ at::Tensor new_full(const at::Tensor & self, at::IntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options={}) {
28
+ return at::_ops::new_full::call(self, c10::fromIntArrayRefSlow(size), fill_value, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt());
29
+ }
30
+ }
31
+
32
+ namespace symint {
33
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
34
+ at::Tensor new_full(const at::Tensor & self, at::IntArrayRef size, const at::Scalar & fill_value, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory) {
35
+ return at::_ops::new_full::call(self, c10::fromIntArrayRefSlow(size), fill_value, dtype, layout, device, pin_memory);
36
+ }
37
+ }
38
+
39
+ namespace symint {
40
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
41
+ at::Tensor new_full(const at::Tensor & self, c10::SymIntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options={}) {
42
+ return at::_ops::new_full::call(self, size, fill_value, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt());
43
+ }
44
+ }
45
+
46
+ namespace symint {
47
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
48
+ at::Tensor new_full(const at::Tensor & self, c10::SymIntArrayRef size, const at::Scalar & fill_value, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory) {
49
+ return at::_ops::new_full::call(self, size, fill_value, dtype, layout, device, pin_memory);
50
+ }
51
+ }
52
+
53
+ // aten::new_full.out(Tensor self, SymInt[] size, Scalar fill_value, *, Tensor(a!) out) -> Tensor(a!)
54
+ inline at::Tensor & new_full_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef size, const at::Scalar & fill_value) {
55
+ return at::_ops::new_full_out::call(self, c10::fromIntArrayRefSlow(size), fill_value, out);
56
+ }
57
+ namespace symint {
58
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
59
+ at::Tensor & new_full_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef size, const at::Scalar & fill_value) {
60
+ return at::_ops::new_full_out::call(self, c10::fromIntArrayRefSlow(size), fill_value, out);
61
+ }
62
+ }
63
+
64
+ // aten::new_full.out(Tensor self, SymInt[] size, Scalar fill_value, *, Tensor(a!) out) -> Tensor(a!)
65
+ inline at::Tensor & new_full_outf(const at::Tensor & self, at::IntArrayRef size, const at::Scalar & fill_value, at::Tensor & out) {
66
+ return at::_ops::new_full_out::call(self, c10::fromIntArrayRefSlow(size), fill_value, out);
67
+ }
68
+ namespace symint {
69
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
70
+ at::Tensor & new_full_outf(const at::Tensor & self, at::IntArrayRef size, const at::Scalar & fill_value, at::Tensor & out) {
71
+ return at::_ops::new_full_out::call(self, c10::fromIntArrayRefSlow(size), fill_value, out);
72
+ }
73
+ }
74
+
75
+ // aten::new_full.out(Tensor self, SymInt[] size, Scalar fill_value, *, Tensor(a!) out) -> Tensor(a!)
76
+ inline at::Tensor & new_full_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef size, const at::Scalar & fill_value) {
77
+ return at::_ops::new_full_out::call(self, size, fill_value, out);
78
+ }
79
+ namespace symint {
80
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
81
+ at::Tensor & new_full_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef size, const at::Scalar & fill_value) {
82
+ return at::_ops::new_full_out::call(self, size, fill_value, out);
83
+ }
84
+ }
85
+
86
+ // aten::new_full.out(Tensor self, SymInt[] size, Scalar fill_value, *, Tensor(a!) out) -> Tensor(a!)
87
+ inline at::Tensor & new_full_symint_outf(const at::Tensor & self, c10::SymIntArrayRef size, const at::Scalar & fill_value, at::Tensor & out) {
88
+ return at::_ops::new_full_out::call(self, size, fill_value, out);
89
+ }
90
+ namespace symint {
91
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
92
+ at::Tensor & new_full_outf(const at::Tensor & self, c10::SymIntArrayRef size, const at::Scalar & fill_value, at::Tensor & out) {
93
+ return at::_ops::new_full_out::call(self, size, fill_value, out);
94
+ }
95
+ }
96
+
97
+ }
evalkit_internvl/lib/python3.10/site-packages/torch/include/ATen/ops/scatter_meta_dispatch.h ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor scatter(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src);
21
+ TORCH_API at::Tensor & scatter_out(at::Tensor & out, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src);
22
+ TORCH_API at::Tensor & scatter_outf(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, at::Tensor & out);
23
+ TORCH_API at::Tensor & scatter_(at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src);
24
+ TORCH_API at::Tensor scatter(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Scalar & value);
25
+ TORCH_API at::Tensor & scatter_out(at::Tensor & out, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Scalar & value);
26
+ TORCH_API at::Tensor & scatter_outf(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Scalar & value, at::Tensor & out);
27
+ TORCH_API at::Tensor & scatter_(at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Scalar & value);
28
+ TORCH_API at::Tensor scatter(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce);
29
+ TORCH_API at::Tensor & scatter_out(at::Tensor & out, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce);
30
+ TORCH_API at::Tensor & scatter_outf(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, at::Tensor & out);
31
+ TORCH_API at::Tensor & scatter_(at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce);
32
+ TORCH_API at::Tensor scatter(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Scalar & value, c10::string_view reduce);
33
+ TORCH_API at::Tensor & scatter_out(at::Tensor & out, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Scalar & value, c10::string_view reduce);
34
+ TORCH_API at::Tensor & scatter_outf(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Scalar & value, c10::string_view reduce, at::Tensor & out);
35
+ TORCH_API at::Tensor & scatter_(at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Scalar & value, c10::string_view reduce);
36
+
37
+ } // namespace meta
38
+ } // namespace at
evalkit_internvl/lib/python3.10/site-packages/torch/include/ATen/ops/special_log_ndtr.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/special_log_ndtr_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::special_log_ndtr(Tensor self) -> Tensor
26
+ inline at::Tensor special_log_ndtr(const at::Tensor & self) {
27
+ return at::_ops::special_log_ndtr::call(self);
28
+ }
29
+
30
+ // aten::special_log_ndtr.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
31
+ inline at::Tensor & special_log_ndtr_out(at::Tensor & out, const at::Tensor & self) {
32
+ return at::_ops::special_log_ndtr_out::call(self, out);
33
+ }
34
+ // aten::special_log_ndtr.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
35
+ inline at::Tensor & special_log_ndtr_outf(const at::Tensor & self, at::Tensor & out) {
36
+ return at::_ops::special_log_ndtr_out::call(self, out);
37
+ }
38
+
39
+ }
evalkit_tf437/lib/python3.10/site-packages/PIL/BdfFontFile.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # bitmap distribution font (bdf) file parser
6
+ #
7
+ # history:
8
+ # 1996-05-16 fl created (as bdf2pil)
9
+ # 1997-08-25 fl converted to FontFile driver
10
+ # 2001-05-25 fl removed bogus __init__ call
11
+ # 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev)
12
+ # 2003-04-22 fl more robustification (from Graham Dumpleton)
13
+ #
14
+ # Copyright (c) 1997-2003 by Secret Labs AB.
15
+ # Copyright (c) 1997-2003 by Fredrik Lundh.
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+
20
+ """
21
+ Parse X Bitmap Distribution Format (BDF)
22
+ """
23
+ from __future__ import annotations
24
+
25
+ from typing import BinaryIO
26
+
27
+ from . import FontFile, Image
28
+
29
+ bdf_slant = {
30
+ "R": "Roman",
31
+ "I": "Italic",
32
+ "O": "Oblique",
33
+ "RI": "Reverse Italic",
34
+ "RO": "Reverse Oblique",
35
+ "OT": "Other",
36
+ }
37
+
38
+ bdf_spacing = {"P": "Proportional", "M": "Monospaced", "C": "Cell"}
39
+
40
+
41
+ def bdf_char(
42
+ f: BinaryIO,
43
+ ) -> (
44
+ tuple[
45
+ str,
46
+ int,
47
+ tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]],
48
+ Image.Image,
49
+ ]
50
+ | None
51
+ ):
52
+ # skip to STARTCHAR
53
+ while True:
54
+ s = f.readline()
55
+ if not s:
56
+ return None
57
+ if s[:9] == b"STARTCHAR":
58
+ break
59
+ id = s[9:].strip().decode("ascii")
60
+
61
+ # load symbol properties
62
+ props = {}
63
+ while True:
64
+ s = f.readline()
65
+ if not s or s[:6] == b"BITMAP":
66
+ break
67
+ i = s.find(b" ")
68
+ props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
69
+
70
+ # load bitmap
71
+ bitmap = bytearray()
72
+ while True:
73
+ s = f.readline()
74
+ if not s or s[:7] == b"ENDCHAR":
75
+ break
76
+ bitmap += s[:-1]
77
+
78
+ # The word BBX
79
+ # followed by the width in x (BBw), height in y (BBh),
80
+ # and x and y displacement (BBxoff0, BByoff0)
81
+ # of the lower left corner from the origin of the character.
82
+ width, height, x_disp, y_disp = (int(p) for p in props["BBX"].split())
83
+
84
+ # The word DWIDTH
85
+ # followed by the width in x and y of the character in device pixels.
86
+ dwx, dwy = (int(p) for p in props["DWIDTH"].split())
87
+
88
+ bbox = (
89
+ (dwx, dwy),
90
+ (x_disp, -y_disp - height, width + x_disp, -y_disp),
91
+ (0, 0, width, height),
92
+ )
93
+
94
+ try:
95
+ im = Image.frombytes("1", (width, height), bitmap, "hex", "1")
96
+ except ValueError:
97
+ # deal with zero-width characters
98
+ im = Image.new("1", (width, height))
99
+
100
+ return id, int(props["ENCODING"]), bbox, im
101
+
102
+
103
+ class BdfFontFile(FontFile.FontFile):
104
+ """Font file plugin for the X11 BDF format."""
105
+
106
+ def __init__(self, fp: BinaryIO) -> None:
107
+ super().__init__()
108
+
109
+ s = fp.readline()
110
+ if s[:13] != b"STARTFONT 2.1":
111
+ msg = "not a valid BDF file"
112
+ raise SyntaxError(msg)
113
+
114
+ props = {}
115
+ comments = []
116
+
117
+ while True:
118
+ s = fp.readline()
119
+ if not s or s[:13] == b"ENDPROPERTIES":
120
+ break
121
+ i = s.find(b" ")
122
+ props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
123
+ if s[:i] in [b"COMMENT", b"COPYRIGHT"]:
124
+ if s.find(b"LogicalFontDescription") < 0:
125
+ comments.append(s[i + 1 : -1].decode("ascii"))
126
+
127
+ while True:
128
+ c = bdf_char(fp)
129
+ if not c:
130
+ break
131
+ id, ch, (xy, dst, src), im = c
132
+ if 0 <= ch < len(self.glyph):
133
+ self.glyph[ch] = xy, dst, src, im
evalkit_tf437/lib/python3.10/site-packages/PIL/BmpImagePlugin.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # BMP file handler
6
+ #
7
+ # Windows (and OS/2) native bitmap storage format.
8
+ #
9
+ # history:
10
+ # 1995-09-01 fl Created
11
+ # 1996-04-30 fl Added save
12
+ # 1997-08-27 fl Fixed save of 1-bit images
13
+ # 1998-03-06 fl Load P images as L where possible
14
+ # 1998-07-03 fl Load P images as 1 where possible
15
+ # 1998-12-29 fl Handle small palettes
16
+ # 2002-12-30 fl Fixed load of 1-bit palette images
17
+ # 2003-04-21 fl Fixed load of 1-bit monochrome images
18
+ # 2003-04-23 fl Added limited support for BI_BITFIELDS compression
19
+ #
20
+ # Copyright (c) 1997-2003 by Secret Labs AB
21
+ # Copyright (c) 1995-2003 by Fredrik Lundh
22
+ #
23
+ # See the README file for information on usage and redistribution.
24
+ #
25
+ from __future__ import annotations
26
+
27
+ import os
28
+ from typing import IO
29
+
30
+ from . import Image, ImageFile, ImagePalette
31
+ from ._binary import i16le as i16
32
+ from ._binary import i32le as i32
33
+ from ._binary import o8
34
+ from ._binary import o16le as o16
35
+ from ._binary import o32le as o32
36
+
37
+ #
38
+ # --------------------------------------------------------------------
39
+ # Read BMP file
40
+
41
+ BIT2MODE = {
42
+ # bits => mode, rawmode
43
+ 1: ("P", "P;1"),
44
+ 4: ("P", "P;4"),
45
+ 8: ("P", "P"),
46
+ 16: ("RGB", "BGR;15"),
47
+ 24: ("RGB", "BGR"),
48
+ 32: ("RGB", "BGRX"),
49
+ }
50
+
51
+
52
+ def _accept(prefix: bytes) -> bool:
53
+ return prefix[:2] == b"BM"
54
+
55
+
56
+ def _dib_accept(prefix: bytes) -> bool:
57
+ return i32(prefix) in [12, 40, 52, 56, 64, 108, 124]
58
+
59
+
60
+ # =============================================================================
61
+ # Image plugin for the Windows BMP format.
62
+ # =============================================================================
63
+ class BmpImageFile(ImageFile.ImageFile):
64
+ """Image plugin for the Windows Bitmap format (BMP)"""
65
+
66
+ # ------------------------------------------------------------- Description
67
+ format_description = "Windows Bitmap"
68
+ format = "BMP"
69
+
70
+ # -------------------------------------------------- BMP Compression values
71
+ COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
72
+ for k, v in COMPRESSIONS.items():
73
+ vars()[k] = v
74
+
75
+ def _bitmap(self, header=0, offset=0):
76
+ """Read relevant info about the BMP"""
77
+ read, seek = self.fp.read, self.fp.seek
78
+ if header:
79
+ seek(header)
80
+ # read bmp header size @offset 14 (this is part of the header size)
81
+ file_info = {"header_size": i32(read(4)), "direction": -1}
82
+
83
+ # -------------------- If requested, read header at a specific position
84
+ # read the rest of the bmp header, without its size
85
+ header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
86
+
87
+ # ------------------------------- Windows Bitmap v2, IBM OS/2 Bitmap v1
88
+ # ----- This format has different offsets because of width/height types
89
+ # 12: BITMAPCOREHEADER/OS21XBITMAPHEADER
90
+ if file_info["header_size"] == 12:
91
+ file_info["width"] = i16(header_data, 0)
92
+ file_info["height"] = i16(header_data, 2)
93
+ file_info["planes"] = i16(header_data, 4)
94
+ file_info["bits"] = i16(header_data, 6)
95
+ file_info["compression"] = self.RAW
96
+ file_info["palette_padding"] = 3
97
+
98
+ # --------------------------------------------- Windows Bitmap v3 to v5
99
+ # 40: BITMAPINFOHEADER
100
+ # 52: BITMAPV2HEADER
101
+ # 56: BITMAPV3HEADER
102
+ # 64: BITMAPCOREHEADER2/OS22XBITMAPHEADER
103
+ # 108: BITMAPV4HEADER
104
+ # 124: BITMAPV5HEADER
105
+ elif file_info["header_size"] in (40, 52, 56, 64, 108, 124):
106
+ file_info["y_flip"] = header_data[7] == 0xFF
107
+ file_info["direction"] = 1 if file_info["y_flip"] else -1
108
+ file_info["width"] = i32(header_data, 0)
109
+ file_info["height"] = (
110
+ i32(header_data, 4)
111
+ if not file_info["y_flip"]
112
+ else 2**32 - i32(header_data, 4)
113
+ )
114
+ file_info["planes"] = i16(header_data, 8)
115
+ file_info["bits"] = i16(header_data, 10)
116
+ file_info["compression"] = i32(header_data, 12)
117
+ # byte size of pixel data
118
+ file_info["data_size"] = i32(header_data, 16)
119
+ file_info["pixels_per_meter"] = (
120
+ i32(header_data, 20),
121
+ i32(header_data, 24),
122
+ )
123
+ file_info["colors"] = i32(header_data, 28)
124
+ file_info["palette_padding"] = 4
125
+ self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"])
126
+ if file_info["compression"] == self.BITFIELDS:
127
+ masks = ["r_mask", "g_mask", "b_mask"]
128
+ if len(header_data) >= 48:
129
+ if len(header_data) >= 52:
130
+ masks.append("a_mask")
131
+ else:
132
+ file_info["a_mask"] = 0x0
133
+ for idx, mask in enumerate(masks):
134
+ file_info[mask] = i32(header_data, 36 + idx * 4)
135
+ else:
136
+ # 40 byte headers only have the three components in the
137
+ # bitfields masks, ref:
138
+ # https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
139
+ # See also
140
+ # https://github.com/python-pillow/Pillow/issues/1293
141
+ # There is a 4th component in the RGBQuad, in the alpha
142
+ # location, but it is listed as a reserved component,
143
+ # and it is not generally an alpha channel
144
+ file_info["a_mask"] = 0x0
145
+ for mask in masks:
146
+ file_info[mask] = i32(read(4))
147
+ file_info["rgb_mask"] = (
148
+ file_info["r_mask"],
149
+ file_info["g_mask"],
150
+ file_info["b_mask"],
151
+ )
152
+ file_info["rgba_mask"] = (
153
+ file_info["r_mask"],
154
+ file_info["g_mask"],
155
+ file_info["b_mask"],
156
+ file_info["a_mask"],
157
+ )
158
+ else:
159
+ msg = f"Unsupported BMP header type ({file_info['header_size']})"
160
+ raise OSError(msg)
161
+
162
+ # ------------------ Special case : header is reported 40, which
163
+ # ---------------------- is shorter than real size for bpp >= 16
164
+ self._size = file_info["width"], file_info["height"]
165
+
166
+ # ------- If color count was not found in the header, compute from bits
167
+ file_info["colors"] = (
168
+ file_info["colors"]
169
+ if file_info.get("colors", 0)
170
+ else (1 << file_info["bits"])
171
+ )
172
+ if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
173
+ offset += 4 * file_info["colors"]
174
+
175
+ # ---------------------- Check bit depth for unusual unsupported values
176
+ self._mode, raw_mode = BIT2MODE.get(file_info["bits"], (None, None))
177
+ if self.mode is None:
178
+ msg = f"Unsupported BMP pixel depth ({file_info['bits']})"
179
+ raise OSError(msg)
180
+
181
+ # ---------------- Process BMP with Bitfields compression (not palette)
182
+ decoder_name = "raw"
183
+ if file_info["compression"] == self.BITFIELDS:
184
+ SUPPORTED = {
185
+ 32: [
186
+ (0xFF0000, 0xFF00, 0xFF, 0x0),
187
+ (0xFF000000, 0xFF0000, 0xFF00, 0x0),
188
+ (0xFF000000, 0xFF00, 0xFF, 0x0),
189
+ (0xFF000000, 0xFF0000, 0xFF00, 0xFF),
190
+ (0xFF, 0xFF00, 0xFF0000, 0xFF000000),
191
+ (0xFF0000, 0xFF00, 0xFF, 0xFF000000),
192
+ (0xFF000000, 0xFF00, 0xFF, 0xFF0000),
193
+ (0x0, 0x0, 0x0, 0x0),
194
+ ],
195
+ 24: [(0xFF0000, 0xFF00, 0xFF)],
196
+ 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
197
+ }
198
+ MASK_MODES = {
199
+ (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
200
+ (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
201
+ (32, (0xFF000000, 0xFF00, 0xFF, 0x0)): "BGXR",
202
+ (32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)): "ABGR",
203
+ (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
204
+ (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
205
+ (32, (0xFF000000, 0xFF00, 0xFF, 0xFF0000)): "BGAR",
206
+ (32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
207
+ (24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
208
+ (16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
209
+ (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
210
+ }
211
+ if file_info["bits"] in SUPPORTED:
212
+ if (
213
+ file_info["bits"] == 32
214
+ and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
215
+ ):
216
+ raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
217
+ self._mode = "RGBA" if "A" in raw_mode else self.mode
218
+ elif (
219
+ file_info["bits"] in (24, 16)
220
+ and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
221
+ ):
222
+ raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
223
+ else:
224
+ msg = "Unsupported BMP bitfields layout"
225
+ raise OSError(msg)
226
+ else:
227
+ msg = "Unsupported BMP bitfields layout"
228
+ raise OSError(msg)
229
+ elif file_info["compression"] == self.RAW:
230
+ if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset
231
+ raw_mode, self._mode = "BGRA", "RGBA"
232
+ elif file_info["compression"] in (self.RLE8, self.RLE4):
233
+ decoder_name = "bmp_rle"
234
+ else:
235
+ msg = f"Unsupported BMP compression ({file_info['compression']})"
236
+ raise OSError(msg)
237
+
238
+ # --------------- Once the header is processed, process the palette/LUT
239
+ if self.mode == "P": # Paletted for 1, 4 and 8 bit images
240
+ # ---------------------------------------------------- 1-bit images
241
+ if not (0 < file_info["colors"] <= 65536):
242
+ msg = f"Unsupported BMP Palette size ({file_info['colors']})"
243
+ raise OSError(msg)
244
+ else:
245
+ padding = file_info["palette_padding"]
246
+ palette = read(padding * file_info["colors"])
247
+ grayscale = True
248
+ indices = (
249
+ (0, 255)
250
+ if file_info["colors"] == 2
251
+ else list(range(file_info["colors"]))
252
+ )
253
+
254
+ # ----------------- Check if grayscale and ignore palette if so
255
+ for ind, val in enumerate(indices):
256
+ rgb = palette[ind * padding : ind * padding + 3]
257
+ if rgb != o8(val) * 3:
258
+ grayscale = False
259
+
260
+ # ------- If all colors are gray, white or black, ditch palette
261
+ if grayscale:
262
+ self._mode = "1" if file_info["colors"] == 2 else "L"
263
+ raw_mode = self.mode
264
+ else:
265
+ self._mode = "P"
266
+ self.palette = ImagePalette.raw(
267
+ "BGRX" if padding == 4 else "BGR", palette
268
+ )
269
+
270
+ # ---------------------------- Finally set the tile data for the plugin
271
+ self.info["compression"] = file_info["compression"]
272
+ args = [raw_mode]
273
+ if decoder_name == "bmp_rle":
274
+ args.append(file_info["compression"] == self.RLE4)
275
+ else:
276
+ args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
277
+ args.append(file_info["direction"])
278
+ self.tile = [
279
+ (
280
+ decoder_name,
281
+ (0, 0, file_info["width"], file_info["height"]),
282
+ offset or self.fp.tell(),
283
+ tuple(args),
284
+ )
285
+ ]
286
+
287
+ def _open(self) -> None:
288
+ """Open file, check magic number and read header"""
289
+ # read 14 bytes: magic number, filesize, reserved, header final offset
290
+ head_data = self.fp.read(14)
291
+ # choke if the file does not have the required magic bytes
292
+ if not _accept(head_data):
293
+ msg = "Not a BMP file"
294
+ raise SyntaxError(msg)
295
+ # read the start position of the BMP image data (u32)
296
+ offset = i32(head_data, 10)
297
+ # load bitmap information (offset=raster info)
298
+ self._bitmap(offset=offset)
299
+
300
+
301
+ class BmpRleDecoder(ImageFile.PyDecoder):
302
+ _pulls_fd = True
303
+
304
+ def decode(self, buffer: bytes) -> tuple[int, int]:
305
+ assert self.fd is not None
306
+ rle4 = self.args[1]
307
+ data = bytearray()
308
+ x = 0
309
+ dest_length = self.state.xsize * self.state.ysize
310
+ while len(data) < dest_length:
311
+ pixels = self.fd.read(1)
312
+ byte = self.fd.read(1)
313
+ if not pixels or not byte:
314
+ break
315
+ num_pixels = pixels[0]
316
+ if num_pixels:
317
+ # encoded mode
318
+ if x + num_pixels > self.state.xsize:
319
+ # Too much data for row
320
+ num_pixels = max(0, self.state.xsize - x)
321
+ if rle4:
322
+ first_pixel = o8(byte[0] >> 4)
323
+ second_pixel = o8(byte[0] & 0x0F)
324
+ for index in range(num_pixels):
325
+ if index % 2 == 0:
326
+ data += first_pixel
327
+ else:
328
+ data += second_pixel
329
+ else:
330
+ data += byte * num_pixels
331
+ x += num_pixels
332
+ else:
333
+ if byte[0] == 0:
334
+ # end of line
335
+ while len(data) % self.state.xsize != 0:
336
+ data += b"\x00"
337
+ x = 0
338
+ elif byte[0] == 1:
339
+ # end of bitmap
340
+ break
341
+ elif byte[0] == 2:
342
+ # delta
343
+ bytes_read = self.fd.read(2)
344
+ if len(bytes_read) < 2:
345
+ break
346
+ right, up = self.fd.read(2)
347
+ data += b"\x00" * (right + up * self.state.xsize)
348
+ x = len(data) % self.state.xsize
349
+ else:
350
+ # absolute mode
351
+ if rle4:
352
+ # 2 pixels per byte
353
+ byte_count = byte[0] // 2
354
+ bytes_read = self.fd.read(byte_count)
355
+ for byte_read in bytes_read:
356
+ data += o8(byte_read >> 4)
357
+ data += o8(byte_read & 0x0F)
358
+ else:
359
+ byte_count = byte[0]
360
+ bytes_read = self.fd.read(byte_count)
361
+ data += bytes_read
362
+ if len(bytes_read) < byte_count:
363
+ break
364
+ x += byte[0]
365
+
366
+ # align to 16-bit word boundary
367
+ if self.fd.tell() % 2 != 0:
368
+ self.fd.seek(1, os.SEEK_CUR)
369
+ rawmode = "L" if self.mode == "L" else "P"
370
+ self.set_as_raw(bytes(data), (rawmode, 0, self.args[-1]))
371
+ return -1, 0
372
+
373
+
374
+ # =============================================================================
375
+ # Image plugin for the DIB format (BMP alias)
376
+ # =============================================================================
377
+ class DibImageFile(BmpImageFile):
378
+ format = "DIB"
379
+ format_description = "Windows Bitmap"
380
+
381
+ def _open(self) -> None:
382
+ self._bitmap()
383
+
384
+
385
+ #
386
+ # --------------------------------------------------------------------
387
+ # Write BMP file
388
+
389
+
390
+ SAVE = {
391
+ "1": ("1", 1, 2),
392
+ "L": ("L", 8, 256),
393
+ "P": ("P", 8, 256),
394
+ "RGB": ("BGR", 24, 0),
395
+ "RGBA": ("BGRA", 32, 0),
396
+ }
397
+
398
+
399
+ def _dib_save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
400
+ _save(im, fp, filename, False)
401
+
402
+
403
+ def _save(
404
+ im: Image.Image, fp: IO[bytes], filename: str | bytes, bitmap_header: bool = True
405
+ ) -> None:
406
+ try:
407
+ rawmode, bits, colors = SAVE[im.mode]
408
+ except KeyError as e:
409
+ msg = f"cannot write mode {im.mode} as BMP"
410
+ raise OSError(msg) from e
411
+
412
+ info = im.encoderinfo
413
+
414
+ dpi = info.get("dpi", (96, 96))
415
+
416
+ # 1 meter == 39.3701 inches
417
+ ppm = tuple(int(x * 39.3701 + 0.5) for x in dpi)
418
+
419
+ stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
420
+ header = 40 # or 64 for OS/2 version 2
421
+ image = stride * im.size[1]
422
+
423
+ if im.mode == "1":
424
+ palette = b"".join(o8(i) * 4 for i in (0, 255))
425
+ elif im.mode == "L":
426
+ palette = b"".join(o8(i) * 4 for i in range(256))
427
+ elif im.mode == "P":
428
+ palette = im.im.getpalette("RGB", "BGRX")
429
+ colors = len(palette) // 4
430
+ else:
431
+ palette = None
432
+
433
+ # bitmap header
434
+ if bitmap_header:
435
+ offset = 14 + header + colors * 4
436
+ file_size = offset + image
437
+ if file_size > 2**32 - 1:
438
+ msg = "File size is too large for the BMP format"
439
+ raise ValueError(msg)
440
+ fp.write(
441
+ b"BM" # file type (magic)
442
+ + o32(file_size) # file size
443
+ + o32(0) # reserved
444
+ + o32(offset) # image data offset
445
+ )
446
+
447
+ # bitmap info header
448
+ fp.write(
449
+ o32(header) # info header size
450
+ + o32(im.size[0]) # width
451
+ + o32(im.size[1]) # height
452
+ + o16(1) # planes
453
+ + o16(bits) # depth
454
+ + o32(0) # compression (0=uncompressed)
455
+ + o32(image) # size of bitmap
456
+ + o32(ppm[0]) # resolution
457
+ + o32(ppm[1]) # resolution
458
+ + o32(colors) # colors used
459
+ + o32(colors) # colors important
460
+ )
461
+
462
+ fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
463
+
464
+ if palette:
465
+ fp.write(palette)
466
+
467
+ ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))])
468
+
469
+
470
+ #
471
+ # --------------------------------------------------------------------
472
+ # Registry
473
+
474
+
475
+ Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
476
+ Image.register_save(BmpImageFile.format, _save)
477
+
478
+ Image.register_extension(BmpImageFile.format, ".bmp")
479
+
480
+ Image.register_mime(BmpImageFile.format, "image/bmp")
481
+
482
+ Image.register_decoder("bmp_rle", BmpRleDecoder)
483
+
484
+ Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
485
+ Image.register_save(DibImageFile.format, _dib_save)
486
+
487
+ Image.register_extension(DibImageFile.format, ".dib")
488
+
489
+ Image.register_mime(DibImageFile.format, "image/bmp")
evalkit_tf437/lib/python3.10/site-packages/PIL/BufrStubImagePlugin.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # BUFR stub adapter
6
+ #
7
+ # Copyright (c) 1996-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+ from __future__ import annotations
12
+
13
+ from typing import IO
14
+
15
+ from . import Image, ImageFile
16
+
17
+ _handler = None
18
+
19
+
20
+ def register_handler(handler: ImageFile.StubHandler | None) -> None:
21
+ """
22
+ Install application-specific BUFR image handler.
23
+
24
+ :param handler: Handler object.
25
+ """
26
+ global _handler
27
+ _handler = handler
28
+
29
+
30
+ # --------------------------------------------------------------------
31
+ # Image adapter
32
+
33
+
34
+ def _accept(prefix: bytes) -> bool:
35
+ return prefix[:4] == b"BUFR" or prefix[:4] == b"ZCZC"
36
+
37
+
38
+ class BufrStubImageFile(ImageFile.StubImageFile):
39
+ format = "BUFR"
40
+ format_description = "BUFR"
41
+
42
+ def _open(self) -> None:
43
+ offset = self.fp.tell()
44
+
45
+ if not _accept(self.fp.read(4)):
46
+ msg = "Not a BUFR file"
47
+ raise SyntaxError(msg)
48
+
49
+ self.fp.seek(offset)
50
+
51
+ # make something up
52
+ self._mode = "F"
53
+ self._size = 1, 1
54
+
55
+ loader = self._load()
56
+ if loader:
57
+ loader.open(self)
58
+
59
+ def _load(self) -> ImageFile.StubHandler | None:
60
+ return _handler
61
+
62
+
63
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
64
+ if _handler is None or not hasattr(_handler, "save"):
65
+ msg = "BUFR save handler not installed"
66
+ raise OSError(msg)
67
+ _handler.save(im, fp, filename)
68
+
69
+
70
+ # --------------------------------------------------------------------
71
+ # Registry
72
+
73
+ Image.register_open(BufrStubImageFile.format, BufrStubImageFile, _accept)
74
+ Image.register_save(BufrStubImageFile.format, _save)
75
+
76
+ Image.register_extension(BufrStubImageFile.format, ".bufr")
evalkit_tf437/lib/python3.10/site-packages/PIL/CurImagePlugin.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # Windows Cursor support for PIL
6
+ #
7
+ # notes:
8
+ # uses BmpImagePlugin.py to read the bitmap data.
9
+ #
10
+ # history:
11
+ # 96-05-27 fl Created
12
+ #
13
+ # Copyright (c) Secret Labs AB 1997.
14
+ # Copyright (c) Fredrik Lundh 1996.
15
+ #
16
+ # See the README file for information on usage and redistribution.
17
+ #
18
+ from __future__ import annotations
19
+
20
+ from . import BmpImagePlugin, Image
21
+ from ._binary import i16le as i16
22
+ from ._binary import i32le as i32
23
+
24
+ #
25
+ # --------------------------------------------------------------------
26
+
27
+
28
+ def _accept(prefix: bytes) -> bool:
29
+ return prefix[:4] == b"\0\0\2\0"
30
+
31
+
32
+ ##
33
+ # Image plugin for Windows Cursor files.
34
+
35
+
36
+ class CurImageFile(BmpImagePlugin.BmpImageFile):
37
+ format = "CUR"
38
+ format_description = "Windows Cursor"
39
+
40
+ def _open(self) -> None:
41
+ offset = self.fp.tell()
42
+
43
+ # check magic
44
+ s = self.fp.read(6)
45
+ if not _accept(s):
46
+ msg = "not a CUR file"
47
+ raise SyntaxError(msg)
48
+
49
+ # pick the largest cursor in the file
50
+ m = b""
51
+ for i in range(i16(s, 4)):
52
+ s = self.fp.read(16)
53
+ if not m:
54
+ m = s
55
+ elif s[0] > m[0] and s[1] > m[1]:
56
+ m = s
57
+ if not m:
58
+ msg = "No cursors were found"
59
+ raise TypeError(msg)
60
+
61
+ # load as bitmap
62
+ self._bitmap(i32(m, 12) + offset)
63
+
64
+ # patch up the bitmap height
65
+ self._size = self.size[0], self.size[1] // 2
66
+ d, e, o, a = self.tile[0]
67
+ self.tile[0] = d, (0, 0) + self.size, o, a
68
+
69
+
70
+ #
71
+ # --------------------------------------------------------------------
72
+
73
+ Image.register_open(CurImageFile.format, CurImageFile, _accept)
74
+
75
+ Image.register_extension(CurImageFile.format, ".cur")
evalkit_tf437/lib/python3.10/site-packages/PIL/FontFile.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # base class for raster font file parsers
6
+ #
7
+ # history:
8
+ # 1997-06-05 fl created
9
+ # 1997-08-19 fl restrict image width
10
+ #
11
+ # Copyright (c) 1997-1998 by Secret Labs AB
12
+ # Copyright (c) 1997-1998 by Fredrik Lundh
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ from typing import BinaryIO
20
+
21
+ from . import Image, _binary
22
+
23
+ WIDTH = 800
24
+
25
+
26
+ def puti16(
27
+ fp: BinaryIO, values: tuple[int, int, int, int, int, int, int, int, int, int]
28
+ ) -> None:
29
+ """Write network order (big-endian) 16-bit sequence"""
30
+ for v in values:
31
+ if v < 0:
32
+ v += 65536
33
+ fp.write(_binary.o16be(v))
34
+
35
+
36
+ class FontFile:
37
+ """Base class for raster font file handlers."""
38
+
39
+ bitmap: Image.Image | None = None
40
+
41
+ def __init__(self) -> None:
42
+ self.info: dict[bytes, bytes | int] = {}
43
+ self.glyph: list[
44
+ tuple[
45
+ tuple[int, int],
46
+ tuple[int, int, int, int],
47
+ tuple[int, int, int, int],
48
+ Image.Image,
49
+ ]
50
+ | None
51
+ ] = [None] * 256
52
+
53
+ def __getitem__(self, ix: int) -> (
54
+ tuple[
55
+ tuple[int, int],
56
+ tuple[int, int, int, int],
57
+ tuple[int, int, int, int],
58
+ Image.Image,
59
+ ]
60
+ | None
61
+ ):
62
+ return self.glyph[ix]
63
+
64
+ def compile(self) -> None:
65
+ """Create metrics and bitmap"""
66
+
67
+ if self.bitmap:
68
+ return
69
+
70
+ # create bitmap large enough to hold all data
71
+ h = w = maxwidth = 0
72
+ lines = 1
73
+ for glyph in self.glyph:
74
+ if glyph:
75
+ d, dst, src, im = glyph
76
+ h = max(h, src[3] - src[1])
77
+ w = w + (src[2] - src[0])
78
+ if w > WIDTH:
79
+ lines += 1
80
+ w = src[2] - src[0]
81
+ maxwidth = max(maxwidth, w)
82
+
83
+ xsize = maxwidth
84
+ ysize = lines * h
85
+
86
+ if xsize == 0 and ysize == 0:
87
+ return
88
+
89
+ self.ysize = h
90
+
91
+ # paste glyphs into bitmap
92
+ self.bitmap = Image.new("1", (xsize, ysize))
93
+ self.metrics: list[
94
+ tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]]
95
+ | None
96
+ ] = [None] * 256
97
+ x = y = 0
98
+ for i in range(256):
99
+ glyph = self[i]
100
+ if glyph:
101
+ d, dst, src, im = glyph
102
+ xx = src[2] - src[0]
103
+ x0, y0 = x, y
104
+ x = x + xx
105
+ if x > WIDTH:
106
+ x, y = 0, y + h
107
+ x0, y0 = x, y
108
+ x = xx
109
+ s = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0
110
+ self.bitmap.paste(im.crop(src), s)
111
+ self.metrics[i] = d, dst, s
112
+
113
+ def save(self, filename: str) -> None:
114
+ """Save font"""
115
+
116
+ self.compile()
117
+
118
+ # font data
119
+ if not self.bitmap:
120
+ msg = "No bitmap created"
121
+ raise ValueError(msg)
122
+ self.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG")
123
+
124
+ # font metrics
125
+ with open(os.path.splitext(filename)[0] + ".pil", "wb") as fp:
126
+ fp.write(b"PILfont\n")
127
+ fp.write(f";;;;;;{self.ysize};\n".encode("ascii")) # HACK!!!
128
+ fp.write(b"DATA\n")
129
+ for id in range(256):
130
+ m = self.metrics[id]
131
+ if not m:
132
+ puti16(fp, (0,) * 10)
133
+ else:
134
+ puti16(fp, m[0] + m[1] + m[2])
evalkit_tf437/lib/python3.10/site-packages/PIL/GribStubImagePlugin.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # GRIB stub adapter
6
+ #
7
+ # Copyright (c) 1996-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+ from __future__ import annotations
12
+
13
+ from typing import IO
14
+
15
+ from . import Image, ImageFile
16
+
17
+ _handler = None
18
+
19
+
20
+ def register_handler(handler: ImageFile.StubHandler | None) -> None:
21
+ """
22
+ Install application-specific GRIB image handler.
23
+
24
+ :param handler: Handler object.
25
+ """
26
+ global _handler
27
+ _handler = handler
28
+
29
+
30
+ # --------------------------------------------------------------------
31
+ # Image adapter
32
+
33
+
34
+ def _accept(prefix: bytes) -> bool:
35
+ return prefix[:4] == b"GRIB" and prefix[7] == 1
36
+
37
+
38
+ class GribStubImageFile(ImageFile.StubImageFile):
39
+ format = "GRIB"
40
+ format_description = "GRIB"
41
+
42
+ def _open(self) -> None:
43
+ offset = self.fp.tell()
44
+
45
+ if not _accept(self.fp.read(8)):
46
+ msg = "Not a GRIB file"
47
+ raise SyntaxError(msg)
48
+
49
+ self.fp.seek(offset)
50
+
51
+ # make something up
52
+ self._mode = "F"
53
+ self._size = 1, 1
54
+
55
+ loader = self._load()
56
+ if loader:
57
+ loader.open(self)
58
+
59
+ def _load(self) -> ImageFile.StubHandler | None:
60
+ return _handler
61
+
62
+
63
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
64
+ if _handler is None or not hasattr(_handler, "save"):
65
+ msg = "GRIB save handler not installed"
66
+ raise OSError(msg)
67
+ _handler.save(im, fp, filename)
68
+
69
+
70
+ # --------------------------------------------------------------------
71
+ # Registry
72
+
73
+ Image.register_open(GribStubImageFile.format, GribStubImageFile, _accept)
74
+ Image.register_save(GribStubImageFile.format, _save)
75
+
76
+ Image.register_extension(GribStubImageFile.format, ".grib")
evalkit_tf437/lib/python3.10/site-packages/PIL/IcoImagePlugin.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # Windows Icon support for PIL
6
+ #
7
+ # History:
8
+ # 96-05-27 fl Created
9
+ #
10
+ # Copyright (c) Secret Labs AB 1997.
11
+ # Copyright (c) Fredrik Lundh 1996.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+
16
+ # This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
17
+ # <casadebender@gmail.com>.
18
+ # https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
19
+ #
20
+ # Icon format references:
21
+ # * https://en.wikipedia.org/wiki/ICO_(file_format)
22
+ # * https://msdn.microsoft.com/en-us/library/ms997538.aspx
23
+ from __future__ import annotations
24
+
25
+ import warnings
26
+ from io import BytesIO
27
+ from math import ceil, log
28
+ from typing import IO
29
+
30
+ from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin
31
+ from ._binary import i16le as i16
32
+ from ._binary import i32le as i32
33
+ from ._binary import o8
34
+ from ._binary import o16le as o16
35
+ from ._binary import o32le as o32
36
+
37
+ #
38
+ # --------------------------------------------------------------------
39
+
40
+ _MAGIC = b"\0\0\1\0"
41
+
42
+
43
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
44
+ fp.write(_MAGIC) # (2+2)
45
+ bmp = im.encoderinfo.get("bitmap_format") == "bmp"
46
+ sizes = im.encoderinfo.get(
47
+ "sizes",
48
+ [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
49
+ )
50
+ frames = []
51
+ provided_ims = [im] + im.encoderinfo.get("append_images", [])
52
+ width, height = im.size
53
+ for size in sorted(set(sizes)):
54
+ if size[0] > width or size[1] > height or size[0] > 256 or size[1] > 256:
55
+ continue
56
+
57
+ for provided_im in provided_ims:
58
+ if provided_im.size != size:
59
+ continue
60
+ frames.append(provided_im)
61
+ if bmp:
62
+ bits = BmpImagePlugin.SAVE[provided_im.mode][1]
63
+ bits_used = [bits]
64
+ for other_im in provided_ims:
65
+ if other_im.size != size:
66
+ continue
67
+ bits = BmpImagePlugin.SAVE[other_im.mode][1]
68
+ if bits not in bits_used:
69
+ # Another image has been supplied for this size
70
+ # with a different bit depth
71
+ frames.append(other_im)
72
+ bits_used.append(bits)
73
+ break
74
+ else:
75
+ # TODO: invent a more convenient method for proportional scalings
76
+ frame = provided_im.copy()
77
+ frame.thumbnail(size, Image.Resampling.LANCZOS, reducing_gap=None)
78
+ frames.append(frame)
79
+ fp.write(o16(len(frames))) # idCount(2)
80
+ offset = fp.tell() + len(frames) * 16
81
+ for frame in frames:
82
+ width, height = frame.size
83
+ # 0 means 256
84
+ fp.write(o8(width if width < 256 else 0)) # bWidth(1)
85
+ fp.write(o8(height if height < 256 else 0)) # bHeight(1)
86
+
87
+ bits, colors = BmpImagePlugin.SAVE[frame.mode][1:] if bmp else (32, 0)
88
+ fp.write(o8(colors)) # bColorCount(1)
89
+ fp.write(b"\0") # bReserved(1)
90
+ fp.write(b"\0\0") # wPlanes(2)
91
+ fp.write(o16(bits)) # wBitCount(2)
92
+
93
+ image_io = BytesIO()
94
+ if bmp:
95
+ frame.save(image_io, "dib")
96
+
97
+ if bits != 32:
98
+ and_mask = Image.new("1", size)
99
+ ImageFile._save(
100
+ and_mask, image_io, [("raw", (0, 0) + size, 0, ("1", 0, -1))]
101
+ )
102
+ else:
103
+ frame.save(image_io, "png")
104
+ image_io.seek(0)
105
+ image_bytes = image_io.read()
106
+ if bmp:
107
+ image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:]
108
+ bytes_len = len(image_bytes)
109
+ fp.write(o32(bytes_len)) # dwBytesInRes(4)
110
+ fp.write(o32(offset)) # dwImageOffset(4)
111
+ current = fp.tell()
112
+ fp.seek(offset)
113
+ fp.write(image_bytes)
114
+ offset = offset + bytes_len
115
+ fp.seek(current)
116
+
117
+
118
+ def _accept(prefix: bytes) -> bool:
119
+ return prefix[:4] == _MAGIC
120
+
121
+
122
+ class IcoFile:
123
+ def __init__(self, buf):
124
+ """
125
+ Parse image from file-like object containing ico file data
126
+ """
127
+
128
+ # check magic
129
+ s = buf.read(6)
130
+ if not _accept(s):
131
+ msg = "not an ICO file"
132
+ raise SyntaxError(msg)
133
+
134
+ self.buf = buf
135
+ self.entry = []
136
+
137
+ # Number of items in file
138
+ self.nb_items = i16(s, 4)
139
+
140
+ # Get headers for each item
141
+ for i in range(self.nb_items):
142
+ s = buf.read(16)
143
+
144
+ icon_header = {
145
+ "width": s[0],
146
+ "height": s[1],
147
+ "nb_color": s[2], # No. of colors in image (0 if >=8bpp)
148
+ "reserved": s[3],
149
+ "planes": i16(s, 4),
150
+ "bpp": i16(s, 6),
151
+ "size": i32(s, 8),
152
+ "offset": i32(s, 12),
153
+ }
154
+
155
+ # See Wikipedia
156
+ for j in ("width", "height"):
157
+ if not icon_header[j]:
158
+ icon_header[j] = 256
159
+
160
+ # See Wikipedia notes about color depth.
161
+ # We need this just to differ images with equal sizes
162
+ icon_header["color_depth"] = (
163
+ icon_header["bpp"]
164
+ or (
165
+ icon_header["nb_color"] != 0
166
+ and ceil(log(icon_header["nb_color"], 2))
167
+ )
168
+ or 256
169
+ )
170
+
171
+ icon_header["dim"] = (icon_header["width"], icon_header["height"])
172
+ icon_header["square"] = icon_header["width"] * icon_header["height"]
173
+
174
+ self.entry.append(icon_header)
175
+
176
+ self.entry = sorted(self.entry, key=lambda x: x["color_depth"])
177
+ # ICO images are usually squares
178
+ self.entry = sorted(self.entry, key=lambda x: x["square"], reverse=True)
179
+
180
+ def sizes(self):
181
+ """
182
+ Get a list of all available icon sizes and color depths.
183
+ """
184
+ return {(h["width"], h["height"]) for h in self.entry}
185
+
186
+ def getentryindex(self, size, bpp=False):
187
+ for i, h in enumerate(self.entry):
188
+ if size == h["dim"] and (bpp is False or bpp == h["color_depth"]):
189
+ return i
190
+ return 0
191
+
192
+ def getimage(self, size, bpp=False):
193
+ """
194
+ Get an image from the icon
195
+ """
196
+ return self.frame(self.getentryindex(size, bpp))
197
+
198
+ def frame(self, idx: int) -> Image.Image:
199
+ """
200
+ Get an image from frame idx
201
+ """
202
+
203
+ header = self.entry[idx]
204
+
205
+ self.buf.seek(header["offset"])
206
+ data = self.buf.read(8)
207
+ self.buf.seek(header["offset"])
208
+
209
+ im: Image.Image
210
+ if data[:8] == PngImagePlugin._MAGIC:
211
+ # png frame
212
+ im = PngImagePlugin.PngImageFile(self.buf)
213
+ Image._decompression_bomb_check(im.size)
214
+ else:
215
+ # XOR + AND mask bmp frame
216
+ im = BmpImagePlugin.DibImageFile(self.buf)
217
+ Image._decompression_bomb_check(im.size)
218
+
219
+ # change tile dimension to only encompass XOR image
220
+ im._size = (im.size[0], int(im.size[1] / 2))
221
+ d, e, o, a = im.tile[0]
222
+ im.tile[0] = d, (0, 0) + im.size, o, a
223
+
224
+ # figure out where AND mask image starts
225
+ bpp = header["bpp"]
226
+ if 32 == bpp:
227
+ # 32-bit color depth icon image allows semitransparent areas
228
+ # PIL's DIB format ignores transparency bits, recover them.
229
+ # The DIB is packed in BGRX byte order where X is the alpha
230
+ # channel.
231
+
232
+ # Back up to start of bmp data
233
+ self.buf.seek(o)
234
+ # extract every 4th byte (eg. 3,7,11,15,...)
235
+ alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]
236
+
237
+ # convert to an 8bpp grayscale image
238
+ mask = Image.frombuffer(
239
+ "L", # 8bpp
240
+ im.size, # (w, h)
241
+ alpha_bytes, # source chars
242
+ "raw", # raw decoder
243
+ ("L", 0, -1), # 8bpp inverted, unpadded, reversed
244
+ )
245
+ else:
246
+ # get AND image from end of bitmap
247
+ w = im.size[0]
248
+ if (w % 32) > 0:
249
+ # bitmap row data is aligned to word boundaries
250
+ w += 32 - (im.size[0] % 32)
251
+
252
+ # the total mask data is
253
+ # padded row size * height / bits per char
254
+
255
+ total_bytes = int((w * im.size[1]) / 8)
256
+ and_mask_offset = header["offset"] + header["size"] - total_bytes
257
+
258
+ self.buf.seek(and_mask_offset)
259
+ mask_data = self.buf.read(total_bytes)
260
+
261
+ # convert raw data to image
262
+ mask = Image.frombuffer(
263
+ "1", # 1 bpp
264
+ im.size, # (w, h)
265
+ mask_data, # source chars
266
+ "raw", # raw decoder
267
+ ("1;I", int(w / 8), -1), # 1bpp inverted, padded, reversed
268
+ )
269
+
270
+ # now we have two images, im is XOR image and mask is AND image
271
+
272
+ # apply mask image as alpha channel
273
+ im = im.convert("RGBA")
274
+ im.putalpha(mask)
275
+
276
+ return im
277
+
278
+
279
+ ##
280
+ # Image plugin for Windows Icon files.
281
+
282
+
283
+ class IcoImageFile(ImageFile.ImageFile):
284
+ """
285
+ PIL read-only image support for Microsoft Windows .ico files.
286
+
287
+ By default the largest resolution image in the file will be loaded. This
288
+ can be changed by altering the 'size' attribute before calling 'load'.
289
+
290
+ The info dictionary has a key 'sizes' that is a list of the sizes available
291
+ in the icon file.
292
+
293
+ Handles classic, XP and Vista icon formats.
294
+
295
+ When saving, PNG compression is used. Support for this was only added in
296
+ Windows Vista. If you are unable to view the icon in Windows, convert the
297
+ image to "RGBA" mode before saving.
298
+
299
+ This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
300
+ <casadebender@gmail.com>.
301
+ https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
302
+ """
303
+
304
+ format = "ICO"
305
+ format_description = "Windows Icon"
306
+
307
+ def _open(self) -> None:
308
+ self.ico = IcoFile(self.fp)
309
+ self.info["sizes"] = self.ico.sizes()
310
+ self.size = self.ico.entry[0]["dim"]
311
+ self.load()
312
+
313
+ @property
314
+ def size(self):
315
+ return self._size
316
+
317
+ @size.setter
318
+ def size(self, value):
319
+ if value not in self.info["sizes"]:
320
+ msg = "This is not one of the allowed sizes of this image"
321
+ raise ValueError(msg)
322
+ self._size = value
323
+
324
+ def load(self):
325
+ if self.im is not None and self.im.size == self.size:
326
+ # Already loaded
327
+ return Image.Image.load(self)
328
+ im = self.ico.getimage(self.size)
329
+ # if tile is PNG, it won't really be loaded yet
330
+ im.load()
331
+ self.im = im.im
332
+ self.pyaccess = None
333
+ self._mode = im.mode
334
+ if im.palette:
335
+ self.palette = im.palette
336
+ if im.size != self.size:
337
+ warnings.warn("Image was not the expected size")
338
+
339
+ index = self.ico.getentryindex(self.size)
340
+ sizes = list(self.info["sizes"])
341
+ sizes[index] = im.size
342
+ self.info["sizes"] = set(sizes)
343
+
344
+ self.size = im.size
345
+
346
+ def load_seek(self, pos: int) -> None:
347
+ # Flag the ImageFile.Parser so that it
348
+ # just does all the decode at the end.
349
+ pass
350
+
351
+
352
+ #
353
+ # --------------------------------------------------------------------
354
+
355
+
356
+ Image.register_open(IcoImageFile.format, IcoImageFile, _accept)
357
+ Image.register_save(IcoImageFile.format, _save)
358
+ Image.register_extension(IcoImageFile.format, ".ico")
359
+
360
+ Image.register_mime(IcoImageFile.format, "image/x-icon")
evalkit_tf437/lib/python3.10/site-packages/PIL/ImImagePlugin.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # IFUNC IM file handling for PIL
6
+ #
7
+ # history:
8
+ # 1995-09-01 fl Created.
9
+ # 1997-01-03 fl Save palette images
10
+ # 1997-01-08 fl Added sequence support
11
+ # 1997-01-23 fl Added P and RGB save support
12
+ # 1997-05-31 fl Read floating point images
13
+ # 1997-06-22 fl Save floating point images
14
+ # 1997-08-27 fl Read and save 1-bit images
15
+ # 1998-06-25 fl Added support for RGB+LUT images
16
+ # 1998-07-02 fl Added support for YCC images
17
+ # 1998-07-15 fl Renamed offset attribute to avoid name clash
18
+ # 1998-12-29 fl Added I;16 support
19
+ # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)
20
+ # 2003-09-26 fl Added LA/PA support
21
+ #
22
+ # Copyright (c) 1997-2003 by Secret Labs AB.
23
+ # Copyright (c) 1995-2001 by Fredrik Lundh.
24
+ #
25
+ # See the README file for information on usage and redistribution.
26
+ #
27
+ from __future__ import annotations
28
+
29
+ import os
30
+ import re
31
+ from typing import IO, Any
32
+
33
+ from . import Image, ImageFile, ImagePalette
34
+
35
+ # --------------------------------------------------------------------
36
+ # Standard tags
37
+
38
+ COMMENT = "Comment"
39
+ DATE = "Date"
40
+ EQUIPMENT = "Digitalization equipment"
41
+ FRAMES = "File size (no of images)"
42
+ LUT = "Lut"
43
+ NAME = "Name"
44
+ SCALE = "Scale (x,y)"
45
+ SIZE = "Image size (x*y)"
46
+ MODE = "Image type"
47
+
48
+ TAGS = {
49
+ COMMENT: 0,
50
+ DATE: 0,
51
+ EQUIPMENT: 0,
52
+ FRAMES: 0,
53
+ LUT: 0,
54
+ NAME: 0,
55
+ SCALE: 0,
56
+ SIZE: 0,
57
+ MODE: 0,
58
+ }
59
+
60
+ OPEN = {
61
+ # ifunc93/p3cfunc formats
62
+ "0 1 image": ("1", "1"),
63
+ "L 1 image": ("1", "1"),
64
+ "Greyscale image": ("L", "L"),
65
+ "Grayscale image": ("L", "L"),
66
+ "RGB image": ("RGB", "RGB;L"),
67
+ "RLB image": ("RGB", "RLB"),
68
+ "RYB image": ("RGB", "RLB"),
69
+ "B1 image": ("1", "1"),
70
+ "B2 image": ("P", "P;2"),
71
+ "B4 image": ("P", "P;4"),
72
+ "X 24 image": ("RGB", "RGB"),
73
+ "L 32 S image": ("I", "I;32"),
74
+ "L 32 F image": ("F", "F;32"),
75
+ # old p3cfunc formats
76
+ "RGB3 image": ("RGB", "RGB;T"),
77
+ "RYB3 image": ("RGB", "RYB;T"),
78
+ # extensions
79
+ "LA image": ("LA", "LA;L"),
80
+ "PA image": ("LA", "PA;L"),
81
+ "RGBA image": ("RGBA", "RGBA;L"),
82
+ "RGBX image": ("RGB", "RGBX;L"),
83
+ "CMYK image": ("CMYK", "CMYK;L"),
84
+ "YCC image": ("YCbCr", "YCbCr;L"),
85
+ }
86
+
87
+ # ifunc95 extensions
88
+ for i in ["8", "8S", "16", "16S", "32", "32F"]:
89
+ OPEN[f"L {i} image"] = ("F", f"F;{i}")
90
+ OPEN[f"L*{i} image"] = ("F", f"F;{i}")
91
+ for i in ["16", "16L", "16B"]:
92
+ OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}")
93
+ OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}")
94
+ for i in ["32S"]:
95
+ OPEN[f"L {i} image"] = ("I", f"I;{i}")
96
+ OPEN[f"L*{i} image"] = ("I", f"I;{i}")
97
+ for j in range(2, 33):
98
+ OPEN[f"L*{j} image"] = ("F", f"F;{j}")
99
+
100
+
101
+ # --------------------------------------------------------------------
102
+ # Read IM directory
103
+
104
+ split = re.compile(rb"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$")
105
+
106
+
107
+ def number(s: Any) -> float:
108
+ try:
109
+ return int(s)
110
+ except ValueError:
111
+ return float(s)
112
+
113
+
114
+ ##
115
+ # Image plugin for the IFUNC IM file format.
116
+
117
+
118
+ class ImImageFile(ImageFile.ImageFile):
119
+ format = "IM"
120
+ format_description = "IFUNC Image Memory"
121
+ _close_exclusive_fp_after_loading = False
122
+
123
+ def _open(self) -> None:
124
+ # Quick rejection: if there's not an LF among the first
125
+ # 100 bytes, this is (probably) not a text header.
126
+
127
+ if b"\n" not in self.fp.read(100):
128
+ msg = "not an IM file"
129
+ raise SyntaxError(msg)
130
+ self.fp.seek(0)
131
+
132
+ n = 0
133
+
134
+ # Default values
135
+ self.info[MODE] = "L"
136
+ self.info[SIZE] = (512, 512)
137
+ self.info[FRAMES] = 1
138
+
139
+ self.rawmode = "L"
140
+
141
+ while True:
142
+ s = self.fp.read(1)
143
+
144
+ # Some versions of IFUNC uses \n\r instead of \r\n...
145
+ if s == b"\r":
146
+ continue
147
+
148
+ if not s or s == b"\0" or s == b"\x1A":
149
+ break
150
+
151
+ # FIXME: this may read whole file if not a text file
152
+ s = s + self.fp.readline()
153
+
154
+ if len(s) > 100:
155
+ msg = "not an IM file"
156
+ raise SyntaxError(msg)
157
+
158
+ if s[-2:] == b"\r\n":
159
+ s = s[:-2]
160
+ elif s[-1:] == b"\n":
161
+ s = s[:-1]
162
+
163
+ try:
164
+ m = split.match(s)
165
+ except re.error as e:
166
+ msg = "not an IM file"
167
+ raise SyntaxError(msg) from e
168
+
169
+ if m:
170
+ k, v = m.group(1, 2)
171
+
172
+ # Don't know if this is the correct encoding,
173
+ # but a decent guess (I guess)
174
+ k = k.decode("latin-1", "replace")
175
+ v = v.decode("latin-1", "replace")
176
+
177
+ # Convert value as appropriate
178
+ if k in [FRAMES, SCALE, SIZE]:
179
+ v = v.replace("*", ",")
180
+ v = tuple(map(number, v.split(",")))
181
+ if len(v) == 1:
182
+ v = v[0]
183
+ elif k == MODE and v in OPEN:
184
+ v, self.rawmode = OPEN[v]
185
+
186
+ # Add to dictionary. Note that COMMENT tags are
187
+ # combined into a list of strings.
188
+ if k == COMMENT:
189
+ if k in self.info:
190
+ self.info[k].append(v)
191
+ else:
192
+ self.info[k] = [v]
193
+ else:
194
+ self.info[k] = v
195
+
196
+ if k in TAGS:
197
+ n += 1
198
+
199
+ else:
200
+ msg = f"Syntax error in IM header: {s.decode('ascii', 'replace')}"
201
+ raise SyntaxError(msg)
202
+
203
+ if not n:
204
+ msg = "Not an IM file"
205
+ raise SyntaxError(msg)
206
+
207
+ # Basic attributes
208
+ self._size = self.info[SIZE]
209
+ self._mode = self.info[MODE]
210
+
211
+ # Skip forward to start of image data
212
+ while s and s[:1] != b"\x1A":
213
+ s = self.fp.read(1)
214
+ if not s:
215
+ msg = "File truncated"
216
+ raise SyntaxError(msg)
217
+
218
+ if LUT in self.info:
219
+ # convert lookup table to palette or lut attribute
220
+ palette = self.fp.read(768)
221
+ greyscale = 1 # greyscale palette
222
+ linear = 1 # linear greyscale palette
223
+ for i in range(256):
224
+ if palette[i] == palette[i + 256] == palette[i + 512]:
225
+ if palette[i] != i:
226
+ linear = 0
227
+ else:
228
+ greyscale = 0
229
+ if self.mode in ["L", "LA", "P", "PA"]:
230
+ if greyscale:
231
+ if not linear:
232
+ self.lut = list(palette[:256])
233
+ else:
234
+ if self.mode in ["L", "P"]:
235
+ self._mode = self.rawmode = "P"
236
+ elif self.mode in ["LA", "PA"]:
237
+ self._mode = "PA"
238
+ self.rawmode = "PA;L"
239
+ self.palette = ImagePalette.raw("RGB;L", palette)
240
+ elif self.mode == "RGB":
241
+ if not greyscale or not linear:
242
+ self.lut = list(palette)
243
+
244
+ self.frame = 0
245
+
246
+ self.__offset = offs = self.fp.tell()
247
+
248
+ self._fp = self.fp # FIXME: hack
249
+
250
+ if self.rawmode[:2] == "F;":
251
+ # ifunc95 formats
252
+ try:
253
+ # use bit decoder (if necessary)
254
+ bits = int(self.rawmode[2:])
255
+ if bits not in [8, 16, 32]:
256
+ self.tile = [("bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1))]
257
+ return
258
+ except ValueError:
259
+ pass
260
+
261
+ if self.rawmode in ["RGB;T", "RYB;T"]:
262
+ # Old LabEye/3PC files. Would be very surprised if anyone
263
+ # ever stumbled upon such a file ;-)
264
+ size = self.size[0] * self.size[1]
265
+ self.tile = [
266
+ ("raw", (0, 0) + self.size, offs, ("G", 0, -1)),
267
+ ("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),
268
+ ("raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)),
269
+ ]
270
+ else:
271
+ # LabEye/IFUNC files
272
+ self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
273
+
274
+ @property
275
+ def n_frames(self) -> int:
276
+ return self.info[FRAMES]
277
+
278
+ @property
279
+ def is_animated(self) -> bool:
280
+ return self.info[FRAMES] > 1
281
+
282
+ def seek(self, frame: int) -> None:
283
+ if not self._seek_check(frame):
284
+ return
285
+
286
+ self.frame = frame
287
+
288
+ if self.mode == "1":
289
+ bits = 1
290
+ else:
291
+ bits = 8 * len(self.mode)
292
+
293
+ size = ((self.size[0] * bits + 7) // 8) * self.size[1]
294
+ offs = self.__offset + frame * size
295
+
296
+ self.fp = self._fp
297
+
298
+ self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
299
+
300
+ def tell(self) -> int:
301
+ return self.frame
302
+
303
+
304
+ #
305
+ # --------------------------------------------------------------------
306
+ # Save IM files
307
+
308
+
309
+ SAVE = {
310
+ # mode: (im type, raw mode)
311
+ "1": ("0 1", "1"),
312
+ "L": ("Greyscale", "L"),
313
+ "LA": ("LA", "LA;L"),
314
+ "P": ("Greyscale", "P"),
315
+ "PA": ("LA", "PA;L"),
316
+ "I": ("L 32S", "I;32S"),
317
+ "I;16": ("L 16", "I;16"),
318
+ "I;16L": ("L 16L", "I;16L"),
319
+ "I;16B": ("L 16B", "I;16B"),
320
+ "F": ("L 32F", "F;32F"),
321
+ "RGB": ("RGB", "RGB;L"),
322
+ "RGBA": ("RGBA", "RGBA;L"),
323
+ "RGBX": ("RGBX", "RGBX;L"),
324
+ "CMYK": ("CMYK", "CMYK;L"),
325
+ "YCbCr": ("YCC", "YCbCr;L"),
326
+ }
327
+
328
+
329
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
330
+ try:
331
+ image_type, rawmode = SAVE[im.mode]
332
+ except KeyError as e:
333
+ msg = f"Cannot save {im.mode} images as IM"
334
+ raise ValueError(msg) from e
335
+
336
+ frames = im.encoderinfo.get("frames", 1)
337
+
338
+ fp.write(f"Image type: {image_type} image\r\n".encode("ascii"))
339
+ if filename:
340
+ # Each line must be 100 characters or less,
341
+ # or: SyntaxError("not an IM file")
342
+ # 8 characters are used for "Name: " and "\r\n"
343
+ # Keep just the filename, ditch the potentially overlong path
344
+ if isinstance(filename, bytes):
345
+ filename = filename.decode("ascii")
346
+ name, ext = os.path.splitext(os.path.basename(filename))
347
+ name = "".join([name[: 92 - len(ext)], ext])
348
+
349
+ fp.write(f"Name: {name}\r\n".encode("ascii"))
350
+ fp.write(("Image size (x*y): %d*%d\r\n" % im.size).encode("ascii"))
351
+ fp.write(f"File size (no of images): {frames}\r\n".encode("ascii"))
352
+ if im.mode in ["P", "PA"]:
353
+ fp.write(b"Lut: 1\r\n")
354
+ fp.write(b"\000" * (511 - fp.tell()) + b"\032")
355
+ if im.mode in ["P", "PA"]:
356
+ im_palette = im.im.getpalette("RGB", "RGB;L")
357
+ colors = len(im_palette) // 3
358
+ palette = b""
359
+ for i in range(3):
360
+ palette += im_palette[colors * i : colors * (i + 1)]
361
+ palette += b"\x00" * (256 - colors)
362
+ fp.write(palette) # 768 bytes
363
+ ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))])
364
+
365
+
366
+ #
367
+ # --------------------------------------------------------------------
368
+ # Registry
369
+
370
+
371
+ Image.register_open(ImImageFile.format, ImImageFile)
372
+ Image.register_save(ImImageFile.format, _save)
373
+
374
+ Image.register_extension(ImImageFile.format, ".im")
evalkit_tf437/lib/python3.10/site-packages/PIL/ImageCms.py ADDED
@@ -0,0 +1,1127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The Python Imaging Library.
2
+ # $Id$
3
+
4
+ # Optional color management support, based on Kevin Cazabon's PyCMS
5
+ # library.
6
+
7
+ # Originally released under LGPL. Graciously donated to PIL in
8
+ # March 2009, for distribution under the standard PIL license
9
+
10
+ # History:
11
+
12
+ # 2009-03-08 fl Added to PIL.
13
+
14
+ # Copyright (C) 2002-2003 Kevin Cazabon
15
+ # Copyright (c) 2009 by Fredrik Lundh
16
+ # Copyright (c) 2013 by Eric Soroos
17
+
18
+ # See the README file for information on usage and redistribution. See
19
+ # below for the original description.
20
+ from __future__ import annotations
21
+
22
+ import operator
23
+ import sys
24
+ from enum import IntEnum, IntFlag
25
+ from functools import reduce
26
+ from typing import Any, Literal, SupportsFloat, SupportsInt, Union
27
+
28
+ from . import Image, __version__
29
+ from ._deprecate import deprecate
30
+ from ._typing import SupportsRead
31
+
32
+ try:
33
+ from . import _imagingcms as core
34
+ except ImportError as ex:
35
+ # Allow error import for doc purposes, but error out when accessing
36
+ # anything in core.
37
+ from ._util import DeferredError
38
+
39
+ core = DeferredError.new(ex)
40
+
41
+ _DESCRIPTION = """
42
+ pyCMS
43
+
44
+ a Python / PIL interface to the littleCMS ICC Color Management System
45
+ Copyright (C) 2002-2003 Kevin Cazabon
46
+ kevin@cazabon.com
47
+ https://www.cazabon.com
48
+
49
+ pyCMS home page: https://www.cazabon.com/pyCMS
50
+ littleCMS home page: https://www.littlecms.com
51
+ (littleCMS is Copyright (C) 1998-2001 Marti Maria)
52
+
53
+ Originally released under LGPL. Graciously donated to PIL in
54
+ March 2009, for distribution under the standard PIL license
55
+
56
+ The pyCMS.py module provides a "clean" interface between Python/PIL and
57
+ pyCMSdll, taking care of some of the more complex handling of the direct
58
+ pyCMSdll functions, as well as error-checking and making sure that all
59
+ relevant data is kept together.
60
+
61
+ While it is possible to call pyCMSdll functions directly, it's not highly
62
+ recommended.
63
+
64
+ Version History:
65
+
66
+ 1.0.0 pil Oct 2013 Port to LCMS 2.
67
+
68
+ 0.1.0 pil mod March 10, 2009
69
+
70
+ Renamed display profile to proof profile. The proof
71
+ profile is the profile of the device that is being
72
+ simulated, not the profile of the device which is
73
+ actually used to display/print the final simulation
74
+ (that'd be the output profile) - also see LCMSAPI.txt
75
+ input colorspace -> using 'renderingIntent' -> proof
76
+ colorspace -> using 'proofRenderingIntent' -> output
77
+ colorspace
78
+
79
+ Added LCMS FLAGS support.
80
+ Added FLAGS["SOFTPROOFING"] as default flag for
81
+ buildProofTransform (otherwise the proof profile/intent
82
+ would be ignored).
83
+
84
+ 0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms
85
+
86
+ 0.0.2 alpha Jan 6, 2002
87
+
88
+ Added try/except statements around type() checks of
89
+ potential CObjects... Python won't let you use type()
90
+ on them, and raises a TypeError (stupid, if you ask
91
+ me!)
92
+
93
+ Added buildProofTransformFromOpenProfiles() function.
94
+ Additional fixes in DLL, see DLL code for details.
95
+
96
+ 0.0.1 alpha first public release, Dec. 26, 2002
97
+
98
+ Known to-do list with current version (of Python interface, not pyCMSdll):
99
+
100
+ none
101
+
102
+ """
103
+
104
+ _VERSION = "1.0.0 pil"
105
+
106
+
107
+ def __getattr__(name: str) -> Any:
108
+ if name == "DESCRIPTION":
109
+ deprecate("PIL.ImageCms.DESCRIPTION", 12)
110
+ return _DESCRIPTION
111
+ elif name == "VERSION":
112
+ deprecate("PIL.ImageCms.VERSION", 12)
113
+ return _VERSION
114
+ elif name == "FLAGS":
115
+ deprecate("PIL.ImageCms.FLAGS", 12, "PIL.ImageCms.Flags")
116
+ return _FLAGS
117
+ msg = f"module '{__name__}' has no attribute '{name}'"
118
+ raise AttributeError(msg)
119
+
120
+
121
+ # --------------------------------------------------------------------.
122
+
123
+
124
+ #
125
+ # intent/direction values
126
+
127
+
128
+ class Intent(IntEnum):
129
+ PERCEPTUAL = 0
130
+ RELATIVE_COLORIMETRIC = 1
131
+ SATURATION = 2
132
+ ABSOLUTE_COLORIMETRIC = 3
133
+
134
+
135
+ class Direction(IntEnum):
136
+ INPUT = 0
137
+ OUTPUT = 1
138
+ PROOF = 2
139
+
140
+
141
+ #
142
+ # flags
143
+
144
+
145
+ class Flags(IntFlag):
146
+ """Flags and documentation are taken from ``lcms2.h``."""
147
+
148
+ NONE = 0
149
+ NOCACHE = 0x0040
150
+ """Inhibit 1-pixel cache"""
151
+ NOOPTIMIZE = 0x0100
152
+ """Inhibit optimizations"""
153
+ NULLTRANSFORM = 0x0200
154
+ """Don't transform anyway"""
155
+ GAMUTCHECK = 0x1000
156
+ """Out of Gamut alarm"""
157
+ SOFTPROOFING = 0x4000
158
+ """Do softproofing"""
159
+ BLACKPOINTCOMPENSATION = 0x2000
160
+ NOWHITEONWHITEFIXUP = 0x0004
161
+ """Don't fix scum dot"""
162
+ HIGHRESPRECALC = 0x0400
163
+ """Use more memory to give better accuracy"""
164
+ LOWRESPRECALC = 0x0800
165
+ """Use less memory to minimize resources"""
166
+ # this should be 8BITS_DEVICELINK, but that is not a valid name in Python:
167
+ USE_8BITS_DEVICELINK = 0x0008
168
+ """Create 8 bits devicelinks"""
169
+ GUESSDEVICECLASS = 0x0020
170
+ """Guess device class (for ``transform2devicelink``)"""
171
+ KEEP_SEQUENCE = 0x0080
172
+ """Keep profile sequence for devicelink creation"""
173
+ FORCE_CLUT = 0x0002
174
+ """Force CLUT optimization"""
175
+ CLUT_POST_LINEARIZATION = 0x0001
176
+ """create postlinearization tables if possible"""
177
+ CLUT_PRE_LINEARIZATION = 0x0010
178
+ """create prelinearization tables if possible"""
179
+ NONEGATIVES = 0x8000
180
+ """Prevent negative numbers in floating point transforms"""
181
+ COPY_ALPHA = 0x04000000
182
+ """Alpha channels are copied on ``cmsDoTransform()``"""
183
+ NODEFAULTRESOURCEDEF = 0x01000000
184
+
185
+ _GRIDPOINTS_1 = 1 << 16
186
+ _GRIDPOINTS_2 = 2 << 16
187
+ _GRIDPOINTS_4 = 4 << 16
188
+ _GRIDPOINTS_8 = 8 << 16
189
+ _GRIDPOINTS_16 = 16 << 16
190
+ _GRIDPOINTS_32 = 32 << 16
191
+ _GRIDPOINTS_64 = 64 << 16
192
+ _GRIDPOINTS_128 = 128 << 16
193
+
194
+ @staticmethod
195
+ def GRIDPOINTS(n: int) -> Flags:
196
+ """
197
+ Fine-tune control over number of gridpoints
198
+
199
+ :param n: :py:class:`int` in range ``0 <= n <= 255``
200
+ """
201
+ return Flags.NONE | ((n & 0xFF) << 16)
202
+
203
+
204
+ _MAX_FLAG = reduce(operator.or_, Flags)
205
+
206
+
207
+ _FLAGS = {
208
+ "MATRIXINPUT": 1,
209
+ "MATRIXOUTPUT": 2,
210
+ "MATRIXONLY": (1 | 2),
211
+ "NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
212
+ # Don't create prelinearization tables on precalculated transforms
213
+ # (internal use):
214
+ "NOPRELINEARIZATION": 16,
215
+ "GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
216
+ "NOTCACHE": 64, # Inhibit 1-pixel cache
217
+ "NOTPRECALC": 256,
218
+ "NULLTRANSFORM": 512, # Don't transform anyway
219
+ "HIGHRESPRECALC": 1024, # Use more memory to give better accuracy
220
+ "LOWRESPRECALC": 2048, # Use less memory to minimize resources
221
+ "WHITEBLACKCOMPENSATION": 8192,
222
+ "BLACKPOINTCOMPENSATION": 8192,
223
+ "GAMUTCHECK": 4096, # Out of Gamut alarm
224
+ "SOFTPROOFING": 16384, # Do softproofing
225
+ "PRESERVEBLACK": 32768, # Black preservation
226
+ "NODEFAULTRESOURCEDEF": 16777216, # CRD special
227
+ "GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints
228
+ }
229
+
230
+
231
+ # --------------------------------------------------------------------.
232
+ # Experimental PIL-level API
233
+ # --------------------------------------------------------------------.
234
+
235
+ ##
236
+ # Profile.
237
+
238
+
239
+ class ImageCmsProfile:
240
+ def __init__(self, profile: str | SupportsRead[bytes] | core.CmsProfile) -> None:
241
+ """
242
+ :param profile: Either a string representing a filename,
243
+ a file like object containing a profile or a
244
+ low-level profile object
245
+
246
+ """
247
+
248
+ if isinstance(profile, str):
249
+ if sys.platform == "win32":
250
+ profile_bytes_path = profile.encode()
251
+ try:
252
+ profile_bytes_path.decode("ascii")
253
+ except UnicodeDecodeError:
254
+ with open(profile, "rb") as f:
255
+ self._set(core.profile_frombytes(f.read()))
256
+ return
257
+ self._set(core.profile_open(profile), profile)
258
+ elif hasattr(profile, "read"):
259
+ self._set(core.profile_frombytes(profile.read()))
260
+ elif isinstance(profile, core.CmsProfile):
261
+ self._set(profile)
262
+ else:
263
+ msg = "Invalid type for Profile" # type: ignore[unreachable]
264
+ raise TypeError(msg)
265
+
266
+ def _set(self, profile: core.CmsProfile, filename: str | None = None) -> None:
267
+ self.profile = profile
268
+ self.filename = filename
269
+ self.product_name = None # profile.product_name
270
+ self.product_info = None # profile.product_info
271
+
272
+ def tobytes(self) -> bytes:
273
+ """
274
+ Returns the profile in a format suitable for embedding in
275
+ saved images.
276
+
277
+ :returns: a bytes object containing the ICC profile.
278
+ """
279
+
280
+ return core.profile_tobytes(self.profile)
281
+
282
+
283
+ class ImageCmsTransform(Image.ImagePointHandler):
284
+ """
285
+ Transform. This can be used with the procedural API, or with the standard
286
+ :py:func:`~PIL.Image.Image.point` method.
287
+
288
+ Will return the output profile in the ``output.info['icc_profile']``.
289
+ """
290
+
291
+ def __init__(
292
+ self,
293
+ input: ImageCmsProfile,
294
+ output: ImageCmsProfile,
295
+ input_mode: str,
296
+ output_mode: str,
297
+ intent: Intent = Intent.PERCEPTUAL,
298
+ proof: ImageCmsProfile | None = None,
299
+ proof_intent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
300
+ flags: Flags = Flags.NONE,
301
+ ):
302
+ supported_modes = (
303
+ "RGB",
304
+ "RGBA",
305
+ "RGBX",
306
+ "CMYK",
307
+ "I;16",
308
+ "I;16L",
309
+ "I;16B",
310
+ "YCbCr",
311
+ "LAB",
312
+ "L",
313
+ "1",
314
+ )
315
+ for mode in (input_mode, output_mode):
316
+ if mode not in supported_modes:
317
+ deprecate(
318
+ mode,
319
+ 12,
320
+ {
321
+ "L;16": "I;16 or I;16L",
322
+ "L:16B": "I;16B",
323
+ "YCCA": "YCbCr",
324
+ "YCC": "YCbCr",
325
+ }.get(mode),
326
+ )
327
+ if proof is None:
328
+ self.transform = core.buildTransform(
329
+ input.profile, output.profile, input_mode, output_mode, intent, flags
330
+ )
331
+ else:
332
+ self.transform = core.buildProofTransform(
333
+ input.profile,
334
+ output.profile,
335
+ proof.profile,
336
+ input_mode,
337
+ output_mode,
338
+ intent,
339
+ proof_intent,
340
+ flags,
341
+ )
342
+ # Note: inputMode and outputMode are for pyCMS compatibility only
343
+ self.input_mode = self.inputMode = input_mode
344
+ self.output_mode = self.outputMode = output_mode
345
+
346
+ self.output_profile = output
347
+
348
+ def point(self, im: Image.Image) -> Image.Image:
349
+ return self.apply(im)
350
+
351
+ def apply(self, im: Image.Image, imOut: Image.Image | None = None) -> Image.Image:
352
+ im.load()
353
+ if imOut is None:
354
+ imOut = Image.new(self.output_mode, im.size, None)
355
+ self.transform.apply(im.im.id, imOut.im.id)
356
+ imOut.info["icc_profile"] = self.output_profile.tobytes()
357
+ return imOut
358
+
359
+ def apply_in_place(self, im: Image.Image) -> Image.Image:
360
+ im.load()
361
+ if im.mode != self.output_mode:
362
+ msg = "mode mismatch"
363
+ raise ValueError(msg) # wrong output mode
364
+ self.transform.apply(im.im.id, im.im.id)
365
+ im.info["icc_profile"] = self.output_profile.tobytes()
366
+ return im
367
+
368
+
369
+ def get_display_profile(handle: SupportsInt | None = None) -> ImageCmsProfile | None:
370
+ """
371
+ (experimental) Fetches the profile for the current display device.
372
+
373
+ :returns: ``None`` if the profile is not known.
374
+ """
375
+
376
+ if sys.platform != "win32":
377
+ return None
378
+
379
+ from . import ImageWin # type: ignore[unused-ignore, unreachable]
380
+
381
+ if isinstance(handle, ImageWin.HDC):
382
+ profile = core.get_display_profile_win32(int(handle), 1)
383
+ else:
384
+ profile = core.get_display_profile_win32(int(handle or 0))
385
+ if profile is None:
386
+ return None
387
+ return ImageCmsProfile(profile)
388
+
389
+
390
+ # --------------------------------------------------------------------.
391
+ # pyCMS compatible layer
392
+ # --------------------------------------------------------------------.
393
+
394
+ _CmsProfileCompatible = Union[
395
+ str, SupportsRead[bytes], core.CmsProfile, ImageCmsProfile
396
+ ]
397
+
398
+
399
+ class PyCMSError(Exception):
400
+ """(pyCMS) Exception class.
401
+ This is used for all errors in the pyCMS API."""
402
+
403
+ pass
404
+
405
+
406
+ def profileToProfile(
407
+ im: Image.Image,
408
+ inputProfile: _CmsProfileCompatible,
409
+ outputProfile: _CmsProfileCompatible,
410
+ renderingIntent: Intent = Intent.PERCEPTUAL,
411
+ outputMode: str | None = None,
412
+ inPlace: bool = False,
413
+ flags: Flags = Flags.NONE,
414
+ ) -> Image.Image | None:
415
+ """
416
+ (pyCMS) Applies an ICC transformation to a given image, mapping from
417
+ ``inputProfile`` to ``outputProfile``.
418
+
419
+ If the input or output profiles specified are not valid filenames, a
420
+ :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
421
+ ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
422
+ If an error occurs during application of the profiles,
423
+ a :exc:`PyCMSError` will be raised.
424
+ If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
425
+ a :exc:`PyCMSError` will be raised.
426
+
427
+ This function applies an ICC transformation to im from ``inputProfile``'s
428
+ color space to ``outputProfile``'s color space using the specified rendering
429
+ intent to decide how to handle out-of-gamut colors.
430
+
431
+ ``outputMode`` can be used to specify that a color mode conversion is to
432
+ be done using these profiles, but the specified profiles must be able
433
+ to handle that mode. I.e., if converting im from RGB to CMYK using
434
+ profiles, the input profile must handle RGB data, and the output
435
+ profile must handle CMYK data.
436
+
437
+ :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
438
+ or Image.open(...), etc.)
439
+ :param inputProfile: String, as a valid filename path to the ICC input
440
+ profile you wish to use for this image, or a profile object
441
+ :param outputProfile: String, as a valid filename path to the ICC output
442
+ profile you wish to use for this image, or a profile object
443
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
444
+ wish to use for the transform
445
+
446
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
447
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
448
+ ImageCms.Intent.SATURATION = 2
449
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
450
+
451
+ see the pyCMS documentation for details on rendering intents and what
452
+ they do.
453
+ :param outputMode: A valid PIL mode for the output image (i.e. "RGB",
454
+ "CMYK", etc.). Note: if rendering the image "inPlace", outputMode
455
+ MUST be the same mode as the input, or omitted completely. If
456
+ omitted, the outputMode will be the same as the mode of the input
457
+ image (im.mode)
458
+ :param inPlace: Boolean. If ``True``, the original image is modified in-place,
459
+ and ``None`` is returned. If ``False`` (default), a new
460
+ :py:class:`~PIL.Image.Image` object is returned with the transform applied.
461
+ :param flags: Integer (0-...) specifying additional flags
462
+ :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
463
+ the value of ``inPlace``
464
+ :exception PyCMSError:
465
+ """
466
+
467
+ if outputMode is None:
468
+ outputMode = im.mode
469
+
470
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
471
+ msg = "renderingIntent must be an integer between 0 and 3"
472
+ raise PyCMSError(msg)
473
+
474
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
475
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
476
+ raise PyCMSError(msg)
477
+
478
+ try:
479
+ if not isinstance(inputProfile, ImageCmsProfile):
480
+ inputProfile = ImageCmsProfile(inputProfile)
481
+ if not isinstance(outputProfile, ImageCmsProfile):
482
+ outputProfile = ImageCmsProfile(outputProfile)
483
+ transform = ImageCmsTransform(
484
+ inputProfile,
485
+ outputProfile,
486
+ im.mode,
487
+ outputMode,
488
+ renderingIntent,
489
+ flags=flags,
490
+ )
491
+ if inPlace:
492
+ transform.apply_in_place(im)
493
+ imOut = None
494
+ else:
495
+ imOut = transform.apply(im)
496
+ except (OSError, TypeError, ValueError) as v:
497
+ raise PyCMSError(v) from v
498
+
499
+ return imOut
500
+
501
+
502
+ def getOpenProfile(
503
+ profileFilename: str | SupportsRead[bytes] | core.CmsProfile,
504
+ ) -> ImageCmsProfile:
505
+ """
506
+ (pyCMS) Opens an ICC profile file.
507
+
508
+ The PyCMSProfile object can be passed back into pyCMS for use in creating
509
+ transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
510
+
511
+ If ``profileFilename`` is not a valid filename for an ICC profile,
512
+ a :exc:`PyCMSError` will be raised.
513
+
514
+ :param profileFilename: String, as a valid filename path to the ICC profile
515
+ you wish to open, or a file-like object.
516
+ :returns: A CmsProfile class object.
517
+ :exception PyCMSError:
518
+ """
519
+
520
+ try:
521
+ return ImageCmsProfile(profileFilename)
522
+ except (OSError, TypeError, ValueError) as v:
523
+ raise PyCMSError(v) from v
524
+
525
+
526
+ def buildTransform(
527
+ inputProfile: _CmsProfileCompatible,
528
+ outputProfile: _CmsProfileCompatible,
529
+ inMode: str,
530
+ outMode: str,
531
+ renderingIntent: Intent = Intent.PERCEPTUAL,
532
+ flags: Flags = Flags.NONE,
533
+ ) -> ImageCmsTransform:
534
+ """
535
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
536
+ ``outputProfile``. Use applyTransform to apply the transform to a given
537
+ image.
538
+
539
+ If the input or output profiles specified are not valid filenames, a
540
+ :exc:`PyCMSError` will be raised. If an error occurs during creation
541
+ of the transform, a :exc:`PyCMSError` will be raised.
542
+
543
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
544
+ (or by pyCMS), a :exc:`PyCMSError` will be raised.
545
+
546
+ This function builds and returns an ICC transform from the ``inputProfile``
547
+ to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
548
+ with out-of-gamut colors. It will ONLY work for converting images that
549
+ are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
550
+ i.e. "RGB", "RGBA", "CMYK", etc.).
551
+
552
+ Building the transform is a fair part of the overhead in
553
+ ImageCms.profileToProfile(), so if you're planning on converting multiple
554
+ images using the same input/output settings, this can save you time.
555
+ Once you have a transform object, it can be used with
556
+ ImageCms.applyProfile() to convert images without the need to re-compute
557
+ the lookup table for the transform.
558
+
559
+ The reason pyCMS returns a class object rather than a handle directly
560
+ to the transform is that it needs to keep track of the PIL input/output
561
+ modes that the transform is meant for. These attributes are stored in
562
+ the ``inMode`` and ``outMode`` attributes of the object (which can be
563
+ manually overridden if you really want to, but I don't know of any
564
+ time that would be of use, or would even work).
565
+
566
+ :param inputProfile: String, as a valid filename path to the ICC input
567
+ profile you wish to use for this transform, or a profile object
568
+ :param outputProfile: String, as a valid filename path to the ICC output
569
+ profile you wish to use for this transform, or a profile object
570
+ :param inMode: String, as a valid PIL mode that the appropriate profile
571
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
572
+ :param outMode: String, as a valid PIL mode that the appropriate profile
573
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
574
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
575
+ wish to use for the transform
576
+
577
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
578
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
579
+ ImageCms.Intent.SATURATION = 2
580
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
581
+
582
+ see the pyCMS documentation for details on rendering intents and what
583
+ they do.
584
+ :param flags: Integer (0-...) specifying additional flags
585
+ :returns: A CmsTransform class object.
586
+ :exception PyCMSError:
587
+ """
588
+
589
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
590
+ msg = "renderingIntent must be an integer between 0 and 3"
591
+ raise PyCMSError(msg)
592
+
593
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
594
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
595
+ raise PyCMSError(msg)
596
+
597
+ try:
598
+ if not isinstance(inputProfile, ImageCmsProfile):
599
+ inputProfile = ImageCmsProfile(inputProfile)
600
+ if not isinstance(outputProfile, ImageCmsProfile):
601
+ outputProfile = ImageCmsProfile(outputProfile)
602
+ return ImageCmsTransform(
603
+ inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
604
+ )
605
+ except (OSError, TypeError, ValueError) as v:
606
+ raise PyCMSError(v) from v
607
+
608
+
609
+ def buildProofTransform(
610
+ inputProfile: _CmsProfileCompatible,
611
+ outputProfile: _CmsProfileCompatible,
612
+ proofProfile: _CmsProfileCompatible,
613
+ inMode: str,
614
+ outMode: str,
615
+ renderingIntent: Intent = Intent.PERCEPTUAL,
616
+ proofRenderingIntent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
617
+ flags: Flags = Flags.SOFTPROOFING,
618
+ ) -> ImageCmsTransform:
619
+ """
620
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
621
+ ``outputProfile``, but tries to simulate the result that would be
622
+ obtained on the ``proofProfile`` device.
623
+
624
+ If the input, output, or proof profiles specified are not valid
625
+ filenames, a :exc:`PyCMSError` will be raised.
626
+
627
+ If an error occurs during creation of the transform,
628
+ a :exc:`PyCMSError` will be raised.
629
+
630
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
631
+ (or by pyCMS), a :exc:`PyCMSError` will be raised.
632
+
633
+ This function builds and returns an ICC transform from the ``inputProfile``
634
+ to the ``outputProfile``, but tries to simulate the result that would be
635
+ obtained on the ``proofProfile`` device using ``renderingIntent`` and
636
+ ``proofRenderingIntent`` to determine what to do with out-of-gamut
637
+ colors. This is known as "soft-proofing". It will ONLY work for
638
+ converting images that are in ``inMode`` to images that are in outMode
639
+ color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
640
+
641
+ Usage of the resulting transform object is exactly the same as with
642
+ ImageCms.buildTransform().
643
+
644
+ Proof profiling is generally used when using an output device to get a
645
+ good idea of what the final printed/displayed image would look like on
646
+ the ``proofProfile`` device when it's quicker and easier to use the
647
+ output device for judging color. Generally, this means that the
648
+ output device is a monitor, or a dye-sub printer (etc.), and the simulated
649
+ device is something more expensive, complicated, or time consuming
650
+ (making it difficult to make a real print for color judgement purposes).
651
+
652
+ Soft-proofing basically functions by adjusting the colors on the
653
+ output device to match the colors of the device being simulated. However,
654
+ when the simulated device has a much wider gamut than the output
655
+ device, you may obtain marginal results.
656
+
657
+ :param inputProfile: String, as a valid filename path to the ICC input
658
+ profile you wish to use for this transform, or a profile object
659
+ :param outputProfile: String, as a valid filename path to the ICC output
660
+ (monitor, usually) profile you wish to use for this transform, or a
661
+ profile object
662
+ :param proofProfile: String, as a valid filename path to the ICC proof
663
+ profile you wish to use for this transform, or a profile object
664
+ :param inMode: String, as a valid PIL mode that the appropriate profile
665
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
666
+ :param outMode: String, as a valid PIL mode that the appropriate profile
667
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
668
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
669
+ wish to use for the input->proof (simulated) transform
670
+
671
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
672
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
673
+ ImageCms.Intent.SATURATION = 2
674
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
675
+
676
+ see the pyCMS documentation for details on rendering intents and what
677
+ they do.
678
+ :param proofRenderingIntent: Integer (0-3) specifying the rendering intent
679
+ you wish to use for proof->output transform
680
+
681
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
682
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
683
+ ImageCms.Intent.SATURATION = 2
684
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
685
+
686
+ see the pyCMS documentation for details on rendering intents and what
687
+ they do.
688
+ :param flags: Integer (0-...) specifying additional flags
689
+ :returns: A CmsTransform class object.
690
+ :exception PyCMSError:
691
+ """
692
+
693
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
694
+ msg = "renderingIntent must be an integer between 0 and 3"
695
+ raise PyCMSError(msg)
696
+
697
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
698
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
699
+ raise PyCMSError(msg)
700
+
701
+ try:
702
+ if not isinstance(inputProfile, ImageCmsProfile):
703
+ inputProfile = ImageCmsProfile(inputProfile)
704
+ if not isinstance(outputProfile, ImageCmsProfile):
705
+ outputProfile = ImageCmsProfile(outputProfile)
706
+ if not isinstance(proofProfile, ImageCmsProfile):
707
+ proofProfile = ImageCmsProfile(proofProfile)
708
+ return ImageCmsTransform(
709
+ inputProfile,
710
+ outputProfile,
711
+ inMode,
712
+ outMode,
713
+ renderingIntent,
714
+ proofProfile,
715
+ proofRenderingIntent,
716
+ flags,
717
+ )
718
+ except (OSError, TypeError, ValueError) as v:
719
+ raise PyCMSError(v) from v
720
+
721
+
722
+ buildTransformFromOpenProfiles = buildTransform
723
+ buildProofTransformFromOpenProfiles = buildProofTransform
724
+
725
+
726
+ def applyTransform(
727
+ im: Image.Image, transform: ImageCmsTransform, inPlace: bool = False
728
+ ) -> Image.Image | None:
729
+ """
730
+ (pyCMS) Applies a transform to a given image.
731
+
732
+ If ``im.mode != transform.input_mode``, a :exc:`PyCMSError` is raised.
733
+
734
+ If ``inPlace`` is ``True`` and ``transform.input_mode != transform.output_mode``, a
735
+ :exc:`PyCMSError` is raised.
736
+
737
+ If ``im.mode``, ``transform.input_mode`` or ``transform.output_mode`` is not
738
+ supported by pyCMSdll or the profiles you used for the transform, a
739
+ :exc:`PyCMSError` is raised.
740
+
741
+ If an error occurs while the transform is being applied,
742
+ a :exc:`PyCMSError` is raised.
743
+
744
+ This function applies a pre-calculated transform (from
745
+ ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
746
+ to an image. The transform can be used for multiple images, saving
747
+ considerable calculation time if doing the same conversion multiple times.
748
+
749
+ If you want to modify im in-place instead of receiving a new image as
750
+ the return value, set ``inPlace`` to ``True``. This can only be done if
751
+ ``transform.input_mode`` and ``transform.output_mode`` are the same, because we
752
+ can't change the mode in-place (the buffer sizes for some modes are
753
+ different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
754
+ object of the same dimensions in mode ``transform.output_mode``.
755
+
756
+ :param im: An :py:class:`~PIL.Image.Image` object, and ``im.mode`` must be the same
757
+ as the ``input_mode`` supported by the transform.
758
+ :param transform: A valid CmsTransform class object
759
+ :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
760
+ returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
761
+ transform applied is returned (and ``im`` is not changed). The default is
762
+ ``False``.
763
+ :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
764
+ depending on the value of ``inPlace``. The profile will be returned in
765
+ the image's ``info['icc_profile']``.
766
+ :exception PyCMSError:
767
+ """
768
+
769
+ try:
770
+ if inPlace:
771
+ transform.apply_in_place(im)
772
+ imOut = None
773
+ else:
774
+ imOut = transform.apply(im)
775
+ except (TypeError, ValueError) as v:
776
+ raise PyCMSError(v) from v
777
+
778
+ return imOut
779
+
780
+
781
+ def createProfile(
782
+ colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = 0
783
+ ) -> core.CmsProfile:
784
+ """
785
+ (pyCMS) Creates a profile.
786
+
787
+ If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
788
+ a :exc:`PyCMSError` is raised.
789
+
790
+ If using LAB and ``colorTemp`` is not a positive integer,
791
+ a :exc:`PyCMSError` is raised.
792
+
793
+ If an error occurs while creating the profile,
794
+ a :exc:`PyCMSError` is raised.
795
+
796
+ Use this function to create common profiles on-the-fly instead of
797
+ having to supply a profile on disk and knowing the path to it. It
798
+ returns a normal CmsProfile object that can be passed to
799
+ ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
800
+ to images.
801
+
802
+ :param colorSpace: String, the color space of the profile you wish to
803
+ create.
804
+ Currently only "LAB", "XYZ", and "sRGB" are supported.
805
+ :param colorTemp: Positive number for the white point for the profile, in
806
+ degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
807
+ illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
808
+ profiles, and is ignored for XYZ and sRGB.
809
+ :returns: A CmsProfile class object
810
+ :exception PyCMSError:
811
+ """
812
+
813
+ if colorSpace not in ["LAB", "XYZ", "sRGB"]:
814
+ msg = (
815
+ f"Color space not supported for on-the-fly profile creation ({colorSpace})"
816
+ )
817
+ raise PyCMSError(msg)
818
+
819
+ if colorSpace == "LAB":
820
+ try:
821
+ colorTemp = float(colorTemp)
822
+ except (TypeError, ValueError) as e:
823
+ msg = f'Color temperature must be numeric, "{colorTemp}" not valid'
824
+ raise PyCMSError(msg) from e
825
+
826
+ try:
827
+ return core.createProfile(colorSpace, colorTemp)
828
+ except (TypeError, ValueError) as v:
829
+ raise PyCMSError(v) from v
830
+
831
+
832
+ def getProfileName(profile: _CmsProfileCompatible) -> str:
833
+ """
834
+
835
+ (pyCMS) Gets the internal product name for the given profile.
836
+
837
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
838
+ a :exc:`PyCMSError` is raised If an error occurs while trying
839
+ to obtain the name tag, a :exc:`PyCMSError` is raised.
840
+
841
+ Use this function to obtain the INTERNAL name of the profile (stored
842
+ in an ICC tag in the profile itself), usually the one used when the
843
+ profile was originally created. Sometimes this tag also contains
844
+ additional information supplied by the creator.
845
+
846
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
847
+ filename of an ICC profile.
848
+ :returns: A string containing the internal name of the profile as stored
849
+ in an ICC tag.
850
+ :exception PyCMSError:
851
+ """
852
+
853
+ try:
854
+ # add an extra newline to preserve pyCMS compatibility
855
+ if not isinstance(profile, ImageCmsProfile):
856
+ profile = ImageCmsProfile(profile)
857
+ # do it in python, not c.
858
+ # // name was "%s - %s" (model, manufacturer) || Description ,
859
+ # // but if the Model and Manufacturer were the same or the model
860
+ # // was long, Just the model, in 1.x
861
+ model = profile.profile.model
862
+ manufacturer = profile.profile.manufacturer
863
+
864
+ if not (model or manufacturer):
865
+ return (profile.profile.profile_description or "") + "\n"
866
+ if not manufacturer or (model and len(model) > 30):
867
+ return f"{model}\n"
868
+ return f"{model} - {manufacturer}\n"
869
+
870
+ except (AttributeError, OSError, TypeError, ValueError) as v:
871
+ raise PyCMSError(v) from v
872
+
873
+
874
+ def getProfileInfo(profile: _CmsProfileCompatible) -> str:
875
+ """
876
+ (pyCMS) Gets the internal product information for the given profile.
877
+
878
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
879
+ a :exc:`PyCMSError` is raised.
880
+
881
+ If an error occurs while trying to obtain the info tag,
882
+ a :exc:`PyCMSError` is raised.
883
+
884
+ Use this function to obtain the information stored in the profile's
885
+ info tag. This often contains details about the profile, and how it
886
+ was created, as supplied by the creator.
887
+
888
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
889
+ filename of an ICC profile.
890
+ :returns: A string containing the internal profile information stored in
891
+ an ICC tag.
892
+ :exception PyCMSError:
893
+ """
894
+
895
+ try:
896
+ if not isinstance(profile, ImageCmsProfile):
897
+ profile = ImageCmsProfile(profile)
898
+ # add an extra newline to preserve pyCMS compatibility
899
+ # Python, not C. the white point bits weren't working well,
900
+ # so skipping.
901
+ # info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
902
+ description = profile.profile.profile_description
903
+ cpright = profile.profile.copyright
904
+ elements = [element for element in (description, cpright) if element]
905
+ return "\r\n\r\n".join(elements) + "\r\n\r\n"
906
+
907
+ except (AttributeError, OSError, TypeError, ValueError) as v:
908
+ raise PyCMSError(v) from v
909
+
910
+
911
+ def getProfileCopyright(profile: _CmsProfileCompatible) -> str:
912
+ """
913
+ (pyCMS) Gets the copyright for the given profile.
914
+
915
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
916
+ :exc:`PyCMSError` is raised.
917
+
918
+ If an error occurs while trying to obtain the copyright tag,
919
+ a :exc:`PyCMSError` is raised.
920
+
921
+ Use this function to obtain the information stored in the profile's
922
+ copyright tag.
923
+
924
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
925
+ filename of an ICC profile.
926
+ :returns: A string containing the internal profile information stored in
927
+ an ICC tag.
928
+ :exception PyCMSError:
929
+ """
930
+ try:
931
+ # add an extra newline to preserve pyCMS compatibility
932
+ if not isinstance(profile, ImageCmsProfile):
933
+ profile = ImageCmsProfile(profile)
934
+ return (profile.profile.copyright or "") + "\n"
935
+ except (AttributeError, OSError, TypeError, ValueError) as v:
936
+ raise PyCMSError(v) from v
937
+
938
+
939
+ def getProfileManufacturer(profile: _CmsProfileCompatible) -> str:
940
+ """
941
+ (pyCMS) Gets the manufacturer for the given profile.
942
+
943
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
944
+ :exc:`PyCMSError` is raised.
945
+
946
+ If an error occurs while trying to obtain the manufacturer tag, a
947
+ :exc:`PyCMSError` is raised.
948
+
949
+ Use this function to obtain the information stored in the profile's
950
+ manufacturer tag.
951
+
952
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
953
+ filename of an ICC profile.
954
+ :returns: A string containing the internal profile information stored in
955
+ an ICC tag.
956
+ :exception PyCMSError:
957
+ """
958
+ try:
959
+ # add an extra newline to preserve pyCMS compatibility
960
+ if not isinstance(profile, ImageCmsProfile):
961
+ profile = ImageCmsProfile(profile)
962
+ return (profile.profile.manufacturer or "") + "\n"
963
+ except (AttributeError, OSError, TypeError, ValueError) as v:
964
+ raise PyCMSError(v) from v
965
+
966
+
967
+ def getProfileModel(profile: _CmsProfileCompatible) -> str:
968
+ """
969
+ (pyCMS) Gets the model for the given profile.
970
+
971
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
972
+ :exc:`PyCMSError` is raised.
973
+
974
+ If an error occurs while trying to obtain the model tag,
975
+ a :exc:`PyCMSError` is raised.
976
+
977
+ Use this function to obtain the information stored in the profile's
978
+ model tag.
979
+
980
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
981
+ filename of an ICC profile.
982
+ :returns: A string containing the internal profile information stored in
983
+ an ICC tag.
984
+ :exception PyCMSError:
985
+ """
986
+
987
+ try:
988
+ # add an extra newline to preserve pyCMS compatibility
989
+ if not isinstance(profile, ImageCmsProfile):
990
+ profile = ImageCmsProfile(profile)
991
+ return (profile.profile.model or "") + "\n"
992
+ except (AttributeError, OSError, TypeError, ValueError) as v:
993
+ raise PyCMSError(v) from v
994
+
995
+
996
+ def getProfileDescription(profile: _CmsProfileCompatible) -> str:
997
+ """
998
+ (pyCMS) Gets the description for the given profile.
999
+
1000
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
1001
+ :exc:`PyCMSError` is raised.
1002
+
1003
+ If an error occurs while trying to obtain the description tag,
1004
+ a :exc:`PyCMSError` is raised.
1005
+
1006
+ Use this function to obtain the information stored in the profile's
1007
+ description tag.
1008
+
1009
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
1010
+ filename of an ICC profile.
1011
+ :returns: A string containing the internal profile information stored in an
1012
+ ICC tag.
1013
+ :exception PyCMSError:
1014
+ """
1015
+
1016
+ try:
1017
+ # add an extra newline to preserve pyCMS compatibility
1018
+ if not isinstance(profile, ImageCmsProfile):
1019
+ profile = ImageCmsProfile(profile)
1020
+ return (profile.profile.profile_description or "") + "\n"
1021
+ except (AttributeError, OSError, TypeError, ValueError) as v:
1022
+ raise PyCMSError(v) from v
1023
+
1024
+
1025
+ def getDefaultIntent(profile: _CmsProfileCompatible) -> int:
1026
+ """
1027
+ (pyCMS) Gets the default intent name for the given profile.
1028
+
1029
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
1030
+ :exc:`PyCMSError` is raised.
1031
+
1032
+ If an error occurs while trying to obtain the default intent, a
1033
+ :exc:`PyCMSError` is raised.
1034
+
1035
+ Use this function to determine the default (and usually best optimized)
1036
+ rendering intent for this profile. Most profiles support multiple
1037
+ rendering intents, but are intended mostly for one type of conversion.
1038
+ If you wish to use a different intent than returned, use
1039
+ ImageCms.isIntentSupported() to verify it will work first.
1040
+
1041
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
1042
+ filename of an ICC profile.
1043
+ :returns: Integer 0-3 specifying the default rendering intent for this
1044
+ profile.
1045
+
1046
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
1047
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
1048
+ ImageCms.Intent.SATURATION = 2
1049
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
1050
+
1051
+ see the pyCMS documentation for details on rendering intents and what
1052
+ they do.
1053
+ :exception PyCMSError:
1054
+ """
1055
+
1056
+ try:
1057
+ if not isinstance(profile, ImageCmsProfile):
1058
+ profile = ImageCmsProfile(profile)
1059
+ return profile.profile.rendering_intent
1060
+ except (AttributeError, OSError, TypeError, ValueError) as v:
1061
+ raise PyCMSError(v) from v
1062
+
1063
+
1064
+ def isIntentSupported(
1065
+ profile: _CmsProfileCompatible, intent: Intent, direction: Direction
1066
+ ) -> Literal[-1, 1]:
1067
+ """
1068
+ (pyCMS) Checks if a given intent is supported.
1069
+
1070
+ Use this function to verify that you can use your desired
1071
+ ``intent`` with ``profile``, and that ``profile`` can be used for the
1072
+ input/output/proof profile as you desire.
1073
+
1074
+ Some profiles are created specifically for one "direction", can cannot
1075
+ be used for others. Some profiles can only be used for certain
1076
+ rendering intents, so it's best to either verify this before trying
1077
+ to create a transform with them (using this function), or catch the
1078
+ potential :exc:`PyCMSError` that will occur if they don't
1079
+ support the modes you select.
1080
+
1081
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
1082
+ filename of an ICC profile.
1083
+ :param intent: Integer (0-3) specifying the rendering intent you wish to
1084
+ use with this profile
1085
+
1086
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
1087
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
1088
+ ImageCms.Intent.SATURATION = 2
1089
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
1090
+
1091
+ see the pyCMS documentation for details on rendering intents and what
1092
+ they do.
1093
+ :param direction: Integer specifying if the profile is to be used for
1094
+ input, output, or proof
1095
+
1096
+ INPUT = 0 (or use ImageCms.Direction.INPUT)
1097
+ OUTPUT = 1 (or use ImageCms.Direction.OUTPUT)
1098
+ PROOF = 2 (or use ImageCms.Direction.PROOF)
1099
+
1100
+ :returns: 1 if the intent/direction are supported, -1 if they are not.
1101
+ :exception PyCMSError:
1102
+ """
1103
+
1104
+ try:
1105
+ if not isinstance(profile, ImageCmsProfile):
1106
+ profile = ImageCmsProfile(profile)
1107
+ # FIXME: I get different results for the same data w. different
1108
+ # compilers. Bug in LittleCMS or in the binding?
1109
+ if profile.profile.is_intent_supported(intent, direction):
1110
+ return 1
1111
+ else:
1112
+ return -1
1113
+ except (AttributeError, OSError, TypeError, ValueError) as v:
1114
+ raise PyCMSError(v) from v
1115
+
1116
+
1117
+ def versions() -> tuple[str, str | None, str, str]:
1118
+ """
1119
+ (pyCMS) Fetches versions.
1120
+ """
1121
+
1122
+ deprecate(
1123
+ "PIL.ImageCms.versions()",
1124
+ 12,
1125
+ '(PIL.features.version("littlecms2"), sys.version, PIL.__version__)',
1126
+ )
1127
+ return _VERSION, core.littlecms_version, sys.version.split()[0], __version__
evalkit_tf437/lib/python3.10/site-packages/PIL/ImageFilter.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # standard filters
6
+ #
7
+ # History:
8
+ # 1995-11-27 fl Created
9
+ # 2002-06-08 fl Added rank and mode filters
10
+ # 2003-09-15 fl Fixed rank calculation in rank filter; added expand call
11
+ #
12
+ # Copyright (c) 1997-2003 by Secret Labs AB.
13
+ # Copyright (c) 1995-2002 by Fredrik Lundh.
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ from __future__ import annotations
18
+
19
+ import abc
20
+ import functools
21
+ from types import ModuleType
22
+ from typing import TYPE_CHECKING, Any, Callable, Sequence, cast
23
+
24
+ if TYPE_CHECKING:
25
+ from . import _imaging
26
+ from ._typing import NumpyArray
27
+
28
+
29
+ class Filter:
30
+ @abc.abstractmethod
31
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
32
+ pass
33
+
34
+
35
+ class MultibandFilter(Filter):
36
+ pass
37
+
38
+
39
+ class BuiltinFilter(MultibandFilter):
40
+ filterargs: tuple[Any, ...]
41
+
42
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
43
+ if image.mode == "P":
44
+ msg = "cannot filter palette images"
45
+ raise ValueError(msg)
46
+ return image.filter(*self.filterargs)
47
+
48
+
49
+ class Kernel(BuiltinFilter):
50
+ """
51
+ Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating
52
+ point kernels.
53
+
54
+ Kernels can only be applied to "L" and "RGB" images.
55
+
56
+ :param size: Kernel size, given as (width, height). This must be (3,3) or (5,5).
57
+ :param kernel: A sequence containing kernel weights. The kernel will be flipped
58
+ vertically before being applied to the image.
59
+ :param scale: Scale factor. If given, the result for each pixel is divided by this
60
+ value. The default is the sum of the kernel weights.
61
+ :param offset: Offset. If given, this value is added to the result, after it has
62
+ been divided by the scale factor.
63
+ """
64
+
65
+ name = "Kernel"
66
+
67
+ def __init__(
68
+ self,
69
+ size: tuple[int, int],
70
+ kernel: Sequence[float],
71
+ scale: float | None = None,
72
+ offset: float = 0,
73
+ ) -> None:
74
+ if scale is None:
75
+ # default scale is sum of kernel
76
+ scale = functools.reduce(lambda a, b: a + b, kernel)
77
+ if size[0] * size[1] != len(kernel):
78
+ msg = "not enough coefficients in kernel"
79
+ raise ValueError(msg)
80
+ self.filterargs = size, scale, offset, kernel
81
+
82
+
83
+ class RankFilter(Filter):
84
+ """
85
+ Create a rank filter. The rank filter sorts all pixels in
86
+ a window of the given size, and returns the ``rank``'th value.
87
+
88
+ :param size: The kernel size, in pixels.
89
+ :param rank: What pixel value to pick. Use 0 for a min filter,
90
+ ``size * size / 2`` for a median filter, ``size * size - 1``
91
+ for a max filter, etc.
92
+ """
93
+
94
+ name = "Rank"
95
+
96
+ def __init__(self, size: int, rank: int) -> None:
97
+ self.size = size
98
+ self.rank = rank
99
+
100
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
101
+ if image.mode == "P":
102
+ msg = "cannot filter palette images"
103
+ raise ValueError(msg)
104
+ image = image.expand(self.size // 2, self.size // 2)
105
+ return image.rankfilter(self.size, self.rank)
106
+
107
+
108
+ class MedianFilter(RankFilter):
109
+ """
110
+ Create a median filter. Picks the median pixel value in a window with the
111
+ given size.
112
+
113
+ :param size: The kernel size, in pixels.
114
+ """
115
+
116
+ name = "Median"
117
+
118
+ def __init__(self, size: int = 3) -> None:
119
+ self.size = size
120
+ self.rank = size * size // 2
121
+
122
+
123
+ class MinFilter(RankFilter):
124
+ """
125
+ Create a min filter. Picks the lowest pixel value in a window with the
126
+ given size.
127
+
128
+ :param size: The kernel size, in pixels.
129
+ """
130
+
131
+ name = "Min"
132
+
133
+ def __init__(self, size: int = 3) -> None:
134
+ self.size = size
135
+ self.rank = 0
136
+
137
+
138
+ class MaxFilter(RankFilter):
139
+ """
140
+ Create a max filter. Picks the largest pixel value in a window with the
141
+ given size.
142
+
143
+ :param size: The kernel size, in pixels.
144
+ """
145
+
146
+ name = "Max"
147
+
148
+ def __init__(self, size: int = 3) -> None:
149
+ self.size = size
150
+ self.rank = size * size - 1
151
+
152
+
153
+ class ModeFilter(Filter):
154
+ """
155
+ Create a mode filter. Picks the most frequent pixel value in a box with the
156
+ given size. Pixel values that occur only once or twice are ignored; if no
157
+ pixel value occurs more than twice, the original pixel value is preserved.
158
+
159
+ :param size: The kernel size, in pixels.
160
+ """
161
+
162
+ name = "Mode"
163
+
164
+ def __init__(self, size: int = 3) -> None:
165
+ self.size = size
166
+
167
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
168
+ return image.modefilter(self.size)
169
+
170
+
171
+ class GaussianBlur(MultibandFilter):
172
+ """Blurs the image with a sequence of extended box filters, which
173
+ approximates a Gaussian kernel. For details on accuracy see
174
+ <https://www.mia.uni-saarland.de/Publications/gwosdek-ssvm11.pdf>
175
+
176
+ :param radius: Standard deviation of the Gaussian kernel. Either a sequence of two
177
+ numbers for x and y, or a single number for both.
178
+ """
179
+
180
+ name = "GaussianBlur"
181
+
182
+ def __init__(self, radius: float | Sequence[float] = 2) -> None:
183
+ self.radius = radius
184
+
185
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
186
+ xy = self.radius
187
+ if isinstance(xy, (int, float)):
188
+ xy = (xy, xy)
189
+ if xy == (0, 0):
190
+ return image.copy()
191
+ return image.gaussian_blur(xy)
192
+
193
+
194
+ class BoxBlur(MultibandFilter):
195
+ """Blurs the image by setting each pixel to the average value of the pixels
196
+ in a square box extending radius pixels in each direction.
197
+ Supports float radius of arbitrary size. Uses an optimized implementation
198
+ which runs in linear time relative to the size of the image
199
+ for any radius value.
200
+
201
+ :param radius: Size of the box in a direction. Either a sequence of two numbers for
202
+ x and y, or a single number for both.
203
+
204
+ Radius 0 does not blur, returns an identical image.
205
+ Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.
206
+ """
207
+
208
+ name = "BoxBlur"
209
+
210
+ def __init__(self, radius: float | Sequence[float]) -> None:
211
+ xy = radius if isinstance(radius, (tuple, list)) else (radius, radius)
212
+ if xy[0] < 0 or xy[1] < 0:
213
+ msg = "radius must be >= 0"
214
+ raise ValueError(msg)
215
+ self.radius = radius
216
+
217
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
218
+ xy = self.radius
219
+ if isinstance(xy, (int, float)):
220
+ xy = (xy, xy)
221
+ if xy == (0, 0):
222
+ return image.copy()
223
+ return image.box_blur(xy)
224
+
225
+
226
+ class UnsharpMask(MultibandFilter):
227
+ """Unsharp mask filter.
228
+
229
+ See Wikipedia's entry on `digital unsharp masking`_ for an explanation of
230
+ the parameters.
231
+
232
+ :param radius: Blur Radius
233
+ :param percent: Unsharp strength, in percent
234
+ :param threshold: Threshold controls the minimum brightness change that
235
+ will be sharpened
236
+
237
+ .. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
238
+
239
+ """
240
+
241
+ name = "UnsharpMask"
242
+
243
+ def __init__(
244
+ self, radius: float = 2, percent: int = 150, threshold: int = 3
245
+ ) -> None:
246
+ self.radius = radius
247
+ self.percent = percent
248
+ self.threshold = threshold
249
+
250
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
251
+ return image.unsharp_mask(self.radius, self.percent, self.threshold)
252
+
253
+
254
+ class BLUR(BuiltinFilter):
255
+ name = "Blur"
256
+ # fmt: off
257
+ filterargs = (5, 5), 16, 0, (
258
+ 1, 1, 1, 1, 1,
259
+ 1, 0, 0, 0, 1,
260
+ 1, 0, 0, 0, 1,
261
+ 1, 0, 0, 0, 1,
262
+ 1, 1, 1, 1, 1,
263
+ )
264
+ # fmt: on
265
+
266
+
267
+ class CONTOUR(BuiltinFilter):
268
+ name = "Contour"
269
+ # fmt: off
270
+ filterargs = (3, 3), 1, 255, (
271
+ -1, -1, -1,
272
+ -1, 8, -1,
273
+ -1, -1, -1,
274
+ )
275
+ # fmt: on
276
+
277
+
278
+ class DETAIL(BuiltinFilter):
279
+ name = "Detail"
280
+ # fmt: off
281
+ filterargs = (3, 3), 6, 0, (
282
+ 0, -1, 0,
283
+ -1, 10, -1,
284
+ 0, -1, 0,
285
+ )
286
+ # fmt: on
287
+
288
+
289
+ class EDGE_ENHANCE(BuiltinFilter):
290
+ name = "Edge-enhance"
291
+ # fmt: off
292
+ filterargs = (3, 3), 2, 0, (
293
+ -1, -1, -1,
294
+ -1, 10, -1,
295
+ -1, -1, -1,
296
+ )
297
+ # fmt: on
298
+
299
+
300
+ class EDGE_ENHANCE_MORE(BuiltinFilter):
301
+ name = "Edge-enhance More"
302
+ # fmt: off
303
+ filterargs = (3, 3), 1, 0, (
304
+ -1, -1, -1,
305
+ -1, 9, -1,
306
+ -1, -1, -1,
307
+ )
308
+ # fmt: on
309
+
310
+
311
+ class EMBOSS(BuiltinFilter):
312
+ name = "Emboss"
313
+ # fmt: off
314
+ filterargs = (3, 3), 1, 128, (
315
+ -1, 0, 0,
316
+ 0, 1, 0,
317
+ 0, 0, 0,
318
+ )
319
+ # fmt: on
320
+
321
+
322
+ class FIND_EDGES(BuiltinFilter):
323
+ name = "Find Edges"
324
+ # fmt: off
325
+ filterargs = (3, 3), 1, 0, (
326
+ -1, -1, -1,
327
+ -1, 8, -1,
328
+ -1, -1, -1,
329
+ )
330
+ # fmt: on
331
+
332
+
333
+ class SHARPEN(BuiltinFilter):
334
+ name = "Sharpen"
335
+ # fmt: off
336
+ filterargs = (3, 3), 16, 0, (
337
+ -2, -2, -2,
338
+ -2, 32, -2,
339
+ -2, -2, -2,
340
+ )
341
+ # fmt: on
342
+
343
+
344
+ class SMOOTH(BuiltinFilter):
345
+ name = "Smooth"
346
+ # fmt: off
347
+ filterargs = (3, 3), 13, 0, (
348
+ 1, 1, 1,
349
+ 1, 5, 1,
350
+ 1, 1, 1,
351
+ )
352
+ # fmt: on
353
+
354
+
355
+ class SMOOTH_MORE(BuiltinFilter):
356
+ name = "Smooth More"
357
+ # fmt: off
358
+ filterargs = (5, 5), 100, 0, (
359
+ 1, 1, 1, 1, 1,
360
+ 1, 5, 5, 5, 1,
361
+ 1, 5, 44, 5, 1,
362
+ 1, 5, 5, 5, 1,
363
+ 1, 1, 1, 1, 1,
364
+ )
365
+ # fmt: on
366
+
367
+
368
+ class Color3DLUT(MultibandFilter):
369
+ """Three-dimensional color lookup table.
370
+
371
+ Transforms 3-channel pixels using the values of the channels as coordinates
372
+ in the 3D lookup table and interpolating the nearest elements.
373
+
374
+ This method allows you to apply almost any color transformation
375
+ in constant time by using pre-calculated decimated tables.
376
+
377
+ .. versionadded:: 5.2.0
378
+
379
+ :param size: Size of the table. One int or tuple of (int, int, int).
380
+ Minimal size in any dimension is 2, maximum is 65.
381
+ :param table: Flat lookup table. A list of ``channels * size**3``
382
+ float elements or a list of ``size**3`` channels-sized
383
+ tuples with floats. Channels are changed first,
384
+ then first dimension, then second, then third.
385
+ Value 0.0 corresponds lowest value of output, 1.0 highest.
386
+ :param channels: Number of channels in the table. Could be 3 or 4.
387
+ Default is 3.
388
+ :param target_mode: A mode for the result image. Should have not less
389
+ than ``channels`` channels. Default is ``None``,
390
+ which means that mode wouldn't be changed.
391
+ """
392
+
393
+ name = "Color 3D LUT"
394
+
395
+ def __init__(
396
+ self,
397
+ size: int | tuple[int, int, int],
398
+ table: Sequence[float] | Sequence[Sequence[int]] | NumpyArray,
399
+ channels: int = 3,
400
+ target_mode: str | None = None,
401
+ **kwargs: bool,
402
+ ) -> None:
403
+ if channels not in (3, 4):
404
+ msg = "Only 3 or 4 output channels are supported"
405
+ raise ValueError(msg)
406
+ self.size = size = self._check_size(size)
407
+ self.channels = channels
408
+ self.mode = target_mode
409
+
410
+ # Hidden flag `_copy_table=False` could be used to avoid extra copying
411
+ # of the table if the table is specially made for the constructor.
412
+ copy_table = kwargs.get("_copy_table", True)
413
+ items = size[0] * size[1] * size[2]
414
+ wrong_size = False
415
+
416
+ numpy: ModuleType | None = None
417
+ if hasattr(table, "shape"):
418
+ try:
419
+ import numpy
420
+ except ImportError:
421
+ pass
422
+
423
+ if numpy and isinstance(table, numpy.ndarray):
424
+ numpy_table: NumpyArray = table
425
+ if copy_table:
426
+ numpy_table = numpy_table.copy()
427
+
428
+ if numpy_table.shape in [
429
+ (items * channels,),
430
+ (items, channels),
431
+ (size[2], size[1], size[0], channels),
432
+ ]:
433
+ table = numpy_table.reshape(items * channels)
434
+ else:
435
+ wrong_size = True
436
+
437
+ else:
438
+ if copy_table:
439
+ table = list(table)
440
+
441
+ # Convert to a flat list
442
+ if table and isinstance(table[0], (list, tuple)):
443
+ raw_table = cast(Sequence[Sequence[int]], table)
444
+ flat_table: list[int] = []
445
+ for pixel in raw_table:
446
+ if len(pixel) != channels:
447
+ msg = (
448
+ "The elements of the table should "
449
+ f"have a length of {channels}."
450
+ )
451
+ raise ValueError(msg)
452
+ flat_table.extend(pixel)
453
+ table = flat_table
454
+
455
+ if wrong_size or len(table) != items * channels:
456
+ msg = (
457
+ "The table should have either channels * size**3 float items "
458
+ "or size**3 items of channels-sized tuples with floats. "
459
+ f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. "
460
+ f"Actual length: {len(table)}"
461
+ )
462
+ raise ValueError(msg)
463
+ self.table = table
464
+
465
+ @staticmethod
466
+ def _check_size(size: Any) -> tuple[int, int, int]:
467
+ try:
468
+ _, _, _ = size
469
+ except ValueError as e:
470
+ msg = "Size should be either an integer or a tuple of three integers."
471
+ raise ValueError(msg) from e
472
+ except TypeError:
473
+ size = (size, size, size)
474
+ size = tuple(int(x) for x in size)
475
+ for size_1d in size:
476
+ if not 2 <= size_1d <= 65:
477
+ msg = "Size should be in [2, 65] range."
478
+ raise ValueError(msg)
479
+ return size
480
+
481
+ @classmethod
482
+ def generate(
483
+ cls,
484
+ size: int | tuple[int, int, int],
485
+ callback: Callable[[float, float, float], tuple[float, ...]],
486
+ channels: int = 3,
487
+ target_mode: str | None = None,
488
+ ) -> Color3DLUT:
489
+ """Generates new LUT using provided callback.
490
+
491
+ :param size: Size of the table. Passed to the constructor.
492
+ :param callback: Function with three parameters which correspond
493
+ three color channels. Will be called ``size**3``
494
+ times with values from 0.0 to 1.0 and should return
495
+ a tuple with ``channels`` elements.
496
+ :param channels: The number of channels which should return callback.
497
+ :param target_mode: Passed to the constructor of the resulting
498
+ lookup table.
499
+ """
500
+ size_1d, size_2d, size_3d = cls._check_size(size)
501
+ if channels not in (3, 4):
502
+ msg = "Only 3 or 4 output channels are supported"
503
+ raise ValueError(msg)
504
+
505
+ table: list[float] = [0] * (size_1d * size_2d * size_3d * channels)
506
+ idx_out = 0
507
+ for b in range(size_3d):
508
+ for g in range(size_2d):
509
+ for r in range(size_1d):
510
+ table[idx_out : idx_out + channels] = callback(
511
+ r / (size_1d - 1), g / (size_2d - 1), b / (size_3d - 1)
512
+ )
513
+ idx_out += channels
514
+
515
+ return cls(
516
+ (size_1d, size_2d, size_3d),
517
+ table,
518
+ channels=channels,
519
+ target_mode=target_mode,
520
+ _copy_table=False,
521
+ )
522
+
523
+ def transform(
524
+ self,
525
+ callback: Callable[..., tuple[float, ...]],
526
+ with_normals: bool = False,
527
+ channels: int | None = None,
528
+ target_mode: str | None = None,
529
+ ) -> Color3DLUT:
530
+ """Transforms the table values using provided callback and returns
531
+ a new LUT with altered values.
532
+
533
+ :param callback: A function which takes old lookup table values
534
+ and returns a new set of values. The number
535
+ of arguments which function should take is
536
+ ``self.channels`` or ``3 + self.channels``
537
+ if ``with_normals`` flag is set.
538
+ Should return a tuple of ``self.channels`` or
539
+ ``channels`` elements if it is set.
540
+ :param with_normals: If true, ``callback`` will be called with
541
+ coordinates in the color cube as the first
542
+ three arguments. Otherwise, ``callback``
543
+ will be called only with actual color values.
544
+ :param channels: The number of channels in the resulting lookup table.
545
+ :param target_mode: Passed to the constructor of the resulting
546
+ lookup table.
547
+ """
548
+ if channels not in (None, 3, 4):
549
+ msg = "Only 3 or 4 output channels are supported"
550
+ raise ValueError(msg)
551
+ ch_in = self.channels
552
+ ch_out = channels or ch_in
553
+ size_1d, size_2d, size_3d = self.size
554
+
555
+ table = [0] * (size_1d * size_2d * size_3d * ch_out)
556
+ idx_in = 0
557
+ idx_out = 0
558
+ for b in range(size_3d):
559
+ for g in range(size_2d):
560
+ for r in range(size_1d):
561
+ values = self.table[idx_in : idx_in + ch_in]
562
+ if with_normals:
563
+ values = callback(
564
+ r / (size_1d - 1),
565
+ g / (size_2d - 1),
566
+ b / (size_3d - 1),
567
+ *values,
568
+ )
569
+ else:
570
+ values = callback(*values)
571
+ table[idx_out : idx_out + ch_out] = values
572
+ idx_in += ch_in
573
+ idx_out += ch_out
574
+
575
+ return type(self)(
576
+ self.size,
577
+ table,
578
+ channels=ch_out,
579
+ target_mode=target_mode or self.mode,
580
+ _copy_table=False,
581
+ )
582
+
583
+ def __repr__(self) -> str:
584
+ r = [
585
+ f"{self.__class__.__name__} from {self.table.__class__.__name__}",
586
+ "size={:d}x{:d}x{:d}".format(*self.size),
587
+ f"channels={self.channels:d}",
588
+ ]
589
+ if self.mode:
590
+ r.append(f"target_mode={self.mode}")
591
+ return "<{}>".format(" ".join(r))
592
+
593
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
594
+ from . import Image
595
+
596
+ return image.color_lut_3d(
597
+ self.mode or image.mode,
598
+ Image.Resampling.BILINEAR,
599
+ self.channels,
600
+ self.size[0],
601
+ self.size[1],
602
+ self.size[2],
603
+ self.table,
604
+ )
evalkit_tf437/lib/python3.10/site-packages/PIL/ImageMode.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # standard mode descriptors
6
+ #
7
+ # History:
8
+ # 2006-03-20 fl Added
9
+ #
10
+ # Copyright (c) 2006 by Secret Labs AB.
11
+ # Copyright (c) 2006 by Fredrik Lundh.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+ from __future__ import annotations
16
+
17
+ import sys
18
+ from functools import lru_cache
19
+ from typing import NamedTuple
20
+
21
+ from ._deprecate import deprecate
22
+
23
+
24
+ class ModeDescriptor(NamedTuple):
25
+ """Wrapper for mode strings."""
26
+
27
+ mode: str
28
+ bands: tuple[str, ...]
29
+ basemode: str
30
+ basetype: str
31
+ typestr: str
32
+
33
+ def __str__(self) -> str:
34
+ return self.mode
35
+
36
+
37
+ @lru_cache
38
+ def getmode(mode: str) -> ModeDescriptor:
39
+ """Gets a mode descriptor for the given mode."""
40
+ endian = "<" if sys.byteorder == "little" else ">"
41
+
42
+ modes = {
43
+ # core modes
44
+ # Bits need to be extended to bytes
45
+ "1": ("L", "L", ("1",), "|b1"),
46
+ "L": ("L", "L", ("L",), "|u1"),
47
+ "I": ("L", "I", ("I",), f"{endian}i4"),
48
+ "F": ("L", "F", ("F",), f"{endian}f4"),
49
+ "P": ("P", "L", ("P",), "|u1"),
50
+ "RGB": ("RGB", "L", ("R", "G", "B"), "|u1"),
51
+ "RGBX": ("RGB", "L", ("R", "G", "B", "X"), "|u1"),
52
+ "RGBA": ("RGB", "L", ("R", "G", "B", "A"), "|u1"),
53
+ "CMYK": ("RGB", "L", ("C", "M", "Y", "K"), "|u1"),
54
+ "YCbCr": ("RGB", "L", ("Y", "Cb", "Cr"), "|u1"),
55
+ # UNDONE - unsigned |u1i1i1
56
+ "LAB": ("RGB", "L", ("L", "A", "B"), "|u1"),
57
+ "HSV": ("RGB", "L", ("H", "S", "V"), "|u1"),
58
+ # extra experimental modes
59
+ "RGBa": ("RGB", "L", ("R", "G", "B", "a"), "|u1"),
60
+ "BGR;15": ("RGB", "L", ("B", "G", "R"), "|u1"),
61
+ "BGR;16": ("RGB", "L", ("B", "G", "R"), "|u1"),
62
+ "BGR;24": ("RGB", "L", ("B", "G", "R"), "|u1"),
63
+ "LA": ("L", "L", ("L", "A"), "|u1"),
64
+ "La": ("L", "L", ("L", "a"), "|u1"),
65
+ "PA": ("RGB", "L", ("P", "A"), "|u1"),
66
+ }
67
+ if mode in modes:
68
+ if mode in ("BGR;15", "BGR;16", "BGR;24"):
69
+ deprecate(mode, 12)
70
+ base_mode, base_type, bands, type_str = modes[mode]
71
+ return ModeDescriptor(mode, bands, base_mode, base_type, type_str)
72
+
73
+ mapping_modes = {
74
+ # I;16 == I;16L, and I;32 == I;32L
75
+ "I;16": "<u2",
76
+ "I;16S": "<i2",
77
+ "I;16L": "<u2",
78
+ "I;16LS": "<i2",
79
+ "I;16B": ">u2",
80
+ "I;16BS": ">i2",
81
+ "I;16N": f"{endian}u2",
82
+ "I;16NS": f"{endian}i2",
83
+ "I;32": "<u4",
84
+ "I;32B": ">u4",
85
+ "I;32L": "<u4",
86
+ "I;32S": "<i4",
87
+ "I;32BS": ">i4",
88
+ "I;32LS": "<i4",
89
+ }
90
+
91
+ type_str = mapping_modes[mode]
92
+ return ModeDescriptor(mode, ("I",), "L", "L", type_str)
evalkit_tf437/lib/python3.10/site-packages/PIL/ImagePalette.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # image palette object
6
+ #
7
+ # History:
8
+ # 1996-03-11 fl Rewritten.
9
+ # 1997-01-03 fl Up and running.
10
+ # 1997-08-23 fl Added load hack
11
+ # 2001-04-16 fl Fixed randint shadow bug in random()
12
+ #
13
+ # Copyright (c) 1997-2001 by Secret Labs AB
14
+ # Copyright (c) 1996-1997 by Fredrik Lundh
15
+ #
16
+ # See the README file for information on usage and redistribution.
17
+ #
18
+ from __future__ import annotations
19
+
20
+ import array
21
+ from typing import IO, TYPE_CHECKING, Sequence
22
+
23
+ from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile
24
+
25
+ if TYPE_CHECKING:
26
+ from . import Image
27
+
28
+
29
+ class ImagePalette:
30
+ """
31
+ Color palette for palette mapped images
32
+
33
+ :param mode: The mode to use for the palette. See:
34
+ :ref:`concept-modes`. Defaults to "RGB"
35
+ :param palette: An optional palette. If given, it must be a bytearray,
36
+ an array or a list of ints between 0-255. The list must consist of
37
+ all channels for one color followed by the next color (e.g. RGBRGBRGB).
38
+ Defaults to an empty palette.
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ mode: str = "RGB",
44
+ palette: Sequence[int] | bytes | bytearray | None = None,
45
+ ) -> None:
46
+ self.mode = mode
47
+ self.rawmode: str | None = None # if set, palette contains raw data
48
+ self.palette = palette or bytearray()
49
+ self.dirty: int | None = None
50
+
51
+ @property
52
+ def palette(self) -> Sequence[int] | bytes | bytearray:
53
+ return self._palette
54
+
55
+ @palette.setter
56
+ def palette(self, palette: Sequence[int] | bytes | bytearray) -> None:
57
+ self._colors: dict[tuple[int, ...], int] | None = None
58
+ self._palette = palette
59
+
60
+ @property
61
+ def colors(self) -> dict[tuple[int, ...], int]:
62
+ if self._colors is None:
63
+ mode_len = len(self.mode)
64
+ self._colors = {}
65
+ for i in range(0, len(self.palette), mode_len):
66
+ color = tuple(self.palette[i : i + mode_len])
67
+ if color in self._colors:
68
+ continue
69
+ self._colors[color] = i // mode_len
70
+ return self._colors
71
+
72
+ @colors.setter
73
+ def colors(self, colors: dict[tuple[int, ...], int]) -> None:
74
+ self._colors = colors
75
+
76
+ def copy(self) -> ImagePalette:
77
+ new = ImagePalette()
78
+
79
+ new.mode = self.mode
80
+ new.rawmode = self.rawmode
81
+ if self.palette is not None:
82
+ new.palette = self.palette[:]
83
+ new.dirty = self.dirty
84
+
85
+ return new
86
+
87
+ def getdata(self) -> tuple[str, Sequence[int] | bytes | bytearray]:
88
+ """
89
+ Get palette contents in format suitable for the low-level
90
+ ``im.putpalette`` primitive.
91
+
92
+ .. warning:: This method is experimental.
93
+ """
94
+ if self.rawmode:
95
+ return self.rawmode, self.palette
96
+ return self.mode, self.tobytes()
97
+
98
+ def tobytes(self) -> bytes:
99
+ """Convert palette to bytes.
100
+
101
+ .. warning:: This method is experimental.
102
+ """
103
+ if self.rawmode:
104
+ msg = "palette contains raw palette data"
105
+ raise ValueError(msg)
106
+ if isinstance(self.palette, bytes):
107
+ return self.palette
108
+ arr = array.array("B", self.palette)
109
+ return arr.tobytes()
110
+
111
+ # Declare tostring as an alias for tobytes
112
+ tostring = tobytes
113
+
114
+ def _new_color_index(
115
+ self, image: Image.Image | None = None, e: Exception | None = None
116
+ ) -> int:
117
+ if not isinstance(self.palette, bytearray):
118
+ self._palette = bytearray(self.palette)
119
+ index = len(self.palette) // 3
120
+ special_colors: tuple[int | tuple[int, ...] | None, ...] = ()
121
+ if image:
122
+ special_colors = (
123
+ image.info.get("background"),
124
+ image.info.get("transparency"),
125
+ )
126
+ while index in special_colors:
127
+ index += 1
128
+ if index >= 256:
129
+ if image:
130
+ # Search for an unused index
131
+ for i, count in reversed(list(enumerate(image.histogram()))):
132
+ if count == 0 and i not in special_colors:
133
+ index = i
134
+ break
135
+ if index >= 256:
136
+ msg = "cannot allocate more than 256 colors"
137
+ raise ValueError(msg) from e
138
+ return index
139
+
140
+ def getcolor(
141
+ self,
142
+ color: tuple[int, ...],
143
+ image: Image.Image | None = None,
144
+ ) -> int:
145
+ """Given an rgb tuple, allocate palette entry.
146
+
147
+ .. warning:: This method is experimental.
148
+ """
149
+ if self.rawmode:
150
+ msg = "palette contains raw palette data"
151
+ raise ValueError(msg)
152
+ if isinstance(color, tuple):
153
+ if self.mode == "RGB":
154
+ if len(color) == 4:
155
+ if color[3] != 255:
156
+ msg = "cannot add non-opaque RGBA color to RGB palette"
157
+ raise ValueError(msg)
158
+ color = color[:3]
159
+ elif self.mode == "RGBA":
160
+ if len(color) == 3:
161
+ color += (255,)
162
+ try:
163
+ return self.colors[color]
164
+ except KeyError as e:
165
+ # allocate new color slot
166
+ index = self._new_color_index(image, e)
167
+ assert isinstance(self._palette, bytearray)
168
+ self.colors[color] = index
169
+ if index * 3 < len(self.palette):
170
+ self._palette = (
171
+ self._palette[: index * 3]
172
+ + bytes(color)
173
+ + self._palette[index * 3 + 3 :]
174
+ )
175
+ else:
176
+ self._palette += bytes(color)
177
+ self.dirty = 1
178
+ return index
179
+ else:
180
+ msg = f"unknown color specifier: {repr(color)}" # type: ignore[unreachable]
181
+ raise ValueError(msg)
182
+
183
+ def save(self, fp: str | IO[str]) -> None:
184
+ """Save palette to text file.
185
+
186
+ .. warning:: This method is experimental.
187
+ """
188
+ if self.rawmode:
189
+ msg = "palette contains raw palette data"
190
+ raise ValueError(msg)
191
+ if isinstance(fp, str):
192
+ fp = open(fp, "w")
193
+ fp.write("# Palette\n")
194
+ fp.write(f"# Mode: {self.mode}\n")
195
+ for i in range(256):
196
+ fp.write(f"{i}")
197
+ for j in range(i * len(self.mode), (i + 1) * len(self.mode)):
198
+ try:
199
+ fp.write(f" {self.palette[j]}")
200
+ except IndexError:
201
+ fp.write(" 0")
202
+ fp.write("\n")
203
+ fp.close()
204
+
205
+
206
+ # --------------------------------------------------------------------
207
+ # Internal
208
+
209
+
210
+ def raw(rawmode, data: Sequence[int] | bytes | bytearray) -> ImagePalette:
211
+ palette = ImagePalette()
212
+ palette.rawmode = rawmode
213
+ palette.palette = data
214
+ palette.dirty = 1
215
+ return palette
216
+
217
+
218
+ # --------------------------------------------------------------------
219
+ # Factories
220
+
221
+
222
+ def make_linear_lut(black: int, white: float) -> list[int]:
223
+ if black == 0:
224
+ return [int(white * i // 255) for i in range(256)]
225
+
226
+ msg = "unavailable when black is non-zero"
227
+ raise NotImplementedError(msg) # FIXME
228
+
229
+
230
+ def make_gamma_lut(exp: float) -> list[int]:
231
+ return [int(((i / 255.0) ** exp) * 255.0 + 0.5) for i in range(256)]
232
+
233
+
234
+ def negative(mode: str = "RGB") -> ImagePalette:
235
+ palette = list(range(256 * len(mode)))
236
+ palette.reverse()
237
+ return ImagePalette(mode, [i // len(mode) for i in palette])
238
+
239
+
240
+ def random(mode: str = "RGB") -> ImagePalette:
241
+ from random import randint
242
+
243
+ palette = [randint(0, 255) for _ in range(256 * len(mode))]
244
+ return ImagePalette(mode, palette)
245
+
246
+
247
+ def sepia(white: str = "#fff0c0") -> ImagePalette:
248
+ bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)]
249
+ return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)])
250
+
251
+
252
+ def wedge(mode: str = "RGB") -> ImagePalette:
253
+ palette = list(range(256 * len(mode)))
254
+ return ImagePalette(mode, [i // len(mode) for i in palette])
255
+
256
+
257
+ def load(filename: str) -> tuple[bytes, str]:
258
+ # FIXME: supports GIMP gradients only
259
+
260
+ with open(filename, "rb") as fp:
261
+ paletteHandlers: list[
262
+ type[
263
+ GimpPaletteFile.GimpPaletteFile
264
+ | GimpGradientFile.GimpGradientFile
265
+ | PaletteFile.PaletteFile
266
+ ]
267
+ ] = [
268
+ GimpPaletteFile.GimpPaletteFile,
269
+ GimpGradientFile.GimpGradientFile,
270
+ PaletteFile.PaletteFile,
271
+ ]
272
+ for paletteHandler in paletteHandlers:
273
+ try:
274
+ fp.seek(0)
275
+ lut = paletteHandler(fp).getpalette()
276
+ if lut:
277
+ break
278
+ except (SyntaxError, ValueError):
279
+ pass
280
+ else:
281
+ msg = "cannot load palette"
282
+ raise OSError(msg)
283
+
284
+ return lut # data, rawmode
evalkit_tf437/lib/python3.10/site-packages/PIL/ImagePath.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # path interface
6
+ #
7
+ # History:
8
+ # 1996-11-04 fl Created
9
+ # 2002-04-14 fl Added documentation stub class
10
+ #
11
+ # Copyright (c) Secret Labs AB 1997.
12
+ # Copyright (c) Fredrik Lundh 1996.
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ from __future__ import annotations
17
+
18
+ from . import Image
19
+
20
+ Path = Image.core.path
evalkit_tf437/lib/python3.10/site-packages/PIL/ImageShow.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # im.show() drivers
6
+ #
7
+ # History:
8
+ # 2008-04-06 fl Created
9
+ #
10
+ # Copyright (c) Secret Labs AB 2008.
11
+ #
12
+ # See the README file for information on usage and redistribution.
13
+ #
14
+ from __future__ import annotations
15
+
16
+ import abc
17
+ import os
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ from shlex import quote
22
+ from typing import Any
23
+
24
+ from . import Image
25
+
26
+ _viewers = []
27
+
28
+
29
+ def register(viewer, order: int = 1) -> None:
30
+ """
31
+ The :py:func:`register` function is used to register additional viewers::
32
+
33
+ from PIL import ImageShow
34
+ ImageShow.register(MyViewer()) # MyViewer will be used as a last resort
35
+ ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised
36
+ ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised
37
+
38
+ :param viewer: The viewer to be registered.
39
+ :param order:
40
+ Zero or a negative integer to prepend this viewer to the list,
41
+ a positive integer to append it.
42
+ """
43
+ try:
44
+ if issubclass(viewer, Viewer):
45
+ viewer = viewer()
46
+ except TypeError:
47
+ pass # raised if viewer wasn't a class
48
+ if order > 0:
49
+ _viewers.append(viewer)
50
+ else:
51
+ _viewers.insert(0, viewer)
52
+
53
+
54
+ def show(image: Image.Image, title: str | None = None, **options: Any) -> bool:
55
+ r"""
56
+ Display a given image.
57
+
58
+ :param image: An image object.
59
+ :param title: Optional title. Not all viewers can display the title.
60
+ :param \**options: Additional viewer options.
61
+ :returns: ``True`` if a suitable viewer was found, ``False`` otherwise.
62
+ """
63
+ for viewer in _viewers:
64
+ if viewer.show(image, title=title, **options):
65
+ return True
66
+ return False
67
+
68
+
69
+ class Viewer:
70
+ """Base class for viewers."""
71
+
72
+ # main api
73
+
74
+ def show(self, image: Image.Image, **options: Any) -> int:
75
+ """
76
+ The main function for displaying an image.
77
+ Converts the given image to the target format and displays it.
78
+ """
79
+
80
+ if not (
81
+ image.mode in ("1", "RGBA")
82
+ or (self.format == "PNG" and image.mode in ("I;16", "LA"))
83
+ ):
84
+ base = Image.getmodebase(image.mode)
85
+ if image.mode != base:
86
+ image = image.convert(base)
87
+
88
+ return self.show_image(image, **options)
89
+
90
+ # hook methods
91
+
92
+ format: str | None = None
93
+ """The format to convert the image into."""
94
+ options: dict[str, Any] = {}
95
+ """Additional options used to convert the image."""
96
+
97
+ def get_format(self, image: Image.Image) -> str | None:
98
+ """Return format name, or ``None`` to save as PGM/PPM."""
99
+ return self.format
100
+
101
+ def get_command(self, file: str, **options: Any) -> str:
102
+ """
103
+ Returns the command used to display the file.
104
+ Not implemented in the base class.
105
+ """
106
+ msg = "unavailable in base viewer"
107
+ raise NotImplementedError(msg)
108
+
109
+ def save_image(self, image: Image.Image) -> str:
110
+ """Save to temporary file and return filename."""
111
+ return image._dump(format=self.get_format(image), **self.options)
112
+
113
+ def show_image(self, image: Image.Image, **options: Any) -> int:
114
+ """Display the given image."""
115
+ return self.show_file(self.save_image(image), **options)
116
+
117
+ def show_file(self, path: str, **options: Any) -> int:
118
+ """
119
+ Display given file.
120
+ """
121
+ if not os.path.exists(path):
122
+ raise FileNotFoundError
123
+ os.system(self.get_command(path, **options)) # nosec
124
+ return 1
125
+
126
+
127
+ # --------------------------------------------------------------------
128
+
129
+
130
+ class WindowsViewer(Viewer):
131
+ """The default viewer on Windows is the default system application for PNG files."""
132
+
133
+ format = "PNG"
134
+ options = {"compress_level": 1, "save_all": True}
135
+
136
+ def get_command(self, file: str, **options: Any) -> str:
137
+ return (
138
+ f'start "Pillow" /WAIT "{file}" '
139
+ "&& ping -n 4 127.0.0.1 >NUL "
140
+ f'&& del /f "{file}"'
141
+ )
142
+
143
+ def show_file(self, path: str, **options: Any) -> int:
144
+ """
145
+ Display given file.
146
+ """
147
+ if not os.path.exists(path):
148
+ raise FileNotFoundError
149
+ subprocess.Popen(
150
+ self.get_command(path, **options),
151
+ shell=True,
152
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW"),
153
+ ) # nosec
154
+ return 1
155
+
156
+
157
+ if sys.platform == "win32":
158
+ register(WindowsViewer)
159
+
160
+
161
+ class MacViewer(Viewer):
162
+ """The default viewer on macOS using ``Preview.app``."""
163
+
164
+ format = "PNG"
165
+ options = {"compress_level": 1, "save_all": True}
166
+
167
+ def get_command(self, file: str, **options: Any) -> str:
168
+ # on darwin open returns immediately resulting in the temp
169
+ # file removal while app is opening
170
+ command = "open -a Preview.app"
171
+ command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&"
172
+ return command
173
+
174
+ def show_file(self, path: str, **options: Any) -> int:
175
+ """
176
+ Display given file.
177
+ """
178
+ if not os.path.exists(path):
179
+ raise FileNotFoundError
180
+ subprocess.call(["open", "-a", "Preview.app", path])
181
+ executable = sys.executable or shutil.which("python3")
182
+ if executable:
183
+ subprocess.Popen(
184
+ [
185
+ executable,
186
+ "-c",
187
+ "import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",
188
+ path,
189
+ ]
190
+ )
191
+ return 1
192
+
193
+
194
+ if sys.platform == "darwin":
195
+ register(MacViewer)
196
+
197
+
198
+ class UnixViewer(Viewer):
199
+ format = "PNG"
200
+ options = {"compress_level": 1, "save_all": True}
201
+
202
+ @abc.abstractmethod
203
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
204
+ pass
205
+
206
+ def get_command(self, file: str, **options: Any) -> str:
207
+ command = self.get_command_ex(file, **options)[0]
208
+ return f"{command} {quote(file)}"
209
+
210
+
211
+ class XDGViewer(UnixViewer):
212
+ """
213
+ The freedesktop.org ``xdg-open`` command.
214
+ """
215
+
216
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
217
+ command = executable = "xdg-open"
218
+ return command, executable
219
+
220
+ def show_file(self, path: str, **options: Any) -> int:
221
+ """
222
+ Display given file.
223
+ """
224
+ if not os.path.exists(path):
225
+ raise FileNotFoundError
226
+ subprocess.Popen(["xdg-open", path])
227
+ return 1
228
+
229
+
230
+ class DisplayViewer(UnixViewer):
231
+ """
232
+ The ImageMagick ``display`` command.
233
+ This viewer supports the ``title`` parameter.
234
+ """
235
+
236
+ def get_command_ex(
237
+ self, file: str, title: str | None = None, **options: Any
238
+ ) -> tuple[str, str]:
239
+ command = executable = "display"
240
+ if title:
241
+ command += f" -title {quote(title)}"
242
+ return command, executable
243
+
244
+ def show_file(self, path: str, **options: Any) -> int:
245
+ """
246
+ Display given file.
247
+ """
248
+ if not os.path.exists(path):
249
+ raise FileNotFoundError
250
+ args = ["display"]
251
+ title = options.get("title")
252
+ if title:
253
+ args += ["-title", title]
254
+ args.append(path)
255
+
256
+ subprocess.Popen(args)
257
+ return 1
258
+
259
+
260
+ class GmDisplayViewer(UnixViewer):
261
+ """The GraphicsMagick ``gm display`` command."""
262
+
263
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
264
+ executable = "gm"
265
+ command = "gm display"
266
+ return command, executable
267
+
268
+ def show_file(self, path: str, **options: Any) -> int:
269
+ """
270
+ Display given file.
271
+ """
272
+ if not os.path.exists(path):
273
+ raise FileNotFoundError
274
+ subprocess.Popen(["gm", "display", path])
275
+ return 1
276
+
277
+
278
+ class EogViewer(UnixViewer):
279
+ """The GNOME Image Viewer ``eog`` command."""
280
+
281
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
282
+ executable = "eog"
283
+ command = "eog -n"
284
+ return command, executable
285
+
286
+ def show_file(self, path: str, **options: Any) -> int:
287
+ """
288
+ Display given file.
289
+ """
290
+ if not os.path.exists(path):
291
+ raise FileNotFoundError
292
+ subprocess.Popen(["eog", "-n", path])
293
+ return 1
294
+
295
+
296
+ class XVViewer(UnixViewer):
297
+ """
298
+ The X Viewer ``xv`` command.
299
+ This viewer supports the ``title`` parameter.
300
+ """
301
+
302
+ def get_command_ex(
303
+ self, file: str, title: str | None = None, **options: Any
304
+ ) -> tuple[str, str]:
305
+ # note: xv is pretty outdated. most modern systems have
306
+ # imagemagick's display command instead.
307
+ command = executable = "xv"
308
+ if title:
309
+ command += f" -name {quote(title)}"
310
+ return command, executable
311
+
312
+ def show_file(self, path: str, **options: Any) -> int:
313
+ """
314
+ Display given file.
315
+ """
316
+ if not os.path.exists(path):
317
+ raise FileNotFoundError
318
+ args = ["xv"]
319
+ title = options.get("title")
320
+ if title:
321
+ args += ["-name", title]
322
+ args.append(path)
323
+
324
+ subprocess.Popen(args)
325
+ return 1
326
+
327
+
328
+ if sys.platform not in ("win32", "darwin"): # unixoids
329
+ if shutil.which("xdg-open"):
330
+ register(XDGViewer)
331
+ if shutil.which("display"):
332
+ register(DisplayViewer)
333
+ if shutil.which("gm"):
334
+ register(GmDisplayViewer)
335
+ if shutil.which("eog"):
336
+ register(EogViewer)
337
+ if shutil.which("xv"):
338
+ register(XVViewer)
339
+
340
+
341
+ class IPythonViewer(Viewer):
342
+ """The viewer for IPython frontends."""
343
+
344
+ def show_image(self, image: Image.Image, **options: Any) -> int:
345
+ ipython_display(image)
346
+ return 1
347
+
348
+
349
+ try:
350
+ from IPython.display import display as ipython_display
351
+ except ImportError:
352
+ pass
353
+ else:
354
+ register(IPythonViewer)
355
+
356
+
357
+ if __name__ == "__main__":
358
+ if len(sys.argv) < 2:
359
+ print("Syntax: python3 ImageShow.py imagefile [title]")
360
+ sys.exit()
361
+
362
+ with Image.open(sys.argv[1]) as im:
363
+ print(show(im, *sys.argv[2:]))
evalkit_tf437/lib/python3.10/site-packages/PIL/ImageTk.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # a Tk display interface
6
+ #
7
+ # History:
8
+ # 96-04-08 fl Created
9
+ # 96-09-06 fl Added getimage method
10
+ # 96-11-01 fl Rewritten, removed image attribute and crop method
11
+ # 97-05-09 fl Use PyImagingPaste method instead of image type
12
+ # 97-05-12 fl Minor tweaks to match the IFUNC95 interface
13
+ # 97-05-17 fl Support the "pilbitmap" booster patch
14
+ # 97-06-05 fl Added file= and data= argument to image constructors
15
+ # 98-03-09 fl Added width and height methods to Image classes
16
+ # 98-07-02 fl Use default mode for "P" images without palette attribute
17
+ # 98-07-02 fl Explicitly destroy Tkinter image objects
18
+ # 99-07-24 fl Support multiple Tk interpreters (from Greg Couch)
19
+ # 99-07-26 fl Automatically hook into Tkinter (if possible)
20
+ # 99-08-15 fl Hook uses _imagingtk instead of _imaging
21
+ #
22
+ # Copyright (c) 1997-1999 by Secret Labs AB
23
+ # Copyright (c) 1996-1997 by Fredrik Lundh
24
+ #
25
+ # See the README file for information on usage and redistribution.
26
+ #
27
+ from __future__ import annotations
28
+
29
+ import tkinter
30
+ from io import BytesIO
31
+
32
+ from . import Image
33
+
34
+ # --------------------------------------------------------------------
35
+ # Check for Tkinter interface hooks
36
+
37
+ _pilbitmap_ok = None
38
+
39
+
40
+ def _pilbitmap_check() -> int:
41
+ global _pilbitmap_ok
42
+ if _pilbitmap_ok is None:
43
+ try:
44
+ im = Image.new("1", (1, 1))
45
+ tkinter.BitmapImage(data=f"PIL:{im.im.id}")
46
+ _pilbitmap_ok = 1
47
+ except tkinter.TclError:
48
+ _pilbitmap_ok = 0
49
+ return _pilbitmap_ok
50
+
51
+
52
+ def _get_image_from_kw(kw):
53
+ source = None
54
+ if "file" in kw:
55
+ source = kw.pop("file")
56
+ elif "data" in kw:
57
+ source = BytesIO(kw.pop("data"))
58
+ if source:
59
+ return Image.open(source)
60
+
61
+
62
+ def _pyimagingtkcall(command, photo, id):
63
+ tk = photo.tk
64
+ try:
65
+ tk.call(command, photo, id)
66
+ except tkinter.TclError:
67
+ # activate Tkinter hook
68
+ # may raise an error if it cannot attach to Tkinter
69
+ from . import _imagingtk
70
+
71
+ _imagingtk.tkinit(tk.interpaddr())
72
+ tk.call(command, photo, id)
73
+
74
+
75
+ # --------------------------------------------------------------------
76
+ # PhotoImage
77
+
78
+
79
+ class PhotoImage:
80
+ """
81
+ A Tkinter-compatible photo image. This can be used
82
+ everywhere Tkinter expects an image object. If the image is an RGBA
83
+ image, pixels having alpha 0 are treated as transparent.
84
+
85
+ The constructor takes either a PIL image, or a mode and a size.
86
+ Alternatively, you can use the ``file`` or ``data`` options to initialize
87
+ the photo image object.
88
+
89
+ :param image: Either a PIL image, or a mode string. If a mode string is
90
+ used, a size must also be given.
91
+ :param size: If the first argument is a mode string, this defines the size
92
+ of the image.
93
+ :keyword file: A filename to load the image from (using
94
+ ``Image.open(file)``).
95
+ :keyword data: An 8-bit string containing image data (as loaded from an
96
+ image file).
97
+ """
98
+
99
+ def __init__(self, image=None, size=None, **kw):
100
+ # Tk compatibility: file or data
101
+ if image is None:
102
+ image = _get_image_from_kw(kw)
103
+
104
+ if hasattr(image, "mode") and hasattr(image, "size"):
105
+ # got an image instead of a mode
106
+ mode = image.mode
107
+ if mode == "P":
108
+ # palette mapped data
109
+ image.apply_transparency()
110
+ image.load()
111
+ try:
112
+ mode = image.palette.mode
113
+ except AttributeError:
114
+ mode = "RGB" # default
115
+ size = image.size
116
+ kw["width"], kw["height"] = size
117
+ else:
118
+ mode = image
119
+ image = None
120
+
121
+ if mode not in ["1", "L", "RGB", "RGBA"]:
122
+ mode = Image.getmodebase(mode)
123
+
124
+ self.__mode = mode
125
+ self.__size = size
126
+ self.__photo = tkinter.PhotoImage(**kw)
127
+ self.tk = self.__photo.tk
128
+ if image:
129
+ self.paste(image)
130
+
131
+ def __del__(self) -> None:
132
+ name = self.__photo.name
133
+ self.__photo.name = None
134
+ try:
135
+ self.__photo.tk.call("image", "delete", name)
136
+ except Exception:
137
+ pass # ignore internal errors
138
+
139
+ def __str__(self) -> str:
140
+ """
141
+ Get the Tkinter photo image identifier. This method is automatically
142
+ called by Tkinter whenever a PhotoImage object is passed to a Tkinter
143
+ method.
144
+
145
+ :return: A Tkinter photo image identifier (a string).
146
+ """
147
+ return str(self.__photo)
148
+
149
+ def width(self) -> int:
150
+ """
151
+ Get the width of the image.
152
+
153
+ :return: The width, in pixels.
154
+ """
155
+ return self.__size[0]
156
+
157
+ def height(self) -> int:
158
+ """
159
+ Get the height of the image.
160
+
161
+ :return: The height, in pixels.
162
+ """
163
+ return self.__size[1]
164
+
165
+ def paste(self, im: Image.Image) -> None:
166
+ """
167
+ Paste a PIL image into the photo image. Note that this can
168
+ be very slow if the photo image is displayed.
169
+
170
+ :param im: A PIL image. The size must match the target region. If the
171
+ mode does not match, the image is converted to the mode of
172
+ the bitmap image.
173
+ """
174
+ # convert to blittable
175
+ im.load()
176
+ image = im.im
177
+ if image.isblock() and im.mode == self.__mode:
178
+ block = image
179
+ else:
180
+ block = image.new_block(self.__mode, im.size)
181
+ image.convert2(block, image) # convert directly between buffers
182
+
183
+ _pyimagingtkcall("PyImagingPhoto", self.__photo, block.id)
184
+
185
+
186
+ # --------------------------------------------------------------------
187
+ # BitmapImage
188
+
189
+
190
+ class BitmapImage:
191
+ """
192
+ A Tkinter-compatible bitmap image. This can be used everywhere Tkinter
193
+ expects an image object.
194
+
195
+ The given image must have mode "1". Pixels having value 0 are treated as
196
+ transparent. Options, if any, are passed on to Tkinter. The most commonly
197
+ used option is ``foreground``, which is used to specify the color for the
198
+ non-transparent parts. See the Tkinter documentation for information on
199
+ how to specify colours.
200
+
201
+ :param image: A PIL image.
202
+ """
203
+
204
+ def __init__(self, image=None, **kw):
205
+ # Tk compatibility: file or data
206
+ if image is None:
207
+ image = _get_image_from_kw(kw)
208
+
209
+ self.__mode = image.mode
210
+ self.__size = image.size
211
+
212
+ if _pilbitmap_check():
213
+ # fast way (requires the pilbitmap booster patch)
214
+ image.load()
215
+ kw["data"] = f"PIL:{image.im.id}"
216
+ self.__im = image # must keep a reference
217
+ else:
218
+ # slow but safe way
219
+ kw["data"] = image.tobitmap()
220
+ self.__photo = tkinter.BitmapImage(**kw)
221
+
222
+ def __del__(self) -> None:
223
+ name = self.__photo.name
224
+ self.__photo.name = None
225
+ try:
226
+ self.__photo.tk.call("image", "delete", name)
227
+ except Exception:
228
+ pass # ignore internal errors
229
+
230
+ def width(self) -> int:
231
+ """
232
+ Get the width of the image.
233
+
234
+ :return: The width, in pixels.
235
+ """
236
+ return self.__size[0]
237
+
238
+ def height(self) -> int:
239
+ """
240
+ Get the height of the image.
241
+
242
+ :return: The height, in pixels.
243
+ """
244
+ return self.__size[1]
245
+
246
+ def __str__(self) -> str:
247
+ """
248
+ Get the Tkinter bitmap image identifier. This method is automatically
249
+ called by Tkinter whenever a BitmapImage object is passed to a Tkinter
250
+ method.
251
+
252
+ :return: A Tkinter bitmap image identifier (a string).
253
+ """
254
+ return str(self.__photo)
255
+
256
+
257
+ def getimage(photo: PhotoImage) -> Image.Image:
258
+ """Copies the contents of a PhotoImage to a PIL image memory."""
259
+ im = Image.new("RGBA", (photo.width(), photo.height()))
260
+ block = im.im
261
+
262
+ _pyimagingtkcall("PyImagingPhotoGet", photo, block.id)
263
+
264
+ return im
265
+
266
+
267
+ def _show(image, title):
268
+ """Helper for the Image.show method."""
269
+
270
+ class UI(tkinter.Label):
271
+ def __init__(self, master, im):
272
+ if im.mode == "1":
273
+ self.image = BitmapImage(im, foreground="white", master=master)
274
+ else:
275
+ self.image = PhotoImage(im, master=master)
276
+ super().__init__(master, image=self.image, bg="black", bd=0)
277
+
278
+ if not tkinter._default_root:
279
+ msg = "tkinter not initialized"
280
+ raise OSError(msg)
281
+ top = tkinter.Toplevel()
282
+ if title:
283
+ top.title(title)
284
+ UI(top, image).pack()
evalkit_tf437/lib/python3.10/site-packages/PIL/ImageTransform.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # transform wrappers
6
+ #
7
+ # History:
8
+ # 2002-04-08 fl Created
9
+ #
10
+ # Copyright (c) 2002 by Secret Labs AB
11
+ # Copyright (c) 2002 by Fredrik Lundh
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+ from __future__ import annotations
16
+
17
+ from typing import Any, Sequence
18
+
19
+ from . import Image
20
+
21
+
22
+ class Transform(Image.ImageTransformHandler):
23
+ """Base class for other transforms defined in :py:mod:`~PIL.ImageTransform`."""
24
+
25
+ method: Image.Transform
26
+
27
+ def __init__(self, data: Sequence[Any]) -> None:
28
+ self.data = data
29
+
30
+ def getdata(self) -> tuple[Image.Transform, Sequence[int]]:
31
+ return self.method, self.data
32
+
33
+ def transform(
34
+ self,
35
+ size: tuple[int, int],
36
+ image: Image.Image,
37
+ **options: Any,
38
+ ) -> Image.Image:
39
+ """Perform the transform. Called from :py:meth:`.Image.transform`."""
40
+ # can be overridden
41
+ method, data = self.getdata()
42
+ return image.transform(size, method, data, **options)
43
+
44
+
45
+ class AffineTransform(Transform):
46
+ """
47
+ Define an affine image transform.
48
+
49
+ This function takes a 6-tuple (a, b, c, d, e, f) which contain the first
50
+ two rows from an affine transform matrix. For each pixel (x, y) in the
51
+ output image, the new value is taken from a position (a x + b y + c,
52
+ d x + e y + f) in the input image, rounded to nearest pixel.
53
+
54
+ This function can be used to scale, translate, rotate, and shear the
55
+ original image.
56
+
57
+ See :py:meth:`.Image.transform`
58
+
59
+ :param matrix: A 6-tuple (a, b, c, d, e, f) containing the first two rows
60
+ from an affine transform matrix.
61
+ """
62
+
63
+ method = Image.Transform.AFFINE
64
+
65
+
66
+ class PerspectiveTransform(Transform):
67
+ """
68
+ Define a perspective image transform.
69
+
70
+ This function takes an 8-tuple (a, b, c, d, e, f, g, h). For each pixel
71
+ (x, y) in the output image, the new value is taken from a position
72
+ ((a x + b y + c) / (g x + h y + 1), (d x + e y + f) / (g x + h y + 1)) in
73
+ the input image, rounded to nearest pixel.
74
+
75
+ This function can be used to scale, translate, rotate, and shear the
76
+ original image.
77
+
78
+ See :py:meth:`.Image.transform`
79
+
80
+ :param matrix: An 8-tuple (a, b, c, d, e, f, g, h).
81
+ """
82
+
83
+ method = Image.Transform.PERSPECTIVE
84
+
85
+
86
+ class ExtentTransform(Transform):
87
+ """
88
+ Define a transform to extract a subregion from an image.
89
+
90
+ Maps a rectangle (defined by two corners) from the image to a rectangle of
91
+ the given size. The resulting image will contain data sampled from between
92
+ the corners, such that (x0, y0) in the input image will end up at (0,0) in
93
+ the output image, and (x1, y1) at size.
94
+
95
+ This method can be used to crop, stretch, shrink, or mirror an arbitrary
96
+ rectangle in the current image. It is slightly slower than crop, but about
97
+ as fast as a corresponding resize operation.
98
+
99
+ See :py:meth:`.Image.transform`
100
+
101
+ :param bbox: A 4-tuple (x0, y0, x1, y1) which specifies two points in the
102
+ input image's coordinate system. See :ref:`coordinate-system`.
103
+ """
104
+
105
+ method = Image.Transform.EXTENT
106
+
107
+
108
+ class QuadTransform(Transform):
109
+ """
110
+ Define a quad image transform.
111
+
112
+ Maps a quadrilateral (a region defined by four corners) from the image to a
113
+ rectangle of the given size.
114
+
115
+ See :py:meth:`.Image.transform`
116
+
117
+ :param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the
118
+ upper left, lower left, lower right, and upper right corner of the
119
+ source quadrilateral.
120
+ """
121
+
122
+ method = Image.Transform.QUAD
123
+
124
+
125
+ class MeshTransform(Transform):
126
+ """
127
+ Define a mesh image transform. A mesh transform consists of one or more
128
+ individual quad transforms.
129
+
130
+ See :py:meth:`.Image.transform`
131
+
132
+ :param data: A list of (bbox, quad) tuples.
133
+ """
134
+
135
+ method = Image.Transform.MESH
evalkit_tf437/lib/python3.10/site-packages/PIL/ImageWin.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # a Windows DIB display interface
6
+ #
7
+ # History:
8
+ # 1996-05-20 fl Created
9
+ # 1996-09-20 fl Fixed subregion exposure
10
+ # 1997-09-21 fl Added draw primitive (for tzPrint)
11
+ # 2003-05-21 fl Added experimental Window/ImageWindow classes
12
+ # 2003-09-05 fl Added fromstring/tostring methods
13
+ #
14
+ # Copyright (c) Secret Labs AB 1997-2003.
15
+ # Copyright (c) Fredrik Lundh 1996-2003.
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+ from __future__ import annotations
20
+
21
+ from . import Image
22
+
23
+
24
+ class HDC:
25
+ """
26
+ Wraps an HDC integer. The resulting object can be passed to the
27
+ :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
28
+ methods.
29
+ """
30
+
31
+ def __init__(self, dc: int) -> None:
32
+ self.dc = dc
33
+
34
+ def __int__(self) -> int:
35
+ return self.dc
36
+
37
+
38
+ class HWND:
39
+ """
40
+ Wraps an HWND integer. The resulting object can be passed to the
41
+ :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
42
+ methods, instead of a DC.
43
+ """
44
+
45
+ def __init__(self, wnd: int) -> None:
46
+ self.wnd = wnd
47
+
48
+ def __int__(self) -> int:
49
+ return self.wnd
50
+
51
+
52
+ class Dib:
53
+ """
54
+ A Windows bitmap with the given mode and size. The mode can be one of "1",
55
+ "L", "P", or "RGB".
56
+
57
+ If the display requires a palette, this constructor creates a suitable
58
+ palette and associates it with the image. For an "L" image, 128 graylevels
59
+ are allocated. For an "RGB" image, a 6x6x6 colour cube is used, together
60
+ with 20 graylevels.
61
+
62
+ To make sure that palettes work properly under Windows, you must call the
63
+ ``palette`` method upon certain events from Windows.
64
+
65
+ :param image: Either a PIL image, or a mode string. If a mode string is
66
+ used, a size must also be given. The mode can be one of "1",
67
+ "L", "P", or "RGB".
68
+ :param size: If the first argument is a mode string, this
69
+ defines the size of the image.
70
+ """
71
+
72
+ def __init__(
73
+ self, image: Image.Image | str, size: tuple[int, int] | list[int] | None = None
74
+ ) -> None:
75
+ if isinstance(image, str):
76
+ mode = image
77
+ image = ""
78
+ else:
79
+ mode = image.mode
80
+ size = image.size
81
+ if mode not in ["1", "L", "P", "RGB"]:
82
+ mode = Image.getmodebase(mode)
83
+ self.image = Image.core.display(mode, size)
84
+ self.mode = mode
85
+ self.size = size
86
+ if image:
87
+ assert not isinstance(image, str)
88
+ self.paste(image)
89
+
90
+ def expose(self, handle):
91
+ """
92
+ Copy the bitmap contents to a device context.
93
+
94
+ :param handle: Device context (HDC), cast to a Python integer, or an
95
+ HDC or HWND instance. In PythonWin, you can use
96
+ ``CDC.GetHandleAttrib()`` to get a suitable handle.
97
+ """
98
+ if isinstance(handle, HWND):
99
+ dc = self.image.getdc(handle)
100
+ try:
101
+ result = self.image.expose(dc)
102
+ finally:
103
+ self.image.releasedc(handle, dc)
104
+ else:
105
+ result = self.image.expose(handle)
106
+ return result
107
+
108
+ def draw(self, handle, dst, src=None):
109
+ """
110
+ Same as expose, but allows you to specify where to draw the image, and
111
+ what part of it to draw.
112
+
113
+ The destination and source areas are given as 4-tuple rectangles. If
114
+ the source is omitted, the entire image is copied. If the source and
115
+ the destination have different sizes, the image is resized as
116
+ necessary.
117
+ """
118
+ if not src:
119
+ src = (0, 0) + self.size
120
+ if isinstance(handle, HWND):
121
+ dc = self.image.getdc(handle)
122
+ try:
123
+ result = self.image.draw(dc, dst, src)
124
+ finally:
125
+ self.image.releasedc(handle, dc)
126
+ else:
127
+ result = self.image.draw(handle, dst, src)
128
+ return result
129
+
130
+ def query_palette(self, handle):
131
+ """
132
+ Installs the palette associated with the image in the given device
133
+ context.
134
+
135
+ This method should be called upon **QUERYNEWPALETTE** and
136
+ **PALETTECHANGED** events from Windows. If this method returns a
137
+ non-zero value, one or more display palette entries were changed, and
138
+ the image should be redrawn.
139
+
140
+ :param handle: Device context (HDC), cast to a Python integer, or an
141
+ HDC or HWND instance.
142
+ :return: A true value if one or more entries were changed (this
143
+ indicates that the image should be redrawn).
144
+ """
145
+ if isinstance(handle, HWND):
146
+ handle = self.image.getdc(handle)
147
+ try:
148
+ result = self.image.query_palette(handle)
149
+ finally:
150
+ self.image.releasedc(handle, handle)
151
+ else:
152
+ result = self.image.query_palette(handle)
153
+ return result
154
+
155
+ def paste(
156
+ self, im: Image.Image, box: tuple[int, int, int, int] | None = None
157
+ ) -> None:
158
+ """
159
+ Paste a PIL image into the bitmap image.
160
+
161
+ :param im: A PIL image. The size must match the target region.
162
+ If the mode does not match, the image is converted to the
163
+ mode of the bitmap image.
164
+ :param box: A 4-tuple defining the left, upper, right, and
165
+ lower pixel coordinate. See :ref:`coordinate-system`. If
166
+ None is given instead of a tuple, all of the image is
167
+ assumed.
168
+ """
169
+ im.load()
170
+ if self.mode != im.mode:
171
+ im = im.convert(self.mode)
172
+ if box:
173
+ self.image.paste(im.im, box)
174
+ else:
175
+ self.image.paste(im.im)
176
+
177
+ def frombytes(self, buffer: bytes) -> None:
178
+ """
179
+ Load display memory contents from byte data.
180
+
181
+ :param buffer: A buffer containing display data (usually
182
+ data returned from :py:func:`~PIL.ImageWin.Dib.tobytes`)
183
+ """
184
+ self.image.frombytes(buffer)
185
+
186
+ def tobytes(self) -> bytes:
187
+ """
188
+ Copy display memory contents to bytes object.
189
+
190
+ :return: A bytes object containing display data.
191
+ """
192
+ return self.image.tobytes()
193
+
194
+
195
+ class Window:
196
+ """Create a Window with the given title size."""
197
+
198
+ def __init__(
199
+ self, title: str = "PIL", width: int | None = None, height: int | None = None
200
+ ) -> None:
201
+ self.hwnd = Image.core.createwindow(
202
+ title, self.__dispatcher, width or 0, height or 0
203
+ )
204
+
205
+ def __dispatcher(self, action, *args):
206
+ return getattr(self, f"ui_handle_{action}")(*args)
207
+
208
+ def ui_handle_clear(self, dc, x0, y0, x1, y1):
209
+ pass
210
+
211
+ def ui_handle_damage(self, x0, y0, x1, y1):
212
+ pass
213
+
214
+ def ui_handle_destroy(self) -> None:
215
+ pass
216
+
217
+ def ui_handle_repair(self, dc, x0, y0, x1, y1):
218
+ pass
219
+
220
+ def ui_handle_resize(self, width, height):
221
+ pass
222
+
223
+ def mainloop(self) -> None:
224
+ Image.core.eventloop()
225
+
226
+
227
+ class ImageWindow(Window):
228
+ """Create an image window which displays the given image."""
229
+
230
+ def __init__(self, image, title="PIL"):
231
+ if not isinstance(image, Dib):
232
+ image = Dib(image)
233
+ self.image = image
234
+ width, height = image.size
235
+ super().__init__(title, width=width, height=height)
236
+
237
+ def ui_handle_repair(self, dc, x0, y0, x1, y1):
238
+ self.image.draw(dc, (x0, y0, x1, y1))
evalkit_tf437/lib/python3.10/site-packages/PIL/ImtImagePlugin.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # IM Tools support for PIL
6
+ #
7
+ # history:
8
+ # 1996-05-27 fl Created (read 8-bit images only)
9
+ # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.2)
10
+ #
11
+ # Copyright (c) Secret Labs AB 1997-2001.
12
+ # Copyright (c) Fredrik Lundh 1996-2001.
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ from __future__ import annotations
17
+
18
+ import re
19
+
20
+ from . import Image, ImageFile
21
+
22
+ #
23
+ # --------------------------------------------------------------------
24
+
25
+ field = re.compile(rb"([a-z]*) ([^ \r\n]*)")
26
+
27
+
28
+ ##
29
+ # Image plugin for IM Tools images.
30
+
31
+
32
+ class ImtImageFile(ImageFile.ImageFile):
33
+ format = "IMT"
34
+ format_description = "IM Tools"
35
+
36
+ def _open(self) -> None:
37
+ # Quick rejection: if there's not a LF among the first
38
+ # 100 bytes, this is (probably) not a text header.
39
+
40
+ assert self.fp is not None
41
+
42
+ buffer = self.fp.read(100)
43
+ if b"\n" not in buffer:
44
+ msg = "not an IM file"
45
+ raise SyntaxError(msg)
46
+
47
+ xsize = ysize = 0
48
+
49
+ while True:
50
+ if buffer:
51
+ s = buffer[:1]
52
+ buffer = buffer[1:]
53
+ else:
54
+ s = self.fp.read(1)
55
+ if not s:
56
+ break
57
+
58
+ if s == b"\x0C":
59
+ # image data begins
60
+ self.tile = [
61
+ (
62
+ "raw",
63
+ (0, 0) + self.size,
64
+ self.fp.tell() - len(buffer),
65
+ (self.mode, 0, 1),
66
+ )
67
+ ]
68
+
69
+ break
70
+
71
+ else:
72
+ # read key/value pair
73
+ if b"\n" not in buffer:
74
+ buffer += self.fp.read(100)
75
+ lines = buffer.split(b"\n")
76
+ s += lines.pop(0)
77
+ buffer = b"\n".join(lines)
78
+ if len(s) == 1 or len(s) > 100:
79
+ break
80
+ if s[0] == ord(b"*"):
81
+ continue # comment
82
+
83
+ m = field.match(s)
84
+ if not m:
85
+ break
86
+ k, v = m.group(1, 2)
87
+ if k == b"width":
88
+ xsize = int(v)
89
+ self._size = xsize, ysize
90
+ elif k == b"height":
91
+ ysize = int(v)
92
+ self._size = xsize, ysize
93
+ elif k == b"pixel" and v == b"n8":
94
+ self._mode = "L"
95
+
96
+
97
+ #
98
+ # --------------------------------------------------------------------
99
+
100
+ Image.register_open(ImtImageFile.format, ImtImageFile)
101
+
102
+ #
103
+ # no extension registered (".im" is simply too common)
evalkit_tf437/lib/python3.10/site-packages/PIL/JpegPresets.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ JPEG quality settings equivalent to the Photoshop settings.
3
+ Can be used when saving JPEG files.
4
+
5
+ The following presets are available by default:
6
+ ``web_low``, ``web_medium``, ``web_high``, ``web_very_high``, ``web_maximum``,
7
+ ``low``, ``medium``, ``high``, ``maximum``.
8
+ More presets can be added to the :py:data:`presets` dict if needed.
9
+
10
+ To apply the preset, specify::
11
+
12
+ quality="preset_name"
13
+
14
+ To apply only the quantization table::
15
+
16
+ qtables="preset_name"
17
+
18
+ To apply only the subsampling setting::
19
+
20
+ subsampling="preset_name"
21
+
22
+ Example::
23
+
24
+ im.save("image_name.jpg", quality="web_high")
25
+
26
+ Subsampling
27
+ -----------
28
+
29
+ Subsampling is the practice of encoding images by implementing less resolution
30
+ for chroma information than for luma information.
31
+ (ref.: https://en.wikipedia.org/wiki/Chroma_subsampling)
32
+
33
+ Possible subsampling values are 0, 1 and 2 that correspond to 4:4:4, 4:2:2 and
34
+ 4:2:0.
35
+
36
+ You can get the subsampling of a JPEG with the
37
+ :func:`.JpegImagePlugin.get_sampling` function.
38
+
39
+ In JPEG compressed data a JPEG marker is used instead of an EXIF tag.
40
+ (ref.: https://web.archive.org/web/20240227115053/https://exiv2.org/tags.html)
41
+
42
+
43
+ Quantization tables
44
+ -------------------
45
+
46
+ They are values use by the DCT (Discrete cosine transform) to remove
47
+ *unnecessary* information from the image (the lossy part of the compression).
48
+ (ref.: https://en.wikipedia.org/wiki/Quantization_matrix#Quantization_matrices,
49
+ https://en.wikipedia.org/wiki/JPEG#Quantization)
50
+
51
+ You can get the quantization tables of a JPEG with::
52
+
53
+ im.quantization
54
+
55
+ This will return a dict with a number of lists. You can pass this dict
56
+ directly as the qtables argument when saving a JPEG.
57
+
58
+ The quantization table format in presets is a list with sublists. These formats
59
+ are interchangeable.
60
+
61
+ Libjpeg ref.:
62
+ https://web.archive.org/web/20120328125543/http://www.jpegcameras.com/libjpeg/libjpeg-3.html
63
+
64
+ """
65
+
66
+ from __future__ import annotations
67
+
68
+ # fmt: off
69
+ presets = {
70
+ 'web_low': {'subsampling': 2, # "4:2:0"
71
+ 'quantization': [
72
+ [20, 16, 25, 39, 50, 46, 62, 68,
73
+ 16, 18, 23, 38, 38, 53, 65, 68,
74
+ 25, 23, 31, 38, 53, 65, 68, 68,
75
+ 39, 38, 38, 53, 65, 68, 68, 68,
76
+ 50, 38, 53, 65, 68, 68, 68, 68,
77
+ 46, 53, 65, 68, 68, 68, 68, 68,
78
+ 62, 65, 68, 68, 68, 68, 68, 68,
79
+ 68, 68, 68, 68, 68, 68, 68, 68],
80
+ [21, 25, 32, 38, 54, 68, 68, 68,
81
+ 25, 28, 24, 38, 54, 68, 68, 68,
82
+ 32, 24, 32, 43, 66, 68, 68, 68,
83
+ 38, 38, 43, 53, 68, 68, 68, 68,
84
+ 54, 54, 66, 68, 68, 68, 68, 68,
85
+ 68, 68, 68, 68, 68, 68, 68, 68,
86
+ 68, 68, 68, 68, 68, 68, 68, 68,
87
+ 68, 68, 68, 68, 68, 68, 68, 68]
88
+ ]},
89
+ 'web_medium': {'subsampling': 2, # "4:2:0"
90
+ 'quantization': [
91
+ [16, 11, 11, 16, 23, 27, 31, 30,
92
+ 11, 12, 12, 15, 20, 23, 23, 30,
93
+ 11, 12, 13, 16, 23, 26, 35, 47,
94
+ 16, 15, 16, 23, 26, 37, 47, 64,
95
+ 23, 20, 23, 26, 39, 51, 64, 64,
96
+ 27, 23, 26, 37, 51, 64, 64, 64,
97
+ 31, 23, 35, 47, 64, 64, 64, 64,
98
+ 30, 30, 47, 64, 64, 64, 64, 64],
99
+ [17, 15, 17, 21, 20, 26, 38, 48,
100
+ 15, 19, 18, 17, 20, 26, 35, 43,
101
+ 17, 18, 20, 22, 26, 30, 46, 53,
102
+ 21, 17, 22, 28, 30, 39, 53, 64,
103
+ 20, 20, 26, 30, 39, 48, 64, 64,
104
+ 26, 26, 30, 39, 48, 63, 64, 64,
105
+ 38, 35, 46, 53, 64, 64, 64, 64,
106
+ 48, 43, 53, 64, 64, 64, 64, 64]
107
+ ]},
108
+ 'web_high': {'subsampling': 0, # "4:4:4"
109
+ 'quantization': [
110
+ [6, 4, 4, 6, 9, 11, 12, 16,
111
+ 4, 5, 5, 6, 8, 10, 12, 12,
112
+ 4, 5, 5, 6, 10, 12, 14, 19,
113
+ 6, 6, 6, 11, 12, 15, 19, 28,
114
+ 9, 8, 10, 12, 16, 20, 27, 31,
115
+ 11, 10, 12, 15, 20, 27, 31, 31,
116
+ 12, 12, 14, 19, 27, 31, 31, 31,
117
+ 16, 12, 19, 28, 31, 31, 31, 31],
118
+ [7, 7, 13, 24, 26, 31, 31, 31,
119
+ 7, 12, 16, 21, 31, 31, 31, 31,
120
+ 13, 16, 17, 31, 31, 31, 31, 31,
121
+ 24, 21, 31, 31, 31, 31, 31, 31,
122
+ 26, 31, 31, 31, 31, 31, 31, 31,
123
+ 31, 31, 31, 31, 31, 31, 31, 31,
124
+ 31, 31, 31, 31, 31, 31, 31, 31,
125
+ 31, 31, 31, 31, 31, 31, 31, 31]
126
+ ]},
127
+ 'web_very_high': {'subsampling': 0, # "4:4:4"
128
+ 'quantization': [
129
+ [2, 2, 2, 2, 3, 4, 5, 6,
130
+ 2, 2, 2, 2, 3, 4, 5, 6,
131
+ 2, 2, 2, 2, 4, 5, 7, 9,
132
+ 2, 2, 2, 4, 5, 7, 9, 12,
133
+ 3, 3, 4, 5, 8, 10, 12, 12,
134
+ 4, 4, 5, 7, 10, 12, 12, 12,
135
+ 5, 5, 7, 9, 12, 12, 12, 12,
136
+ 6, 6, 9, 12, 12, 12, 12, 12],
137
+ [3, 3, 5, 9, 13, 15, 15, 15,
138
+ 3, 4, 6, 11, 14, 12, 12, 12,
139
+ 5, 6, 9, 14, 12, 12, 12, 12,
140
+ 9, 11, 14, 12, 12, 12, 12, 12,
141
+ 13, 14, 12, 12, 12, 12, 12, 12,
142
+ 15, 12, 12, 12, 12, 12, 12, 12,
143
+ 15, 12, 12, 12, 12, 12, 12, 12,
144
+ 15, 12, 12, 12, 12, 12, 12, 12]
145
+ ]},
146
+ 'web_maximum': {'subsampling': 0, # "4:4:4"
147
+ 'quantization': [
148
+ [1, 1, 1, 1, 1, 1, 1, 1,
149
+ 1, 1, 1, 1, 1, 1, 1, 1,
150
+ 1, 1, 1, 1, 1, 1, 1, 2,
151
+ 1, 1, 1, 1, 1, 1, 2, 2,
152
+ 1, 1, 1, 1, 1, 2, 2, 3,
153
+ 1, 1, 1, 1, 2, 2, 3, 3,
154
+ 1, 1, 1, 2, 2, 3, 3, 3,
155
+ 1, 1, 2, 2, 3, 3, 3, 3],
156
+ [1, 1, 1, 2, 2, 3, 3, 3,
157
+ 1, 1, 1, 2, 3, 3, 3, 3,
158
+ 1, 1, 1, 3, 3, 3, 3, 3,
159
+ 2, 2, 3, 3, 3, 3, 3, 3,
160
+ 2, 3, 3, 3, 3, 3, 3, 3,
161
+ 3, 3, 3, 3, 3, 3, 3, 3,
162
+ 3, 3, 3, 3, 3, 3, 3, 3,
163
+ 3, 3, 3, 3, 3, 3, 3, 3]
164
+ ]},
165
+ 'low': {'subsampling': 2, # "4:2:0"
166
+ 'quantization': [
167
+ [18, 14, 14, 21, 30, 35, 34, 17,
168
+ 14, 16, 16, 19, 26, 23, 12, 12,
169
+ 14, 16, 17, 21, 23, 12, 12, 12,
170
+ 21, 19, 21, 23, 12, 12, 12, 12,
171
+ 30, 26, 23, 12, 12, 12, 12, 12,
172
+ 35, 23, 12, 12, 12, 12, 12, 12,
173
+ 34, 12, 12, 12, 12, 12, 12, 12,
174
+ 17, 12, 12, 12, 12, 12, 12, 12],
175
+ [20, 19, 22, 27, 20, 20, 17, 17,
176
+ 19, 25, 23, 14, 14, 12, 12, 12,
177
+ 22, 23, 14, 14, 12, 12, 12, 12,
178
+ 27, 14, 14, 12, 12, 12, 12, 12,
179
+ 20, 14, 12, 12, 12, 12, 12, 12,
180
+ 20, 12, 12, 12, 12, 12, 12, 12,
181
+ 17, 12, 12, 12, 12, 12, 12, 12,
182
+ 17, 12, 12, 12, 12, 12, 12, 12]
183
+ ]},
184
+ 'medium': {'subsampling': 2, # "4:2:0"
185
+ 'quantization': [
186
+ [12, 8, 8, 12, 17, 21, 24, 17,
187
+ 8, 9, 9, 11, 15, 19, 12, 12,
188
+ 8, 9, 10, 12, 19, 12, 12, 12,
189
+ 12, 11, 12, 21, 12, 12, 12, 12,
190
+ 17, 15, 19, 12, 12, 12, 12, 12,
191
+ 21, 19, 12, 12, 12, 12, 12, 12,
192
+ 24, 12, 12, 12, 12, 12, 12, 12,
193
+ 17, 12, 12, 12, 12, 12, 12, 12],
194
+ [13, 11, 13, 16, 20, 20, 17, 17,
195
+ 11, 14, 14, 14, 14, 12, 12, 12,
196
+ 13, 14, 14, 14, 12, 12, 12, 12,
197
+ 16, 14, 14, 12, 12, 12, 12, 12,
198
+ 20, 14, 12, 12, 12, 12, 12, 12,
199
+ 20, 12, 12, 12, 12, 12, 12, 12,
200
+ 17, 12, 12, 12, 12, 12, 12, 12,
201
+ 17, 12, 12, 12, 12, 12, 12, 12]
202
+ ]},
203
+ 'high': {'subsampling': 0, # "4:4:4"
204
+ 'quantization': [
205
+ [6, 4, 4, 6, 9, 11, 12, 16,
206
+ 4, 5, 5, 6, 8, 10, 12, 12,
207
+ 4, 5, 5, 6, 10, 12, 12, 12,
208
+ 6, 6, 6, 11, 12, 12, 12, 12,
209
+ 9, 8, 10, 12, 12, 12, 12, 12,
210
+ 11, 10, 12, 12, 12, 12, 12, 12,
211
+ 12, 12, 12, 12, 12, 12, 12, 12,
212
+ 16, 12, 12, 12, 12, 12, 12, 12],
213
+ [7, 7, 13, 24, 20, 20, 17, 17,
214
+ 7, 12, 16, 14, 14, 12, 12, 12,
215
+ 13, 16, 14, 14, 12, 12, 12, 12,
216
+ 24, 14, 14, 12, 12, 12, 12, 12,
217
+ 20, 14, 12, 12, 12, 12, 12, 12,
218
+ 20, 12, 12, 12, 12, 12, 12, 12,
219
+ 17, 12, 12, 12, 12, 12, 12, 12,
220
+ 17, 12, 12, 12, 12, 12, 12, 12]
221
+ ]},
222
+ 'maximum': {'subsampling': 0, # "4:4:4"
223
+ 'quantization': [
224
+ [2, 2, 2, 2, 3, 4, 5, 6,
225
+ 2, 2, 2, 2, 3, 4, 5, 6,
226
+ 2, 2, 2, 2, 4, 5, 7, 9,
227
+ 2, 2, 2, 4, 5, 7, 9, 12,
228
+ 3, 3, 4, 5, 8, 10, 12, 12,
229
+ 4, 4, 5, 7, 10, 12, 12, 12,
230
+ 5, 5, 7, 9, 12, 12, 12, 12,
231
+ 6, 6, 9, 12, 12, 12, 12, 12],
232
+ [3, 3, 5, 9, 13, 15, 15, 15,
233
+ 3, 4, 6, 10, 14, 12, 12, 12,
234
+ 5, 6, 9, 14, 12, 12, 12, 12,
235
+ 9, 10, 14, 12, 12, 12, 12, 12,
236
+ 13, 14, 12, 12, 12, 12, 12, 12,
237
+ 15, 12, 12, 12, 12, 12, 12, 12,
238
+ 15, 12, 12, 12, 12, 12, 12, 12,
239
+ 15, 12, 12, 12, 12, 12, 12, 12]
240
+ ]},
241
+ }
242
+ # fmt: on
evalkit_tf437/lib/python3.10/site-packages/PIL/PalmImagePlugin.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+
6
+ ##
7
+ # Image plugin for Palm pixmap images (output only).
8
+ ##
9
+ from __future__ import annotations
10
+
11
+ from typing import IO
12
+
13
+ from . import Image, ImageFile
14
+ from ._binary import o8
15
+ from ._binary import o16be as o16b
16
+
17
+ # fmt: off
18
+ _Palm8BitColormapValues = (
19
+ (255, 255, 255), (255, 204, 255), (255, 153, 255), (255, 102, 255),
20
+ (255, 51, 255), (255, 0, 255), (255, 255, 204), (255, 204, 204),
21
+ (255, 153, 204), (255, 102, 204), (255, 51, 204), (255, 0, 204),
22
+ (255, 255, 153), (255, 204, 153), (255, 153, 153), (255, 102, 153),
23
+ (255, 51, 153), (255, 0, 153), (204, 255, 255), (204, 204, 255),
24
+ (204, 153, 255), (204, 102, 255), (204, 51, 255), (204, 0, 255),
25
+ (204, 255, 204), (204, 204, 204), (204, 153, 204), (204, 102, 204),
26
+ (204, 51, 204), (204, 0, 204), (204, 255, 153), (204, 204, 153),
27
+ (204, 153, 153), (204, 102, 153), (204, 51, 153), (204, 0, 153),
28
+ (153, 255, 255), (153, 204, 255), (153, 153, 255), (153, 102, 255),
29
+ (153, 51, 255), (153, 0, 255), (153, 255, 204), (153, 204, 204),
30
+ (153, 153, 204), (153, 102, 204), (153, 51, 204), (153, 0, 204),
31
+ (153, 255, 153), (153, 204, 153), (153, 153, 153), (153, 102, 153),
32
+ (153, 51, 153), (153, 0, 153), (102, 255, 255), (102, 204, 255),
33
+ (102, 153, 255), (102, 102, 255), (102, 51, 255), (102, 0, 255),
34
+ (102, 255, 204), (102, 204, 204), (102, 153, 204), (102, 102, 204),
35
+ (102, 51, 204), (102, 0, 204), (102, 255, 153), (102, 204, 153),
36
+ (102, 153, 153), (102, 102, 153), (102, 51, 153), (102, 0, 153),
37
+ (51, 255, 255), (51, 204, 255), (51, 153, 255), (51, 102, 255),
38
+ (51, 51, 255), (51, 0, 255), (51, 255, 204), (51, 204, 204),
39
+ (51, 153, 204), (51, 102, 204), (51, 51, 204), (51, 0, 204),
40
+ (51, 255, 153), (51, 204, 153), (51, 153, 153), (51, 102, 153),
41
+ (51, 51, 153), (51, 0, 153), (0, 255, 255), (0, 204, 255),
42
+ (0, 153, 255), (0, 102, 255), (0, 51, 255), (0, 0, 255),
43
+ (0, 255, 204), (0, 204, 204), (0, 153, 204), (0, 102, 204),
44
+ (0, 51, 204), (0, 0, 204), (0, 255, 153), (0, 204, 153),
45
+ (0, 153, 153), (0, 102, 153), (0, 51, 153), (0, 0, 153),
46
+ (255, 255, 102), (255, 204, 102), (255, 153, 102), (255, 102, 102),
47
+ (255, 51, 102), (255, 0, 102), (255, 255, 51), (255, 204, 51),
48
+ (255, 153, 51), (255, 102, 51), (255, 51, 51), (255, 0, 51),
49
+ (255, 255, 0), (255, 204, 0), (255, 153, 0), (255, 102, 0),
50
+ (255, 51, 0), (255, 0, 0), (204, 255, 102), (204, 204, 102),
51
+ (204, 153, 102), (204, 102, 102), (204, 51, 102), (204, 0, 102),
52
+ (204, 255, 51), (204, 204, 51), (204, 153, 51), (204, 102, 51),
53
+ (204, 51, 51), (204, 0, 51), (204, 255, 0), (204, 204, 0),
54
+ (204, 153, 0), (204, 102, 0), (204, 51, 0), (204, 0, 0),
55
+ (153, 255, 102), (153, 204, 102), (153, 153, 102), (153, 102, 102),
56
+ (153, 51, 102), (153, 0, 102), (153, 255, 51), (153, 204, 51),
57
+ (153, 153, 51), (153, 102, 51), (153, 51, 51), (153, 0, 51),
58
+ (153, 255, 0), (153, 204, 0), (153, 153, 0), (153, 102, 0),
59
+ (153, 51, 0), (153, 0, 0), (102, 255, 102), (102, 204, 102),
60
+ (102, 153, 102), (102, 102, 102), (102, 51, 102), (102, 0, 102),
61
+ (102, 255, 51), (102, 204, 51), (102, 153, 51), (102, 102, 51),
62
+ (102, 51, 51), (102, 0, 51), (102, 255, 0), (102, 204, 0),
63
+ (102, 153, 0), (102, 102, 0), (102, 51, 0), (102, 0, 0),
64
+ (51, 255, 102), (51, 204, 102), (51, 153, 102), (51, 102, 102),
65
+ (51, 51, 102), (51, 0, 102), (51, 255, 51), (51, 204, 51),
66
+ (51, 153, 51), (51, 102, 51), (51, 51, 51), (51, 0, 51),
67
+ (51, 255, 0), (51, 204, 0), (51, 153, 0), (51, 102, 0),
68
+ (51, 51, 0), (51, 0, 0), (0, 255, 102), (0, 204, 102),
69
+ (0, 153, 102), (0, 102, 102), (0, 51, 102), (0, 0, 102),
70
+ (0, 255, 51), (0, 204, 51), (0, 153, 51), (0, 102, 51),
71
+ (0, 51, 51), (0, 0, 51), (0, 255, 0), (0, 204, 0),
72
+ (0, 153, 0), (0, 102, 0), (0, 51, 0), (17, 17, 17),
73
+ (34, 34, 34), (68, 68, 68), (85, 85, 85), (119, 119, 119),
74
+ (136, 136, 136), (170, 170, 170), (187, 187, 187), (221, 221, 221),
75
+ (238, 238, 238), (192, 192, 192), (128, 0, 0), (128, 0, 128),
76
+ (0, 128, 0), (0, 128, 128), (0, 0, 0), (0, 0, 0),
77
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
78
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
79
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
80
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
81
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
82
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0))
83
+ # fmt: on
84
+
85
+
86
+ # so build a prototype image to be used for palette resampling
87
+ def build_prototype_image() -> Image.Image:
88
+ image = Image.new("L", (1, len(_Palm8BitColormapValues)))
89
+ image.putdata(list(range(len(_Palm8BitColormapValues))))
90
+ palettedata: tuple[int, ...] = ()
91
+ for colormapValue in _Palm8BitColormapValues:
92
+ palettedata += colormapValue
93
+ palettedata += (0, 0, 0) * (256 - len(_Palm8BitColormapValues))
94
+ image.putpalette(palettedata)
95
+ return image
96
+
97
+
98
+ Palm8BitColormapImage = build_prototype_image()
99
+
100
+ # OK, we now have in Palm8BitColormapImage,
101
+ # a "P"-mode image with the right palette
102
+ #
103
+ # --------------------------------------------------------------------
104
+
105
+ _FLAGS = {"custom-colormap": 0x4000, "is-compressed": 0x8000, "has-transparent": 0x2000}
106
+
107
+ _COMPRESSION_TYPES = {"none": 0xFF, "rle": 0x01, "scanline": 0x00}
108
+
109
+
110
+ #
111
+ # --------------------------------------------------------------------
112
+
113
+ ##
114
+ # (Internal) Image save plugin for the Palm format.
115
+
116
+
117
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
118
+ if im.mode == "P":
119
+ # we assume this is a color Palm image with the standard colormap,
120
+ # unless the "info" dict has a "custom-colormap" field
121
+
122
+ rawmode = "P"
123
+ bpp = 8
124
+ version = 1
125
+
126
+ elif im.mode == "L":
127
+ if im.encoderinfo.get("bpp") in (1, 2, 4):
128
+ # this is 8-bit grayscale, so we shift it to get the high-order bits,
129
+ # and invert it because
130
+ # Palm does grayscale from white (0) to black (1)
131
+ bpp = im.encoderinfo["bpp"]
132
+ maxval = (1 << bpp) - 1
133
+ shift = 8 - bpp
134
+ im = im.point(lambda x: maxval - (x >> shift))
135
+ elif im.info.get("bpp") in (1, 2, 4):
136
+ # here we assume that even though the inherent mode is 8-bit grayscale,
137
+ # only the lower bpp bits are significant.
138
+ # We invert them to match the Palm.
139
+ bpp = im.info["bpp"]
140
+ maxval = (1 << bpp) - 1
141
+ im = im.point(lambda x: maxval - (x & maxval))
142
+ else:
143
+ msg = f"cannot write mode {im.mode} as Palm"
144
+ raise OSError(msg)
145
+
146
+ # we ignore the palette here
147
+ im._mode = "P"
148
+ rawmode = f"P;{bpp}"
149
+ version = 1
150
+
151
+ elif im.mode == "1":
152
+ # monochrome -- write it inverted, as is the Palm standard
153
+ rawmode = "1;I"
154
+ bpp = 1
155
+ version = 0
156
+
157
+ else:
158
+ msg = f"cannot write mode {im.mode} as Palm"
159
+ raise OSError(msg)
160
+
161
+ #
162
+ # make sure image data is available
163
+ im.load()
164
+
165
+ # write header
166
+
167
+ cols = im.size[0]
168
+ rows = im.size[1]
169
+
170
+ rowbytes = int((cols + (16 // bpp - 1)) / (16 // bpp)) * 2
171
+ transparent_index = 0
172
+ compression_type = _COMPRESSION_TYPES["none"]
173
+
174
+ flags = 0
175
+ if im.mode == "P" and "custom-colormap" in im.info:
176
+ flags = flags & _FLAGS["custom-colormap"]
177
+ colormapsize = 4 * 256 + 2
178
+ colormapmode = im.palette.mode
179
+ colormap = im.getdata().getpalette()
180
+ else:
181
+ colormapsize = 0
182
+
183
+ if "offset" in im.info:
184
+ offset = (rowbytes * rows + 16 + 3 + colormapsize) // 4
185
+ else:
186
+ offset = 0
187
+
188
+ fp.write(o16b(cols) + o16b(rows) + o16b(rowbytes) + o16b(flags))
189
+ fp.write(o8(bpp))
190
+ fp.write(o8(version))
191
+ fp.write(o16b(offset))
192
+ fp.write(o8(transparent_index))
193
+ fp.write(o8(compression_type))
194
+ fp.write(o16b(0)) # reserved by Palm
195
+
196
+ # now write colormap if necessary
197
+
198
+ if colormapsize > 0:
199
+ fp.write(o16b(256))
200
+ for i in range(256):
201
+ fp.write(o8(i))
202
+ if colormapmode == "RGB":
203
+ fp.write(
204
+ o8(colormap[3 * i])
205
+ + o8(colormap[3 * i + 1])
206
+ + o8(colormap[3 * i + 2])
207
+ )
208
+ elif colormapmode == "RGBA":
209
+ fp.write(
210
+ o8(colormap[4 * i])
211
+ + o8(colormap[4 * i + 1])
212
+ + o8(colormap[4 * i + 2])
213
+ )
214
+
215
+ # now convert data to raw form
216
+ ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, rowbytes, 1))])
217
+
218
+ if hasattr(fp, "flush"):
219
+ fp.flush()
220
+
221
+
222
+ #
223
+ # --------------------------------------------------------------------
224
+
225
+ Image.register_save("Palm", _save)
226
+
227
+ Image.register_extension("Palm", ".palm")
228
+
229
+ Image.register_mime("Palm", "image/palm")
evalkit_tf437/lib/python3.10/site-packages/PIL/PcfFontFile.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # THIS IS WORK IN PROGRESS
3
+ #
4
+ # The Python Imaging Library
5
+ # $Id$
6
+ #
7
+ # portable compiled font file parser
8
+ #
9
+ # history:
10
+ # 1997-08-19 fl created
11
+ # 2003-09-13 fl fixed loading of unicode fonts
12
+ #
13
+ # Copyright (c) 1997-2003 by Secret Labs AB.
14
+ # Copyright (c) 1997-2003 by Fredrik Lundh.
15
+ #
16
+ # See the README file for information on usage and redistribution.
17
+ #
18
+ from __future__ import annotations
19
+
20
+ import io
21
+ from typing import BinaryIO, Callable
22
+
23
+ from . import FontFile, Image
24
+ from ._binary import i8
25
+ from ._binary import i16be as b16
26
+ from ._binary import i16le as l16
27
+ from ._binary import i32be as b32
28
+ from ._binary import i32le as l32
29
+
30
+ # --------------------------------------------------------------------
31
+ # declarations
32
+
33
+ PCF_MAGIC = 0x70636601 # "\x01fcp"
34
+
35
+ PCF_PROPERTIES = 1 << 0
36
+ PCF_ACCELERATORS = 1 << 1
37
+ PCF_METRICS = 1 << 2
38
+ PCF_BITMAPS = 1 << 3
39
+ PCF_INK_METRICS = 1 << 4
40
+ PCF_BDF_ENCODINGS = 1 << 5
41
+ PCF_SWIDTHS = 1 << 6
42
+ PCF_GLYPH_NAMES = 1 << 7
43
+ PCF_BDF_ACCELERATORS = 1 << 8
44
+
45
+ BYTES_PER_ROW: list[Callable[[int], int]] = [
46
+ lambda bits: ((bits + 7) >> 3),
47
+ lambda bits: ((bits + 15) >> 3) & ~1,
48
+ lambda bits: ((bits + 31) >> 3) & ~3,
49
+ lambda bits: ((bits + 63) >> 3) & ~7,
50
+ ]
51
+
52
+
53
+ def sz(s: bytes, o: int) -> bytes:
54
+ return s[o : s.index(b"\0", o)]
55
+
56
+
57
+ class PcfFontFile(FontFile.FontFile):
58
+ """Font file plugin for the X11 PCF format."""
59
+
60
+ name = "name"
61
+
62
+ def __init__(self, fp: BinaryIO, charset_encoding: str = "iso8859-1"):
63
+ self.charset_encoding = charset_encoding
64
+
65
+ magic = l32(fp.read(4))
66
+ if magic != PCF_MAGIC:
67
+ msg = "not a PCF file"
68
+ raise SyntaxError(msg)
69
+
70
+ super().__init__()
71
+
72
+ count = l32(fp.read(4))
73
+ self.toc = {}
74
+ for i in range(count):
75
+ type = l32(fp.read(4))
76
+ self.toc[type] = l32(fp.read(4)), l32(fp.read(4)), l32(fp.read(4))
77
+
78
+ self.fp = fp
79
+
80
+ self.info = self._load_properties()
81
+
82
+ metrics = self._load_metrics()
83
+ bitmaps = self._load_bitmaps(metrics)
84
+ encoding = self._load_encoding()
85
+
86
+ #
87
+ # create glyph structure
88
+
89
+ for ch, ix in enumerate(encoding):
90
+ if ix is not None:
91
+ (
92
+ xsize,
93
+ ysize,
94
+ left,
95
+ right,
96
+ width,
97
+ ascent,
98
+ descent,
99
+ attributes,
100
+ ) = metrics[ix]
101
+ self.glyph[ch] = (
102
+ (width, 0),
103
+ (left, descent - ysize, xsize + left, descent),
104
+ (0, 0, xsize, ysize),
105
+ bitmaps[ix],
106
+ )
107
+
108
+ def _getformat(
109
+ self, tag: int
110
+ ) -> tuple[BinaryIO, int, Callable[[bytes], int], Callable[[bytes], int]]:
111
+ format, size, offset = self.toc[tag]
112
+
113
+ fp = self.fp
114
+ fp.seek(offset)
115
+
116
+ format = l32(fp.read(4))
117
+
118
+ if format & 4:
119
+ i16, i32 = b16, b32
120
+ else:
121
+ i16, i32 = l16, l32
122
+
123
+ return fp, format, i16, i32
124
+
125
+ def _load_properties(self) -> dict[bytes, bytes | int]:
126
+ #
127
+ # font properties
128
+
129
+ properties = {}
130
+
131
+ fp, format, i16, i32 = self._getformat(PCF_PROPERTIES)
132
+
133
+ nprops = i32(fp.read(4))
134
+
135
+ # read property description
136
+ p = [(i32(fp.read(4)), i8(fp.read(1)), i32(fp.read(4))) for _ in range(nprops)]
137
+
138
+ if nprops & 3:
139
+ fp.seek(4 - (nprops & 3), io.SEEK_CUR) # pad
140
+
141
+ data = fp.read(i32(fp.read(4)))
142
+
143
+ for k, s, v in p:
144
+ property_value: bytes | int = sz(data, v) if s else v
145
+ properties[sz(data, k)] = property_value
146
+
147
+ return properties
148
+
149
+ def _load_metrics(self) -> list[tuple[int, int, int, int, int, int, int, int]]:
150
+ #
151
+ # font metrics
152
+
153
+ metrics: list[tuple[int, int, int, int, int, int, int, int]] = []
154
+
155
+ fp, format, i16, i32 = self._getformat(PCF_METRICS)
156
+
157
+ append = metrics.append
158
+
159
+ if (format & 0xFF00) == 0x100:
160
+ # "compressed" metrics
161
+ for i in range(i16(fp.read(2))):
162
+ left = i8(fp.read(1)) - 128
163
+ right = i8(fp.read(1)) - 128
164
+ width = i8(fp.read(1)) - 128
165
+ ascent = i8(fp.read(1)) - 128
166
+ descent = i8(fp.read(1)) - 128
167
+ xsize = right - left
168
+ ysize = ascent + descent
169
+ append((xsize, ysize, left, right, width, ascent, descent, 0))
170
+
171
+ else:
172
+ # "jumbo" metrics
173
+ for i in range(i32(fp.read(4))):
174
+ left = i16(fp.read(2))
175
+ right = i16(fp.read(2))
176
+ width = i16(fp.read(2))
177
+ ascent = i16(fp.read(2))
178
+ descent = i16(fp.read(2))
179
+ attributes = i16(fp.read(2))
180
+ xsize = right - left
181
+ ysize = ascent + descent
182
+ append((xsize, ysize, left, right, width, ascent, descent, attributes))
183
+
184
+ return metrics
185
+
186
+ def _load_bitmaps(
187
+ self, metrics: list[tuple[int, int, int, int, int, int, int, int]]
188
+ ) -> list[Image.Image]:
189
+ #
190
+ # bitmap data
191
+
192
+ fp, format, i16, i32 = self._getformat(PCF_BITMAPS)
193
+
194
+ nbitmaps = i32(fp.read(4))
195
+
196
+ if nbitmaps != len(metrics):
197
+ msg = "Wrong number of bitmaps"
198
+ raise OSError(msg)
199
+
200
+ offsets = [i32(fp.read(4)) for _ in range(nbitmaps)]
201
+
202
+ bitmap_sizes = [i32(fp.read(4)) for _ in range(4)]
203
+
204
+ # byteorder = format & 4 # non-zero => MSB
205
+ bitorder = format & 8 # non-zero => MSB
206
+ padindex = format & 3
207
+
208
+ bitmapsize = bitmap_sizes[padindex]
209
+ offsets.append(bitmapsize)
210
+
211
+ data = fp.read(bitmapsize)
212
+
213
+ pad = BYTES_PER_ROW[padindex]
214
+ mode = "1;R"
215
+ if bitorder:
216
+ mode = "1"
217
+
218
+ bitmaps = []
219
+ for i in range(nbitmaps):
220
+ xsize, ysize = metrics[i][:2]
221
+ b, e = offsets[i : i + 2]
222
+ bitmaps.append(
223
+ Image.frombytes("1", (xsize, ysize), data[b:e], "raw", mode, pad(xsize))
224
+ )
225
+
226
+ return bitmaps
227
+
228
+ def _load_encoding(self) -> list[int | None]:
229
+ fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS)
230
+
231
+ first_col, last_col = i16(fp.read(2)), i16(fp.read(2))
232
+ first_row, last_row = i16(fp.read(2)), i16(fp.read(2))
233
+
234
+ i16(fp.read(2)) # default
235
+
236
+ nencoding = (last_col - first_col + 1) * (last_row - first_row + 1)
237
+
238
+ # map character code to bitmap index
239
+ encoding: list[int | None] = [None] * min(256, nencoding)
240
+
241
+ encoding_offsets = [i16(fp.read(2)) for _ in range(nencoding)]
242
+
243
+ for i in range(first_col, len(encoding)):
244
+ try:
245
+ encoding_offset = encoding_offsets[
246
+ ord(bytearray([i]).decode(self.charset_encoding))
247
+ ]
248
+ if encoding_offset != 0xFFFF:
249
+ encoding[i] = encoding_offset
250
+ except UnicodeDecodeError:
251
+ # character is not supported in selected encoding
252
+ pass
253
+
254
+ return encoding
evalkit_tf437/lib/python3.10/site-packages/PIL/PngImagePlugin.py ADDED
@@ -0,0 +1,1489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # PNG support code
6
+ #
7
+ # See "PNG (Portable Network Graphics) Specification, version 1.0;
8
+ # W3C Recommendation", 1996-10-01, Thomas Boutell (ed.).
9
+ #
10
+ # history:
11
+ # 1996-05-06 fl Created (couldn't resist it)
12
+ # 1996-12-14 fl Upgraded, added read and verify support (0.2)
13
+ # 1996-12-15 fl Separate PNG stream parser
14
+ # 1996-12-29 fl Added write support, added getchunks
15
+ # 1996-12-30 fl Eliminated circular references in decoder (0.3)
16
+ # 1998-07-12 fl Read/write 16-bit images as mode I (0.4)
17
+ # 2001-02-08 fl Added transparency support (from Zircon) (0.5)
18
+ # 2001-04-16 fl Don't close data source in "open" method (0.6)
19
+ # 2004-02-24 fl Don't even pretend to support interlaced files (0.7)
20
+ # 2004-08-31 fl Do basic sanity check on chunk identifiers (0.8)
21
+ # 2004-09-20 fl Added PngInfo chunk container
22
+ # 2004-12-18 fl Added DPI read support (based on code by Niki Spahiev)
23
+ # 2008-08-13 fl Added tRNS support for RGB images
24
+ # 2009-03-06 fl Support for preserving ICC profiles (by Florian Hoech)
25
+ # 2009-03-08 fl Added zTXT support (from Lowell Alleman)
26
+ # 2009-03-29 fl Read interlaced PNG files (from Conrado Porto Lopes Gouvua)
27
+ #
28
+ # Copyright (c) 1997-2009 by Secret Labs AB
29
+ # Copyright (c) 1996 by Fredrik Lundh
30
+ #
31
+ # See the README file for information on usage and redistribution.
32
+ #
33
+ from __future__ import annotations
34
+
35
+ import itertools
36
+ import logging
37
+ import re
38
+ import struct
39
+ import warnings
40
+ import zlib
41
+ from enum import IntEnum
42
+ from typing import IO, TYPE_CHECKING, Any, NoReturn
43
+
44
+ from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence
45
+ from ._binary import i16be as i16
46
+ from ._binary import i32be as i32
47
+ from ._binary import o8
48
+ from ._binary import o16be as o16
49
+ from ._binary import o32be as o32
50
+
51
+ if TYPE_CHECKING:
52
+ from . import _imaging
53
+
54
+ logger = logging.getLogger(__name__)
55
+
56
+ is_cid = re.compile(rb"\w\w\w\w").match
57
+
58
+
59
+ _MAGIC = b"\211PNG\r\n\032\n"
60
+
61
+
62
+ _MODES = {
63
+ # supported bits/color combinations, and corresponding modes/rawmodes
64
+ # Grayscale
65
+ (1, 0): ("1", "1"),
66
+ (2, 0): ("L", "L;2"),
67
+ (4, 0): ("L", "L;4"),
68
+ (8, 0): ("L", "L"),
69
+ (16, 0): ("I;16", "I;16B"),
70
+ # Truecolour
71
+ (8, 2): ("RGB", "RGB"),
72
+ (16, 2): ("RGB", "RGB;16B"),
73
+ # Indexed-colour
74
+ (1, 3): ("P", "P;1"),
75
+ (2, 3): ("P", "P;2"),
76
+ (4, 3): ("P", "P;4"),
77
+ (8, 3): ("P", "P"),
78
+ # Grayscale with alpha
79
+ (8, 4): ("LA", "LA"),
80
+ (16, 4): ("RGBA", "LA;16B"), # LA;16B->LA not yet available
81
+ # Truecolour with alpha
82
+ (8, 6): ("RGBA", "RGBA"),
83
+ (16, 6): ("RGBA", "RGBA;16B"),
84
+ }
85
+
86
+
87
+ _simple_palette = re.compile(b"^\xff*\x00\xff*$")
88
+
89
+ MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK
90
+ """
91
+ Maximum decompressed size for a iTXt or zTXt chunk.
92
+ Eliminates decompression bombs where compressed chunks can expand 1000x.
93
+ See :ref:`Text in PNG File Format<png-text>`.
94
+ """
95
+ MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK
96
+ """
97
+ Set the maximum total text chunk size.
98
+ See :ref:`Text in PNG File Format<png-text>`.
99
+ """
100
+
101
+
102
+ # APNG frame disposal modes
103
+ class Disposal(IntEnum):
104
+ OP_NONE = 0
105
+ """
106
+ No disposal is done on this frame before rendering the next frame.
107
+ See :ref:`Saving APNG sequences<apng-saving>`.
108
+ """
109
+ OP_BACKGROUND = 1
110
+ """
111
+ This frame’s modified region is cleared to fully transparent black before rendering
112
+ the next frame.
113
+ See :ref:`Saving APNG sequences<apng-saving>`.
114
+ """
115
+ OP_PREVIOUS = 2
116
+ """
117
+ This frame’s modified region is reverted to the previous frame’s contents before
118
+ rendering the next frame.
119
+ See :ref:`Saving APNG sequences<apng-saving>`.
120
+ """
121
+
122
+
123
+ # APNG frame blend modes
124
+ class Blend(IntEnum):
125
+ OP_SOURCE = 0
126
+ """
127
+ All color components of this frame, including alpha, overwrite the previous output
128
+ image contents.
129
+ See :ref:`Saving APNG sequences<apng-saving>`.
130
+ """
131
+ OP_OVER = 1
132
+ """
133
+ This frame should be alpha composited with the previous output image contents.
134
+ See :ref:`Saving APNG sequences<apng-saving>`.
135
+ """
136
+
137
+
138
+ def _safe_zlib_decompress(s):
139
+ dobj = zlib.decompressobj()
140
+ plaintext = dobj.decompress(s, MAX_TEXT_CHUNK)
141
+ if dobj.unconsumed_tail:
142
+ msg = "Decompressed Data Too Large"
143
+ raise ValueError(msg)
144
+ return plaintext
145
+
146
+
147
+ def _crc32(data, seed=0):
148
+ return zlib.crc32(data, seed) & 0xFFFFFFFF
149
+
150
+
151
+ # --------------------------------------------------------------------
152
+ # Support classes. Suitable for PNG and related formats like MNG etc.
153
+
154
+
155
+ class ChunkStream:
156
+ def __init__(self, fp: IO[bytes]) -> None:
157
+ self.fp: IO[bytes] | None = fp
158
+ self.queue: list[tuple[bytes, int, int]] | None = []
159
+
160
+ def read(self) -> tuple[bytes, int, int]:
161
+ """Fetch a new chunk. Returns header information."""
162
+ cid = None
163
+
164
+ assert self.fp is not None
165
+ if self.queue:
166
+ cid, pos, length = self.queue.pop()
167
+ self.fp.seek(pos)
168
+ else:
169
+ s = self.fp.read(8)
170
+ cid = s[4:]
171
+ pos = self.fp.tell()
172
+ length = i32(s)
173
+
174
+ if not is_cid(cid):
175
+ if not ImageFile.LOAD_TRUNCATED_IMAGES:
176
+ msg = f"broken PNG file (chunk {repr(cid)})"
177
+ raise SyntaxError(msg)
178
+
179
+ return cid, pos, length
180
+
181
+ def __enter__(self) -> ChunkStream:
182
+ return self
183
+
184
+ def __exit__(self, *args: object) -> None:
185
+ self.close()
186
+
187
+ def close(self) -> None:
188
+ self.queue = self.fp = None
189
+
190
+ def push(self, cid: bytes, pos: int, length: int) -> None:
191
+ assert self.queue is not None
192
+ self.queue.append((cid, pos, length))
193
+
194
+ def call(self, cid, pos, length):
195
+ """Call the appropriate chunk handler"""
196
+
197
+ logger.debug("STREAM %r %s %s", cid, pos, length)
198
+ return getattr(self, f"chunk_{cid.decode('ascii')}")(pos, length)
199
+
200
+ def crc(self, cid: bytes, data: bytes) -> None:
201
+ """Read and verify checksum"""
202
+
203
+ # Skip CRC checks for ancillary chunks if allowed to load truncated
204
+ # images
205
+ # 5th byte of first char is 1 [specs, section 5.4]
206
+ if ImageFile.LOAD_TRUNCATED_IMAGES and (cid[0] >> 5 & 1):
207
+ self.crc_skip(cid, data)
208
+ return
209
+
210
+ assert self.fp is not None
211
+ try:
212
+ crc1 = _crc32(data, _crc32(cid))
213
+ crc2 = i32(self.fp.read(4))
214
+ if crc1 != crc2:
215
+ msg = f"broken PNG file (bad header checksum in {repr(cid)})"
216
+ raise SyntaxError(msg)
217
+ except struct.error as e:
218
+ msg = f"broken PNG file (incomplete checksum in {repr(cid)})"
219
+ raise SyntaxError(msg) from e
220
+
221
+ def crc_skip(self, cid: bytes, data: bytes) -> None:
222
+ """Read checksum"""
223
+
224
+ assert self.fp is not None
225
+ self.fp.read(4)
226
+
227
+ def verify(self, endchunk: bytes = b"IEND") -> list[bytes]:
228
+ # Simple approach; just calculate checksum for all remaining
229
+ # blocks. Must be called directly after open.
230
+
231
+ cids = []
232
+
233
+ while True:
234
+ try:
235
+ cid, pos, length = self.read()
236
+ except struct.error as e:
237
+ msg = "truncated PNG file"
238
+ raise OSError(msg) from e
239
+
240
+ if cid == endchunk:
241
+ break
242
+ self.crc(cid, ImageFile._safe_read(self.fp, length))
243
+ cids.append(cid)
244
+
245
+ return cids
246
+
247
+
248
+ class iTXt(str):
249
+ """
250
+ Subclass of string to allow iTXt chunks to look like strings while
251
+ keeping their extra information
252
+
253
+ """
254
+
255
+ lang: str | bytes | None
256
+ tkey: str | bytes | None
257
+
258
+ @staticmethod
259
+ def __new__(cls, text, lang=None, tkey=None):
260
+ """
261
+ :param cls: the class to use when creating the instance
262
+ :param text: value for this key
263
+ :param lang: language code
264
+ :param tkey: UTF-8 version of the key name
265
+ """
266
+
267
+ self = str.__new__(cls, text)
268
+ self.lang = lang
269
+ self.tkey = tkey
270
+ return self
271
+
272
+
273
+ class PngInfo:
274
+ """
275
+ PNG chunk container (for use with save(pnginfo=))
276
+
277
+ """
278
+
279
+ def __init__(self) -> None:
280
+ self.chunks: list[tuple[bytes, bytes, bool]] = []
281
+
282
+ def add(self, cid: bytes, data: bytes, after_idat: bool = False) -> None:
283
+ """Appends an arbitrary chunk. Use with caution.
284
+
285
+ :param cid: a byte string, 4 bytes long.
286
+ :param data: a byte string of the encoded data
287
+ :param after_idat: for use with private chunks. Whether the chunk
288
+ should be written after IDAT
289
+
290
+ """
291
+
292
+ self.chunks.append((cid, data, after_idat))
293
+
294
+ def add_itxt(
295
+ self,
296
+ key: str | bytes,
297
+ value: str | bytes,
298
+ lang: str | bytes = "",
299
+ tkey: str | bytes = "",
300
+ zip: bool = False,
301
+ ) -> None:
302
+ """Appends an iTXt chunk.
303
+
304
+ :param key: latin-1 encodable text key name
305
+ :param value: value for this key
306
+ :param lang: language code
307
+ :param tkey: UTF-8 version of the key name
308
+ :param zip: compression flag
309
+
310
+ """
311
+
312
+ if not isinstance(key, bytes):
313
+ key = key.encode("latin-1", "strict")
314
+ if not isinstance(value, bytes):
315
+ value = value.encode("utf-8", "strict")
316
+ if not isinstance(lang, bytes):
317
+ lang = lang.encode("utf-8", "strict")
318
+ if not isinstance(tkey, bytes):
319
+ tkey = tkey.encode("utf-8", "strict")
320
+
321
+ if zip:
322
+ self.add(
323
+ b"iTXt",
324
+ key + b"\0\x01\0" + lang + b"\0" + tkey + b"\0" + zlib.compress(value),
325
+ )
326
+ else:
327
+ self.add(b"iTXt", key + b"\0\0\0" + lang + b"\0" + tkey + b"\0" + value)
328
+
329
+ def add_text(
330
+ self, key: str | bytes, value: str | bytes | iTXt, zip: bool = False
331
+ ) -> None:
332
+ """Appends a text chunk.
333
+
334
+ :param key: latin-1 encodable text key name
335
+ :param value: value for this key, text or an
336
+ :py:class:`PIL.PngImagePlugin.iTXt` instance
337
+ :param zip: compression flag
338
+
339
+ """
340
+ if isinstance(value, iTXt):
341
+ return self.add_itxt(
342
+ key,
343
+ value,
344
+ value.lang if value.lang is not None else b"",
345
+ value.tkey if value.tkey is not None else b"",
346
+ zip=zip,
347
+ )
348
+
349
+ # The tEXt chunk stores latin-1 text
350
+ if not isinstance(value, bytes):
351
+ try:
352
+ value = value.encode("latin-1", "strict")
353
+ except UnicodeError:
354
+ return self.add_itxt(key, value, zip=zip)
355
+
356
+ if not isinstance(key, bytes):
357
+ key = key.encode("latin-1", "strict")
358
+
359
+ if zip:
360
+ self.add(b"zTXt", key + b"\0\0" + zlib.compress(value))
361
+ else:
362
+ self.add(b"tEXt", key + b"\0" + value)
363
+
364
+
365
+ # --------------------------------------------------------------------
366
+ # PNG image stream (IHDR/IEND)
367
+
368
+
369
+ class PngStream(ChunkStream):
370
+ def __init__(self, fp):
371
+ super().__init__(fp)
372
+
373
+ # local copies of Image attributes
374
+ self.im_info = {}
375
+ self.im_text = {}
376
+ self.im_size = (0, 0)
377
+ self.im_mode = None
378
+ self.im_tile = None
379
+ self.im_palette = None
380
+ self.im_custom_mimetype = None
381
+ self.im_n_frames = None
382
+ self._seq_num = None
383
+ self.rewind_state = None
384
+
385
+ self.text_memory = 0
386
+
387
+ def check_text_memory(self, chunklen: int) -> None:
388
+ self.text_memory += chunklen
389
+ if self.text_memory > MAX_TEXT_MEMORY:
390
+ msg = (
391
+ "Too much memory used in text chunks: "
392
+ f"{self.text_memory}>MAX_TEXT_MEMORY"
393
+ )
394
+ raise ValueError(msg)
395
+
396
+ def save_rewind(self) -> None:
397
+ self.rewind_state = {
398
+ "info": self.im_info.copy(),
399
+ "tile": self.im_tile,
400
+ "seq_num": self._seq_num,
401
+ }
402
+
403
+ def rewind(self) -> None:
404
+ self.im_info = self.rewind_state["info"].copy()
405
+ self.im_tile = self.rewind_state["tile"]
406
+ self._seq_num = self.rewind_state["seq_num"]
407
+
408
+ def chunk_iCCP(self, pos: int, length: int) -> bytes:
409
+ # ICC profile
410
+ s = ImageFile._safe_read(self.fp, length)
411
+ # according to PNG spec, the iCCP chunk contains:
412
+ # Profile name 1-79 bytes (character string)
413
+ # Null separator 1 byte (null character)
414
+ # Compression method 1 byte (0)
415
+ # Compressed profile n bytes (zlib with deflate compression)
416
+ i = s.find(b"\0")
417
+ logger.debug("iCCP profile name %r", s[:i])
418
+ comp_method = s[i + 1]
419
+ logger.debug("Compression method %s", comp_method)
420
+ if comp_method != 0:
421
+ msg = f"Unknown compression method {comp_method} in iCCP chunk"
422
+ raise SyntaxError(msg)
423
+ try:
424
+ icc_profile = _safe_zlib_decompress(s[i + 2 :])
425
+ except ValueError:
426
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
427
+ icc_profile = None
428
+ else:
429
+ raise
430
+ except zlib.error:
431
+ icc_profile = None # FIXME
432
+ self.im_info["icc_profile"] = icc_profile
433
+ return s
434
+
435
+ def chunk_IHDR(self, pos: int, length: int) -> bytes:
436
+ # image header
437
+ s = ImageFile._safe_read(self.fp, length)
438
+ if length < 13:
439
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
440
+ return s
441
+ msg = "Truncated IHDR chunk"
442
+ raise ValueError(msg)
443
+ self.im_size = i32(s, 0), i32(s, 4)
444
+ try:
445
+ self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])]
446
+ except Exception:
447
+ pass
448
+ if s[12]:
449
+ self.im_info["interlace"] = 1
450
+ if s[11]:
451
+ msg = "unknown filter category"
452
+ raise SyntaxError(msg)
453
+ return s
454
+
455
+ def chunk_IDAT(self, pos: int, length: int) -> NoReturn:
456
+ # image data
457
+ if "bbox" in self.im_info:
458
+ tile = [("zip", self.im_info["bbox"], pos, self.im_rawmode)]
459
+ else:
460
+ if self.im_n_frames is not None:
461
+ self.im_info["default_image"] = True
462
+ tile = [("zip", (0, 0) + self.im_size, pos, self.im_rawmode)]
463
+ self.im_tile = tile
464
+ self.im_idat = length
465
+ msg = "image data found"
466
+ raise EOFError(msg)
467
+
468
+ def chunk_IEND(self, pos: int, length: int) -> NoReturn:
469
+ msg = "end of PNG image"
470
+ raise EOFError(msg)
471
+
472
+ def chunk_PLTE(self, pos: int, length: int) -> bytes:
473
+ # palette
474
+ s = ImageFile._safe_read(self.fp, length)
475
+ if self.im_mode == "P":
476
+ self.im_palette = "RGB", s
477
+ return s
478
+
479
+ def chunk_tRNS(self, pos: int, length: int) -> bytes:
480
+ # transparency
481
+ s = ImageFile._safe_read(self.fp, length)
482
+ if self.im_mode == "P":
483
+ if _simple_palette.match(s):
484
+ # tRNS contains only one full-transparent entry,
485
+ # other entries are full opaque
486
+ i = s.find(b"\0")
487
+ if i >= 0:
488
+ self.im_info["transparency"] = i
489
+ else:
490
+ # otherwise, we have a byte string with one alpha value
491
+ # for each palette entry
492
+ self.im_info["transparency"] = s
493
+ elif self.im_mode in ("1", "L", "I;16"):
494
+ self.im_info["transparency"] = i16(s)
495
+ elif self.im_mode == "RGB":
496
+ self.im_info["transparency"] = i16(s), i16(s, 2), i16(s, 4)
497
+ return s
498
+
499
+ def chunk_gAMA(self, pos: int, length: int) -> bytes:
500
+ # gamma setting
501
+ s = ImageFile._safe_read(self.fp, length)
502
+ self.im_info["gamma"] = i32(s) / 100000.0
503
+ return s
504
+
505
+ def chunk_cHRM(self, pos: int, length: int) -> bytes:
506
+ # chromaticity, 8 unsigned ints, actual value is scaled by 100,000
507
+ # WP x,y, Red x,y, Green x,y Blue x,y
508
+
509
+ s = ImageFile._safe_read(self.fp, length)
510
+ raw_vals = struct.unpack(">%dI" % (len(s) // 4), s)
511
+ self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals)
512
+ return s
513
+
514
+ def chunk_sRGB(self, pos: int, length: int) -> bytes:
515
+ # srgb rendering intent, 1 byte
516
+ # 0 perceptual
517
+ # 1 relative colorimetric
518
+ # 2 saturation
519
+ # 3 absolute colorimetric
520
+
521
+ s = ImageFile._safe_read(self.fp, length)
522
+ if length < 1:
523
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
524
+ return s
525
+ msg = "Truncated sRGB chunk"
526
+ raise ValueError(msg)
527
+ self.im_info["srgb"] = s[0]
528
+ return s
529
+
530
+ def chunk_pHYs(self, pos: int, length: int) -> bytes:
531
+ # pixels per unit
532
+ s = ImageFile._safe_read(self.fp, length)
533
+ if length < 9:
534
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
535
+ return s
536
+ msg = "Truncated pHYs chunk"
537
+ raise ValueError(msg)
538
+ px, py = i32(s, 0), i32(s, 4)
539
+ unit = s[8]
540
+ if unit == 1: # meter
541
+ dpi = px * 0.0254, py * 0.0254
542
+ self.im_info["dpi"] = dpi
543
+ elif unit == 0:
544
+ self.im_info["aspect"] = px, py
545
+ return s
546
+
547
+ def chunk_tEXt(self, pos: int, length: int) -> bytes:
548
+ # text
549
+ s = ImageFile._safe_read(self.fp, length)
550
+ try:
551
+ k, v = s.split(b"\0", 1)
552
+ except ValueError:
553
+ # fallback for broken tEXt tags
554
+ k = s
555
+ v = b""
556
+ if k:
557
+ k = k.decode("latin-1", "strict")
558
+ v_str = v.decode("latin-1", "replace")
559
+
560
+ self.im_info[k] = v if k == "exif" else v_str
561
+ self.im_text[k] = v_str
562
+ self.check_text_memory(len(v_str))
563
+
564
+ return s
565
+
566
+ def chunk_zTXt(self, pos: int, length: int) -> bytes:
567
+ # compressed text
568
+ s = ImageFile._safe_read(self.fp, length)
569
+ try:
570
+ k, v = s.split(b"\0", 1)
571
+ except ValueError:
572
+ k = s
573
+ v = b""
574
+ if v:
575
+ comp_method = v[0]
576
+ else:
577
+ comp_method = 0
578
+ if comp_method != 0:
579
+ msg = f"Unknown compression method {comp_method} in zTXt chunk"
580
+ raise SyntaxError(msg)
581
+ try:
582
+ v = _safe_zlib_decompress(v[1:])
583
+ except ValueError:
584
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
585
+ v = b""
586
+ else:
587
+ raise
588
+ except zlib.error:
589
+ v = b""
590
+
591
+ if k:
592
+ k = k.decode("latin-1", "strict")
593
+ v = v.decode("latin-1", "replace")
594
+
595
+ self.im_info[k] = self.im_text[k] = v
596
+ self.check_text_memory(len(v))
597
+
598
+ return s
599
+
600
+ def chunk_iTXt(self, pos: int, length: int) -> bytes:
601
+ # international text
602
+ r = s = ImageFile._safe_read(self.fp, length)
603
+ try:
604
+ k, r = r.split(b"\0", 1)
605
+ except ValueError:
606
+ return s
607
+ if len(r) < 2:
608
+ return s
609
+ cf, cm, r = r[0], r[1], r[2:]
610
+ try:
611
+ lang, tk, v = r.split(b"\0", 2)
612
+ except ValueError:
613
+ return s
614
+ if cf != 0:
615
+ if cm == 0:
616
+ try:
617
+ v = _safe_zlib_decompress(v)
618
+ except ValueError:
619
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
620
+ return s
621
+ else:
622
+ raise
623
+ except zlib.error:
624
+ return s
625
+ else:
626
+ return s
627
+ if k == b"XML:com.adobe.xmp":
628
+ self.im_info["xmp"] = v
629
+ try:
630
+ k = k.decode("latin-1", "strict")
631
+ lang = lang.decode("utf-8", "strict")
632
+ tk = tk.decode("utf-8", "strict")
633
+ v = v.decode("utf-8", "strict")
634
+ except UnicodeError:
635
+ return s
636
+
637
+ self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk)
638
+ self.check_text_memory(len(v))
639
+
640
+ return s
641
+
642
+ def chunk_eXIf(self, pos: int, length: int) -> bytes:
643
+ s = ImageFile._safe_read(self.fp, length)
644
+ self.im_info["exif"] = b"Exif\x00\x00" + s
645
+ return s
646
+
647
+ # APNG chunks
648
+ def chunk_acTL(self, pos: int, length: int) -> bytes:
649
+ s = ImageFile._safe_read(self.fp, length)
650
+ if length < 8:
651
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
652
+ return s
653
+ msg = "APNG contains truncated acTL chunk"
654
+ raise ValueError(msg)
655
+ if self.im_n_frames is not None:
656
+ self.im_n_frames = None
657
+ warnings.warn("Invalid APNG, will use default PNG image if possible")
658
+ return s
659
+ n_frames = i32(s)
660
+ if n_frames == 0 or n_frames > 0x80000000:
661
+ warnings.warn("Invalid APNG, will use default PNG image if possible")
662
+ return s
663
+ self.im_n_frames = n_frames
664
+ self.im_info["loop"] = i32(s, 4)
665
+ self.im_custom_mimetype = "image/apng"
666
+ return s
667
+
668
+ def chunk_fcTL(self, pos: int, length: int) -> bytes:
669
+ s = ImageFile._safe_read(self.fp, length)
670
+ if length < 26:
671
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
672
+ return s
673
+ msg = "APNG contains truncated fcTL chunk"
674
+ raise ValueError(msg)
675
+ seq = i32(s)
676
+ if (self._seq_num is None and seq != 0) or (
677
+ self._seq_num is not None and self._seq_num != seq - 1
678
+ ):
679
+ msg = "APNG contains frame sequence errors"
680
+ raise SyntaxError(msg)
681
+ self._seq_num = seq
682
+ width, height = i32(s, 4), i32(s, 8)
683
+ px, py = i32(s, 12), i32(s, 16)
684
+ im_w, im_h = self.im_size
685
+ if px + width > im_w or py + height > im_h:
686
+ msg = "APNG contains invalid frames"
687
+ raise SyntaxError(msg)
688
+ self.im_info["bbox"] = (px, py, px + width, py + height)
689
+ delay_num, delay_den = i16(s, 20), i16(s, 22)
690
+ if delay_den == 0:
691
+ delay_den = 100
692
+ self.im_info["duration"] = float(delay_num) / float(delay_den) * 1000
693
+ self.im_info["disposal"] = s[24]
694
+ self.im_info["blend"] = s[25]
695
+ return s
696
+
697
+ def chunk_fdAT(self, pos: int, length: int) -> bytes:
698
+ if length < 4:
699
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
700
+ s = ImageFile._safe_read(self.fp, length)
701
+ return s
702
+ msg = "APNG contains truncated fDAT chunk"
703
+ raise ValueError(msg)
704
+ s = ImageFile._safe_read(self.fp, 4)
705
+ seq = i32(s)
706
+ if self._seq_num != seq - 1:
707
+ msg = "APNG contains frame sequence errors"
708
+ raise SyntaxError(msg)
709
+ self._seq_num = seq
710
+ return self.chunk_IDAT(pos + 4, length - 4)
711
+
712
+
713
+ # --------------------------------------------------------------------
714
+ # PNG reader
715
+
716
+
717
+ def _accept(prefix: bytes) -> bool:
718
+ return prefix[:8] == _MAGIC
719
+
720
+
721
+ ##
722
+ # Image plugin for PNG images.
723
+
724
+
725
+ class PngImageFile(ImageFile.ImageFile):
726
+ format = "PNG"
727
+ format_description = "Portable network graphics"
728
+
729
+ def _open(self) -> None:
730
+ if not _accept(self.fp.read(8)):
731
+ msg = "not a PNG file"
732
+ raise SyntaxError(msg)
733
+ self._fp = self.fp
734
+ self.__frame = 0
735
+
736
+ #
737
+ # Parse headers up to the first IDAT or fDAT chunk
738
+
739
+ self.private_chunks: list[tuple[bytes, bytes] | tuple[bytes, bytes, bool]] = []
740
+ self.png: PngStream | None = PngStream(self.fp)
741
+
742
+ while True:
743
+ #
744
+ # get next chunk
745
+
746
+ cid, pos, length = self.png.read()
747
+
748
+ try:
749
+ s = self.png.call(cid, pos, length)
750
+ except EOFError:
751
+ break
752
+ except AttributeError:
753
+ logger.debug("%r %s %s (unknown)", cid, pos, length)
754
+ s = ImageFile._safe_read(self.fp, length)
755
+ if cid[1:2].islower():
756
+ self.private_chunks.append((cid, s))
757
+
758
+ self.png.crc(cid, s)
759
+
760
+ #
761
+ # Copy relevant attributes from the PngStream. An alternative
762
+ # would be to let the PngStream class modify these attributes
763
+ # directly, but that introduces circular references which are
764
+ # difficult to break if things go wrong in the decoder...
765
+ # (believe me, I've tried ;-)
766
+
767
+ self._mode = self.png.im_mode
768
+ self._size = self.png.im_size
769
+ self.info = self.png.im_info
770
+ self._text = None
771
+ self.tile = self.png.im_tile
772
+ self.custom_mimetype = self.png.im_custom_mimetype
773
+ self.n_frames = self.png.im_n_frames or 1
774
+ self.default_image = self.info.get("default_image", False)
775
+
776
+ if self.png.im_palette:
777
+ rawmode, data = self.png.im_palette
778
+ self.palette = ImagePalette.raw(rawmode, data)
779
+
780
+ if cid == b"fdAT":
781
+ self.__prepare_idat = length - 4
782
+ else:
783
+ self.__prepare_idat = length # used by load_prepare()
784
+
785
+ if self.png.im_n_frames is not None:
786
+ self._close_exclusive_fp_after_loading = False
787
+ self.png.save_rewind()
788
+ self.__rewind_idat = self.__prepare_idat
789
+ self.__rewind = self._fp.tell()
790
+ if self.default_image:
791
+ # IDAT chunk contains default image and not first animation frame
792
+ self.n_frames += 1
793
+ self._seek(0)
794
+ self.is_animated = self.n_frames > 1
795
+
796
+ @property
797
+ def text(self):
798
+ # experimental
799
+ if self._text is None:
800
+ # iTxt, tEXt and zTXt chunks may appear at the end of the file
801
+ # So load the file to ensure that they are read
802
+ if self.is_animated:
803
+ frame = self.__frame
804
+ # for APNG, seek to the final frame before loading
805
+ self.seek(self.n_frames - 1)
806
+ self.load()
807
+ if self.is_animated:
808
+ self.seek(frame)
809
+ return self._text
810
+
811
+ def verify(self) -> None:
812
+ """Verify PNG file"""
813
+
814
+ if self.fp is None:
815
+ msg = "verify must be called directly after open"
816
+ raise RuntimeError(msg)
817
+
818
+ # back up to beginning of IDAT block
819
+ self.fp.seek(self.tile[0][2] - 8)
820
+
821
+ assert self.png is not None
822
+ self.png.verify()
823
+ self.png.close()
824
+
825
+ if self._exclusive_fp:
826
+ self.fp.close()
827
+ self.fp = None
828
+
829
+ def seek(self, frame: int) -> None:
830
+ if not self._seek_check(frame):
831
+ return
832
+ if frame < self.__frame:
833
+ self._seek(0, True)
834
+
835
+ last_frame = self.__frame
836
+ for f in range(self.__frame + 1, frame + 1):
837
+ try:
838
+ self._seek(f)
839
+ except EOFError as e:
840
+ self.seek(last_frame)
841
+ msg = "no more images in APNG file"
842
+ raise EOFError(msg) from e
843
+
844
+ def _seek(self, frame: int, rewind: bool = False) -> None:
845
+ assert self.png is not None
846
+
847
+ self.dispose: _imaging.ImagingCore | None
848
+ if frame == 0:
849
+ if rewind:
850
+ self._fp.seek(self.__rewind)
851
+ self.png.rewind()
852
+ self.__prepare_idat = self.__rewind_idat
853
+ self.im = None
854
+ if self.pyaccess:
855
+ self.pyaccess = None
856
+ self.info = self.png.im_info
857
+ self.tile = self.png.im_tile
858
+ self.fp = self._fp
859
+ self._prev_im = None
860
+ self.dispose = None
861
+ self.default_image = self.info.get("default_image", False)
862
+ self.dispose_op = self.info.get("disposal")
863
+ self.blend_op = self.info.get("blend")
864
+ self.dispose_extent = self.info.get("bbox")
865
+ self.__frame = 0
866
+ else:
867
+ if frame != self.__frame + 1:
868
+ msg = f"cannot seek to frame {frame}"
869
+ raise ValueError(msg)
870
+
871
+ # ensure previous frame was loaded
872
+ self.load()
873
+
874
+ if self.dispose:
875
+ self.im.paste(self.dispose, self.dispose_extent)
876
+ self._prev_im = self.im.copy()
877
+
878
+ self.fp = self._fp
879
+
880
+ # advance to the next frame
881
+ if self.__prepare_idat:
882
+ ImageFile._safe_read(self.fp, self.__prepare_idat)
883
+ self.__prepare_idat = 0
884
+ frame_start = False
885
+ while True:
886
+ self.fp.read(4) # CRC
887
+
888
+ try:
889
+ cid, pos, length = self.png.read()
890
+ except (struct.error, SyntaxError):
891
+ break
892
+
893
+ if cid == b"IEND":
894
+ msg = "No more images in APNG file"
895
+ raise EOFError(msg)
896
+ if cid == b"fcTL":
897
+ if frame_start:
898
+ # there must be at least one fdAT chunk between fcTL chunks
899
+ msg = "APNG missing frame data"
900
+ raise SyntaxError(msg)
901
+ frame_start = True
902
+
903
+ try:
904
+ self.png.call(cid, pos, length)
905
+ except UnicodeDecodeError:
906
+ break
907
+ except EOFError:
908
+ if cid == b"fdAT":
909
+ length -= 4
910
+ if frame_start:
911
+ self.__prepare_idat = length
912
+ break
913
+ ImageFile._safe_read(self.fp, length)
914
+ except AttributeError:
915
+ logger.debug("%r %s %s (unknown)", cid, pos, length)
916
+ ImageFile._safe_read(self.fp, length)
917
+
918
+ self.__frame = frame
919
+ self.tile = self.png.im_tile
920
+ self.dispose_op = self.info.get("disposal")
921
+ self.blend_op = self.info.get("blend")
922
+ self.dispose_extent = self.info.get("bbox")
923
+
924
+ if not self.tile:
925
+ msg = "image not found in APNG frame"
926
+ raise EOFError(msg)
927
+
928
+ # setup frame disposal (actual disposal done when needed in the next _seek())
929
+ if self._prev_im is None and self.dispose_op == Disposal.OP_PREVIOUS:
930
+ self.dispose_op = Disposal.OP_BACKGROUND
931
+
932
+ self.dispose = None
933
+ if self.dispose_op == Disposal.OP_PREVIOUS:
934
+ if self._prev_im:
935
+ self.dispose = self._prev_im.copy()
936
+ self.dispose = self._crop(self.dispose, self.dispose_extent)
937
+ elif self.dispose_op == Disposal.OP_BACKGROUND:
938
+ self.dispose = Image.core.fill(self.mode, self.size)
939
+ self.dispose = self._crop(self.dispose, self.dispose_extent)
940
+
941
+ def tell(self) -> int:
942
+ return self.__frame
943
+
944
+ def load_prepare(self) -> None:
945
+ """internal: prepare to read PNG file"""
946
+
947
+ if self.info.get("interlace"):
948
+ self.decoderconfig = self.decoderconfig + (1,)
949
+
950
+ self.__idat = self.__prepare_idat # used by load_read()
951
+ ImageFile.ImageFile.load_prepare(self)
952
+
953
+ def load_read(self, read_bytes: int) -> bytes:
954
+ """internal: read more image data"""
955
+
956
+ assert self.png is not None
957
+ while self.__idat == 0:
958
+ # end of chunk, skip forward to next one
959
+
960
+ self.fp.read(4) # CRC
961
+
962
+ cid, pos, length = self.png.read()
963
+
964
+ if cid not in [b"IDAT", b"DDAT", b"fdAT"]:
965
+ self.png.push(cid, pos, length)
966
+ return b""
967
+
968
+ if cid == b"fdAT":
969
+ try:
970
+ self.png.call(cid, pos, length)
971
+ except EOFError:
972
+ pass
973
+ self.__idat = length - 4 # sequence_num has already been read
974
+ else:
975
+ self.__idat = length # empty chunks are allowed
976
+
977
+ # read more data from this chunk
978
+ if read_bytes <= 0:
979
+ read_bytes = self.__idat
980
+ else:
981
+ read_bytes = min(read_bytes, self.__idat)
982
+
983
+ self.__idat = self.__idat - read_bytes
984
+
985
+ return self.fp.read(read_bytes)
986
+
987
+ def load_end(self) -> None:
988
+ """internal: finished reading image data"""
989
+ assert self.png is not None
990
+ if self.__idat != 0:
991
+ self.fp.read(self.__idat)
992
+ while True:
993
+ self.fp.read(4) # CRC
994
+
995
+ try:
996
+ cid, pos, length = self.png.read()
997
+ except (struct.error, SyntaxError):
998
+ break
999
+
1000
+ if cid == b"IEND":
1001
+ break
1002
+ elif cid == b"fcTL" and self.is_animated:
1003
+ # start of the next frame, stop reading
1004
+ self.__prepare_idat = 0
1005
+ self.png.push(cid, pos, length)
1006
+ break
1007
+
1008
+ try:
1009
+ self.png.call(cid, pos, length)
1010
+ except UnicodeDecodeError:
1011
+ break
1012
+ except EOFError:
1013
+ if cid == b"fdAT":
1014
+ length -= 4
1015
+ try:
1016
+ ImageFile._safe_read(self.fp, length)
1017
+ except OSError as e:
1018
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
1019
+ break
1020
+ else:
1021
+ raise e
1022
+ except AttributeError:
1023
+ logger.debug("%r %s %s (unknown)", cid, pos, length)
1024
+ s = ImageFile._safe_read(self.fp, length)
1025
+ if cid[1:2].islower():
1026
+ self.private_chunks.append((cid, s, True))
1027
+ self._text = self.png.im_text
1028
+ if not self.is_animated:
1029
+ self.png.close()
1030
+ self.png = None
1031
+ else:
1032
+ if self._prev_im and self.blend_op == Blend.OP_OVER:
1033
+ updated = self._crop(self.im, self.dispose_extent)
1034
+ if self.im.mode == "RGB" and "transparency" in self.info:
1035
+ mask = updated.convert_transparent(
1036
+ "RGBA", self.info["transparency"]
1037
+ )
1038
+ else:
1039
+ mask = updated.convert("RGBA")
1040
+ self._prev_im.paste(updated, self.dispose_extent, mask)
1041
+ self.im = self._prev_im
1042
+ if self.pyaccess:
1043
+ self.pyaccess = None
1044
+
1045
+ def _getexif(self) -> dict[str, Any] | None:
1046
+ if "exif" not in self.info:
1047
+ self.load()
1048
+ if "exif" not in self.info and "Raw profile type exif" not in self.info:
1049
+ return None
1050
+ return self.getexif()._get_merged_dict()
1051
+
1052
+ def getexif(self) -> Image.Exif:
1053
+ if "exif" not in self.info:
1054
+ self.load()
1055
+
1056
+ return super().getexif()
1057
+
1058
+
1059
+ # --------------------------------------------------------------------
1060
+ # PNG writer
1061
+
1062
+ _OUTMODES = {
1063
+ # supported PIL modes, and corresponding rawmode, bit depth and color type
1064
+ "1": ("1", b"\x01", b"\x00"),
1065
+ "L;1": ("L;1", b"\x01", b"\x00"),
1066
+ "L;2": ("L;2", b"\x02", b"\x00"),
1067
+ "L;4": ("L;4", b"\x04", b"\x00"),
1068
+ "L": ("L", b"\x08", b"\x00"),
1069
+ "LA": ("LA", b"\x08", b"\x04"),
1070
+ "I": ("I;16B", b"\x10", b"\x00"),
1071
+ "I;16": ("I;16B", b"\x10", b"\x00"),
1072
+ "I;16B": ("I;16B", b"\x10", b"\x00"),
1073
+ "P;1": ("P;1", b"\x01", b"\x03"),
1074
+ "P;2": ("P;2", b"\x02", b"\x03"),
1075
+ "P;4": ("P;4", b"\x04", b"\x03"),
1076
+ "P": ("P", b"\x08", b"\x03"),
1077
+ "RGB": ("RGB", b"\x08", b"\x02"),
1078
+ "RGBA": ("RGBA", b"\x08", b"\x06"),
1079
+ }
1080
+
1081
+
1082
+ def putchunk(fp, cid, *data):
1083
+ """Write a PNG chunk (including CRC field)"""
1084
+
1085
+ data = b"".join(data)
1086
+
1087
+ fp.write(o32(len(data)) + cid)
1088
+ fp.write(data)
1089
+ crc = _crc32(data, _crc32(cid))
1090
+ fp.write(o32(crc))
1091
+
1092
+
1093
+ class _idat:
1094
+ # wrap output from the encoder in IDAT chunks
1095
+
1096
+ def __init__(self, fp, chunk):
1097
+ self.fp = fp
1098
+ self.chunk = chunk
1099
+
1100
+ def write(self, data: bytes) -> None:
1101
+ self.chunk(self.fp, b"IDAT", data)
1102
+
1103
+
1104
+ class _fdat:
1105
+ # wrap encoder output in fdAT chunks
1106
+
1107
+ def __init__(self, fp, chunk, seq_num):
1108
+ self.fp = fp
1109
+ self.chunk = chunk
1110
+ self.seq_num = seq_num
1111
+
1112
+ def write(self, data: bytes) -> None:
1113
+ self.chunk(self.fp, b"fdAT", o32(self.seq_num), data)
1114
+ self.seq_num += 1
1115
+
1116
+
1117
+ def _write_multiple_frames(im, fp, chunk, mode, rawmode, default_image, append_images):
1118
+ duration = im.encoderinfo.get("duration")
1119
+ loop = im.encoderinfo.get("loop", im.info.get("loop", 0))
1120
+ disposal = im.encoderinfo.get("disposal", im.info.get("disposal", Disposal.OP_NONE))
1121
+ blend = im.encoderinfo.get("blend", im.info.get("blend", Blend.OP_SOURCE))
1122
+
1123
+ if default_image:
1124
+ chain = itertools.chain(append_images)
1125
+ else:
1126
+ chain = itertools.chain([im], append_images)
1127
+
1128
+ im_frames = []
1129
+ frame_count = 0
1130
+ for im_seq in chain:
1131
+ for im_frame in ImageSequence.Iterator(im_seq):
1132
+ if im_frame.mode == mode:
1133
+ im_frame = im_frame.copy()
1134
+ else:
1135
+ im_frame = im_frame.convert(mode)
1136
+ encoderinfo = im.encoderinfo.copy()
1137
+ if isinstance(duration, (list, tuple)):
1138
+ encoderinfo["duration"] = duration[frame_count]
1139
+ elif duration is None and "duration" in im_frame.info:
1140
+ encoderinfo["duration"] = im_frame.info["duration"]
1141
+ if isinstance(disposal, (list, tuple)):
1142
+ encoderinfo["disposal"] = disposal[frame_count]
1143
+ if isinstance(blend, (list, tuple)):
1144
+ encoderinfo["blend"] = blend[frame_count]
1145
+ frame_count += 1
1146
+
1147
+ if im_frames:
1148
+ previous = im_frames[-1]
1149
+ prev_disposal = previous["encoderinfo"].get("disposal")
1150
+ prev_blend = previous["encoderinfo"].get("blend")
1151
+ if prev_disposal == Disposal.OP_PREVIOUS and len(im_frames) < 2:
1152
+ prev_disposal = Disposal.OP_BACKGROUND
1153
+
1154
+ if prev_disposal == Disposal.OP_BACKGROUND:
1155
+ base_im = previous["im"].copy()
1156
+ dispose = Image.core.fill("RGBA", im.size, (0, 0, 0, 0))
1157
+ bbox = previous["bbox"]
1158
+ if bbox:
1159
+ dispose = dispose.crop(bbox)
1160
+ else:
1161
+ bbox = (0, 0) + im.size
1162
+ base_im.paste(dispose, bbox)
1163
+ elif prev_disposal == Disposal.OP_PREVIOUS:
1164
+ base_im = im_frames[-2]["im"]
1165
+ else:
1166
+ base_im = previous["im"]
1167
+ delta = ImageChops.subtract_modulo(
1168
+ im_frame.convert("RGBA"), base_im.convert("RGBA")
1169
+ )
1170
+ bbox = delta.getbbox(alpha_only=False)
1171
+ if (
1172
+ not bbox
1173
+ and prev_disposal == encoderinfo.get("disposal")
1174
+ and prev_blend == encoderinfo.get("blend")
1175
+ and "duration" in encoderinfo
1176
+ ):
1177
+ previous["encoderinfo"]["duration"] += encoderinfo["duration"]
1178
+ continue
1179
+ else:
1180
+ bbox = None
1181
+ im_frames.append({"im": im_frame, "bbox": bbox, "encoderinfo": encoderinfo})
1182
+
1183
+ if len(im_frames) == 1 and not default_image:
1184
+ return im_frames[0]["im"]
1185
+
1186
+ # animation control
1187
+ chunk(
1188
+ fp,
1189
+ b"acTL",
1190
+ o32(len(im_frames)), # 0: num_frames
1191
+ o32(loop), # 4: num_plays
1192
+ )
1193
+
1194
+ # default image IDAT (if it exists)
1195
+ if default_image:
1196
+ if im.mode != mode:
1197
+ im = im.convert(mode)
1198
+ ImageFile._save(im, _idat(fp, chunk), [("zip", (0, 0) + im.size, 0, rawmode)])
1199
+
1200
+ seq_num = 0
1201
+ for frame, frame_data in enumerate(im_frames):
1202
+ im_frame = frame_data["im"]
1203
+ if not frame_data["bbox"]:
1204
+ bbox = (0, 0) + im_frame.size
1205
+ else:
1206
+ bbox = frame_data["bbox"]
1207
+ im_frame = im_frame.crop(bbox)
1208
+ size = im_frame.size
1209
+ encoderinfo = frame_data["encoderinfo"]
1210
+ frame_duration = int(round(encoderinfo.get("duration", 0)))
1211
+ frame_disposal = encoderinfo.get("disposal", disposal)
1212
+ frame_blend = encoderinfo.get("blend", blend)
1213
+ # frame control
1214
+ chunk(
1215
+ fp,
1216
+ b"fcTL",
1217
+ o32(seq_num), # sequence_number
1218
+ o32(size[0]), # width
1219
+ o32(size[1]), # height
1220
+ o32(bbox[0]), # x_offset
1221
+ o32(bbox[1]), # y_offset
1222
+ o16(frame_duration), # delay_numerator
1223
+ o16(1000), # delay_denominator
1224
+ o8(frame_disposal), # dispose_op
1225
+ o8(frame_blend), # blend_op
1226
+ )
1227
+ seq_num += 1
1228
+ # frame data
1229
+ if frame == 0 and not default_image:
1230
+ # first frame must be in IDAT chunks for backwards compatibility
1231
+ ImageFile._save(
1232
+ im_frame,
1233
+ _idat(fp, chunk),
1234
+ [("zip", (0, 0) + im_frame.size, 0, rawmode)],
1235
+ )
1236
+ else:
1237
+ fdat_chunks = _fdat(fp, chunk, seq_num)
1238
+ ImageFile._save(
1239
+ im_frame,
1240
+ fdat_chunks,
1241
+ [("zip", (0, 0) + im_frame.size, 0, rawmode)],
1242
+ )
1243
+ seq_num = fdat_chunks.seq_num
1244
+
1245
+
1246
+ def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
1247
+ _save(im, fp, filename, save_all=True)
1248
+
1249
+
1250
+ def _save(im, fp, filename, chunk=putchunk, save_all=False):
1251
+ # save an image to disk (called by the save method)
1252
+
1253
+ if save_all:
1254
+ default_image = im.encoderinfo.get(
1255
+ "default_image", im.info.get("default_image")
1256
+ )
1257
+ modes = set()
1258
+ sizes = set()
1259
+ append_images = im.encoderinfo.get("append_images", [])
1260
+ for im_seq in itertools.chain([im], append_images):
1261
+ for im_frame in ImageSequence.Iterator(im_seq):
1262
+ modes.add(im_frame.mode)
1263
+ sizes.add(im_frame.size)
1264
+ for mode in ("RGBA", "RGB", "P"):
1265
+ if mode in modes:
1266
+ break
1267
+ else:
1268
+ mode = modes.pop()
1269
+ size = tuple(max(frame_size[i] for frame_size in sizes) for i in range(2))
1270
+ else:
1271
+ size = im.size
1272
+ mode = im.mode
1273
+
1274
+ outmode = mode
1275
+ if mode == "P":
1276
+ #
1277
+ # attempt to minimize storage requirements for palette images
1278
+ if "bits" in im.encoderinfo:
1279
+ # number of bits specified by user
1280
+ colors = min(1 << im.encoderinfo["bits"], 256)
1281
+ else:
1282
+ # check palette contents
1283
+ if im.palette:
1284
+ colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 1)
1285
+ else:
1286
+ colors = 256
1287
+
1288
+ if colors <= 16:
1289
+ if colors <= 2:
1290
+ bits = 1
1291
+ elif colors <= 4:
1292
+ bits = 2
1293
+ else:
1294
+ bits = 4
1295
+ outmode += f";{bits}"
1296
+
1297
+ # encoder options
1298
+ im.encoderconfig = (
1299
+ im.encoderinfo.get("optimize", False),
1300
+ im.encoderinfo.get("compress_level", -1),
1301
+ im.encoderinfo.get("compress_type", -1),
1302
+ im.encoderinfo.get("dictionary", b""),
1303
+ )
1304
+
1305
+ # get the corresponding PNG mode
1306
+ try:
1307
+ rawmode, bit_depth, color_type = _OUTMODES[outmode]
1308
+ except KeyError as e:
1309
+ msg = f"cannot write mode {mode} as PNG"
1310
+ raise OSError(msg) from e
1311
+
1312
+ #
1313
+ # write minimal PNG file
1314
+
1315
+ fp.write(_MAGIC)
1316
+
1317
+ chunk(
1318
+ fp,
1319
+ b"IHDR",
1320
+ o32(size[0]), # 0: size
1321
+ o32(size[1]),
1322
+ bit_depth,
1323
+ color_type,
1324
+ b"\0", # 10: compression
1325
+ b"\0", # 11: filter category
1326
+ b"\0", # 12: interlace flag
1327
+ )
1328
+
1329
+ chunks = [b"cHRM", b"gAMA", b"sBIT", b"sRGB", b"tIME"]
1330
+
1331
+ icc = im.encoderinfo.get("icc_profile", im.info.get("icc_profile"))
1332
+ if icc:
1333
+ # ICC profile
1334
+ # according to PNG spec, the iCCP chunk contains:
1335
+ # Profile name 1-79 bytes (character string)
1336
+ # Null separator 1 byte (null character)
1337
+ # Compression method 1 byte (0)
1338
+ # Compressed profile n bytes (zlib with deflate compression)
1339
+ name = b"ICC Profile"
1340
+ data = name + b"\0\0" + zlib.compress(icc)
1341
+ chunk(fp, b"iCCP", data)
1342
+
1343
+ # You must either have sRGB or iCCP.
1344
+ # Disallow sRGB chunks when an iCCP-chunk has been emitted.
1345
+ chunks.remove(b"sRGB")
1346
+
1347
+ info = im.encoderinfo.get("pnginfo")
1348
+ if info:
1349
+ chunks_multiple_allowed = [b"sPLT", b"iTXt", b"tEXt", b"zTXt"]
1350
+ for info_chunk in info.chunks:
1351
+ cid, data = info_chunk[:2]
1352
+ if cid in chunks:
1353
+ chunks.remove(cid)
1354
+ chunk(fp, cid, data)
1355
+ elif cid in chunks_multiple_allowed:
1356
+ chunk(fp, cid, data)
1357
+ elif cid[1:2].islower():
1358
+ # Private chunk
1359
+ after_idat = len(info_chunk) == 3 and info_chunk[2]
1360
+ if not after_idat:
1361
+ chunk(fp, cid, data)
1362
+
1363
+ if im.mode == "P":
1364
+ palette_byte_number = colors * 3
1365
+ palette_bytes = im.im.getpalette("RGB")[:palette_byte_number]
1366
+ while len(palette_bytes) < palette_byte_number:
1367
+ palette_bytes += b"\0"
1368
+ chunk(fp, b"PLTE", palette_bytes)
1369
+
1370
+ transparency = im.encoderinfo.get("transparency", im.info.get("transparency", None))
1371
+
1372
+ if transparency or transparency == 0:
1373
+ if im.mode == "P":
1374
+ # limit to actual palette size
1375
+ alpha_bytes = colors
1376
+ if isinstance(transparency, bytes):
1377
+ chunk(fp, b"tRNS", transparency[:alpha_bytes])
1378
+ else:
1379
+ transparency = max(0, min(255, transparency))
1380
+ alpha = b"\xFF" * transparency + b"\0"
1381
+ chunk(fp, b"tRNS", alpha[:alpha_bytes])
1382
+ elif im.mode in ("1", "L", "I", "I;16"):
1383
+ transparency = max(0, min(65535, transparency))
1384
+ chunk(fp, b"tRNS", o16(transparency))
1385
+ elif im.mode == "RGB":
1386
+ red, green, blue = transparency
1387
+ chunk(fp, b"tRNS", o16(red) + o16(green) + o16(blue))
1388
+ else:
1389
+ if "transparency" in im.encoderinfo:
1390
+ # don't bother with transparency if it's an RGBA
1391
+ # and it's in the info dict. It's probably just stale.
1392
+ msg = "cannot use transparency for this mode"
1393
+ raise OSError(msg)
1394
+ else:
1395
+ if im.mode == "P" and im.im.getpalettemode() == "RGBA":
1396
+ alpha = im.im.getpalette("RGBA", "A")
1397
+ alpha_bytes = colors
1398
+ chunk(fp, b"tRNS", alpha[:alpha_bytes])
1399
+
1400
+ dpi = im.encoderinfo.get("dpi")
1401
+ if dpi:
1402
+ chunk(
1403
+ fp,
1404
+ b"pHYs",
1405
+ o32(int(dpi[0] / 0.0254 + 0.5)),
1406
+ o32(int(dpi[1] / 0.0254 + 0.5)),
1407
+ b"\x01",
1408
+ )
1409
+
1410
+ if info:
1411
+ chunks = [b"bKGD", b"hIST"]
1412
+ for info_chunk in info.chunks:
1413
+ cid, data = info_chunk[:2]
1414
+ if cid in chunks:
1415
+ chunks.remove(cid)
1416
+ chunk(fp, cid, data)
1417
+
1418
+ exif = im.encoderinfo.get("exif")
1419
+ if exif:
1420
+ if isinstance(exif, Image.Exif):
1421
+ exif = exif.tobytes(8)
1422
+ if exif.startswith(b"Exif\x00\x00"):
1423
+ exif = exif[6:]
1424
+ chunk(fp, b"eXIf", exif)
1425
+
1426
+ if save_all:
1427
+ im = _write_multiple_frames(
1428
+ im, fp, chunk, mode, rawmode, default_image, append_images
1429
+ )
1430
+ if im:
1431
+ ImageFile._save(im, _idat(fp, chunk), [("zip", (0, 0) + im.size, 0, rawmode)])
1432
+
1433
+ if info:
1434
+ for info_chunk in info.chunks:
1435
+ cid, data = info_chunk[:2]
1436
+ if cid[1:2].islower():
1437
+ # Private chunk
1438
+ after_idat = len(info_chunk) == 3 and info_chunk[2]
1439
+ if after_idat:
1440
+ chunk(fp, cid, data)
1441
+
1442
+ chunk(fp, b"IEND", b"")
1443
+
1444
+ if hasattr(fp, "flush"):
1445
+ fp.flush()
1446
+
1447
+
1448
+ # --------------------------------------------------------------------
1449
+ # PNG chunk converter
1450
+
1451
+
1452
+ def getchunks(im, **params):
1453
+ """Return a list of PNG chunks representing this image."""
1454
+
1455
+ class collector:
1456
+ data = []
1457
+
1458
+ def write(self, data: bytes) -> None:
1459
+ pass
1460
+
1461
+ def append(self, chunk: bytes) -> None:
1462
+ self.data.append(chunk)
1463
+
1464
+ def append(fp, cid, *data):
1465
+ data = b"".join(data)
1466
+ crc = o32(_crc32(data, _crc32(cid)))
1467
+ fp.append((cid, data, crc))
1468
+
1469
+ fp = collector()
1470
+
1471
+ try:
1472
+ im.encoderinfo = params
1473
+ _save(im, fp, None, append)
1474
+ finally:
1475
+ del im.encoderinfo
1476
+
1477
+ return fp.data
1478
+
1479
+
1480
+ # --------------------------------------------------------------------
1481
+ # Registry
1482
+
1483
+ Image.register_open(PngImageFile.format, PngImageFile, _accept)
1484
+ Image.register_save(PngImageFile.format, _save)
1485
+ Image.register_save_all(PngImageFile.format, _save_all)
1486
+
1487
+ Image.register_extensions(PngImageFile.format, [".png", ".apng"])
1488
+
1489
+ Image.register_mime(PngImageFile.format, "image/png")
evalkit_tf437/lib/python3.10/site-packages/PIL/PyAccess.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # Pillow fork
4
+ #
5
+ # Python implementation of the PixelAccess Object
6
+ #
7
+ # Copyright (c) 1997-2009 by Secret Labs AB. All rights reserved.
8
+ # Copyright (c) 1995-2009 by Fredrik Lundh.
9
+ # Copyright (c) 2013 Eric Soroos
10
+ #
11
+ # See the README file for information on usage and redistribution
12
+ #
13
+
14
+ # Notes:
15
+ #
16
+ # * Implements the pixel access object following Access.c
17
+ # * Taking only the tuple form, which is used from python.
18
+ # * Fill.c uses the integer form, but it's still going to use the old
19
+ # Access.c implementation.
20
+ #
21
+ from __future__ import annotations
22
+
23
+ import logging
24
+ import sys
25
+ from typing import TYPE_CHECKING
26
+
27
+ from ._deprecate import deprecate
28
+
29
+ FFI: type
30
+ try:
31
+ from cffi import FFI
32
+
33
+ defs = """
34
+ struct Pixel_RGBA {
35
+ unsigned char r,g,b,a;
36
+ };
37
+ struct Pixel_I16 {
38
+ unsigned char l,r;
39
+ };
40
+ """
41
+ ffi = FFI()
42
+ ffi.cdef(defs)
43
+ except ImportError as ex:
44
+ # Allow error import for doc purposes, but error out when accessing
45
+ # anything in core.
46
+ from ._util import DeferredError
47
+
48
+ FFI = ffi = DeferredError.new(ex)
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+ if TYPE_CHECKING:
53
+ from . import Image
54
+
55
+
56
+ class PyAccess:
57
+ def __init__(self, img: Image.Image, readonly: bool = False) -> None:
58
+ deprecate("PyAccess", 11)
59
+ vals = dict(img.im.unsafe_ptrs)
60
+ self.readonly = readonly
61
+ self.image8 = ffi.cast("unsigned char **", vals["image8"])
62
+ self.image32 = ffi.cast("int **", vals["image32"])
63
+ self.image = ffi.cast("unsigned char **", vals["image"])
64
+ self.xsize, self.ysize = img.im.size
65
+ self._img = img
66
+
67
+ # Keep pointer to im object to prevent dereferencing.
68
+ self._im = img.im
69
+ if self._im.mode in ("P", "PA"):
70
+ self._palette = img.palette
71
+
72
+ # Debugging is polluting test traces, only useful here
73
+ # when hacking on PyAccess
74
+ # logger.debug("%s", vals)
75
+ self._post_init()
76
+
77
+ def _post_init(self) -> None:
78
+ pass
79
+
80
+ def __setitem__(
81
+ self,
82
+ xy: tuple[int, int] | list[int],
83
+ color: float | tuple[int, ...] | list[int],
84
+ ) -> None:
85
+ """
86
+ Modifies the pixel at x,y. The color is given as a single
87
+ numerical value for single band images, and a tuple for
88
+ multi-band images. In addition to this, RGB and RGBA tuples
89
+ are accepted for P and PA images.
90
+
91
+ :param xy: The pixel coordinate, given as (x, y). See
92
+ :ref:`coordinate-system`.
93
+ :param color: The pixel value.
94
+ """
95
+ if self.readonly:
96
+ msg = "Attempt to putpixel a read only image"
97
+ raise ValueError(msg)
98
+ (x, y) = xy
99
+ if x < 0:
100
+ x = self.xsize + x
101
+ if y < 0:
102
+ y = self.ysize + y
103
+ (x, y) = self.check_xy((x, y))
104
+
105
+ if (
106
+ self._im.mode in ("P", "PA")
107
+ and isinstance(color, (list, tuple))
108
+ and len(color) in [3, 4]
109
+ ):
110
+ # RGB or RGBA value for a P or PA image
111
+ if self._im.mode == "PA":
112
+ alpha = color[3] if len(color) == 4 else 255
113
+ color = color[:3]
114
+ palette_index = self._palette.getcolor(color, self._img)
115
+ color = (palette_index, alpha) if self._im.mode == "PA" else palette_index
116
+
117
+ return self.set_pixel(x, y, color)
118
+
119
+ def __getitem__(self, xy: tuple[int, int] | list[int]) -> float | tuple[int, ...]:
120
+ """
121
+ Returns the pixel at x,y. The pixel is returned as a single
122
+ value for single band images or a tuple for multiple band
123
+ images
124
+
125
+ :param xy: The pixel coordinate, given as (x, y). See
126
+ :ref:`coordinate-system`.
127
+ :returns: a pixel value for single band images, a tuple of
128
+ pixel values for multiband images.
129
+ """
130
+ (x, y) = xy
131
+ if x < 0:
132
+ x = self.xsize + x
133
+ if y < 0:
134
+ y = self.ysize + y
135
+ (x, y) = self.check_xy((x, y))
136
+ return self.get_pixel(x, y)
137
+
138
+ putpixel = __setitem__
139
+ getpixel = __getitem__
140
+
141
+ def check_xy(self, xy: tuple[int, int]) -> tuple[int, int]:
142
+ (x, y) = xy
143
+ if not (0 <= x < self.xsize and 0 <= y < self.ysize):
144
+ msg = "pixel location out of range"
145
+ raise ValueError(msg)
146
+ return xy
147
+
148
+ def get_pixel(self, x: int, y: int) -> float | tuple[int, ...]:
149
+ raise NotImplementedError()
150
+
151
+ def set_pixel(
152
+ self, x: int, y: int, color: float | tuple[int, ...] | list[int]
153
+ ) -> None:
154
+ raise NotImplementedError()
155
+
156
+
157
+ class _PyAccess32_2(PyAccess):
158
+ """PA, LA, stored in first and last bytes of a 32 bit word"""
159
+
160
+ def _post_init(self, *args, **kwargs):
161
+ self.pixels = ffi.cast("struct Pixel_RGBA **", self.image32)
162
+
163
+ def get_pixel(self, x: int, y: int) -> tuple[int, int]:
164
+ pixel = self.pixels[y][x]
165
+ return pixel.r, pixel.a
166
+
167
+ def set_pixel(self, x, y, color):
168
+ pixel = self.pixels[y][x]
169
+ # tuple
170
+ pixel.r = min(color[0], 255)
171
+ pixel.a = min(color[1], 255)
172
+
173
+
174
+ class _PyAccess32_3(PyAccess):
175
+ """RGB and friends, stored in the first three bytes of a 32 bit word"""
176
+
177
+ def _post_init(self, *args, **kwargs):
178
+ self.pixels = ffi.cast("struct Pixel_RGBA **", self.image32)
179
+
180
+ def get_pixel(self, x: int, y: int) -> tuple[int, int, int]:
181
+ pixel = self.pixels[y][x]
182
+ return pixel.r, pixel.g, pixel.b
183
+
184
+ def set_pixel(self, x, y, color):
185
+ pixel = self.pixels[y][x]
186
+ # tuple
187
+ pixel.r = min(color[0], 255)
188
+ pixel.g = min(color[1], 255)
189
+ pixel.b = min(color[2], 255)
190
+ pixel.a = 255
191
+
192
+
193
+ class _PyAccess32_4(PyAccess):
194
+ """RGBA etc, all 4 bytes of a 32 bit word"""
195
+
196
+ def _post_init(self, *args, **kwargs):
197
+ self.pixels = ffi.cast("struct Pixel_RGBA **", self.image32)
198
+
199
+ def get_pixel(self, x: int, y: int) -> tuple[int, int, int, int]:
200
+ pixel = self.pixels[y][x]
201
+ return pixel.r, pixel.g, pixel.b, pixel.a
202
+
203
+ def set_pixel(self, x, y, color):
204
+ pixel = self.pixels[y][x]
205
+ # tuple
206
+ pixel.r = min(color[0], 255)
207
+ pixel.g = min(color[1], 255)
208
+ pixel.b = min(color[2], 255)
209
+ pixel.a = min(color[3], 255)
210
+
211
+
212
+ class _PyAccess8(PyAccess):
213
+ """1, L, P, 8 bit images stored as uint8"""
214
+
215
+ def _post_init(self, *args, **kwargs):
216
+ self.pixels = self.image8
217
+
218
+ def get_pixel(self, x: int, y: int) -> int:
219
+ return self.pixels[y][x]
220
+
221
+ def set_pixel(self, x, y, color):
222
+ try:
223
+ # integer
224
+ self.pixels[y][x] = min(color, 255)
225
+ except TypeError:
226
+ # tuple
227
+ self.pixels[y][x] = min(color[0], 255)
228
+
229
+
230
+ class _PyAccessI16_N(PyAccess):
231
+ """I;16 access, native bitendian without conversion"""
232
+
233
+ def _post_init(self, *args, **kwargs):
234
+ self.pixels = ffi.cast("unsigned short **", self.image)
235
+
236
+ def get_pixel(self, x: int, y: int) -> int:
237
+ return self.pixels[y][x]
238
+
239
+ def set_pixel(self, x, y, color):
240
+ try:
241
+ # integer
242
+ self.pixels[y][x] = min(color, 65535)
243
+ except TypeError:
244
+ # tuple
245
+ self.pixels[y][x] = min(color[0], 65535)
246
+
247
+
248
+ class _PyAccessI16_L(PyAccess):
249
+ """I;16L access, with conversion"""
250
+
251
+ def _post_init(self, *args, **kwargs):
252
+ self.pixels = ffi.cast("struct Pixel_I16 **", self.image)
253
+
254
+ def get_pixel(self, x: int, y: int) -> int:
255
+ pixel = self.pixels[y][x]
256
+ return pixel.l + pixel.r * 256
257
+
258
+ def set_pixel(self, x, y, color):
259
+ pixel = self.pixels[y][x]
260
+ try:
261
+ color = min(color, 65535)
262
+ except TypeError:
263
+ color = min(color[0], 65535)
264
+
265
+ pixel.l = color & 0xFF
266
+ pixel.r = color >> 8
267
+
268
+
269
+ class _PyAccessI16_B(PyAccess):
270
+ """I;16B access, with conversion"""
271
+
272
+ def _post_init(self, *args, **kwargs):
273
+ self.pixels = ffi.cast("struct Pixel_I16 **", self.image)
274
+
275
+ def get_pixel(self, x: int, y: int) -> int:
276
+ pixel = self.pixels[y][x]
277
+ return pixel.l * 256 + pixel.r
278
+
279
+ def set_pixel(self, x, y, color):
280
+ pixel = self.pixels[y][x]
281
+ try:
282
+ color = min(color, 65535)
283
+ except Exception:
284
+ color = min(color[0], 65535)
285
+
286
+ pixel.l = color >> 8
287
+ pixel.r = color & 0xFF
288
+
289
+
290
+ class _PyAccessI32_N(PyAccess):
291
+ """Signed Int32 access, native endian"""
292
+
293
+ def _post_init(self, *args, **kwargs):
294
+ self.pixels = self.image32
295
+
296
+ def get_pixel(self, x: int, y: int) -> int:
297
+ return self.pixels[y][x]
298
+
299
+ def set_pixel(self, x, y, color):
300
+ self.pixels[y][x] = color
301
+
302
+
303
+ class _PyAccessI32_Swap(PyAccess):
304
+ """I;32L/B access, with byteswapping conversion"""
305
+
306
+ def _post_init(self, *args, **kwargs):
307
+ self.pixels = self.image32
308
+
309
+ def reverse(self, i):
310
+ orig = ffi.new("int *", i)
311
+ chars = ffi.cast("unsigned char *", orig)
312
+ chars[0], chars[1], chars[2], chars[3] = chars[3], chars[2], chars[1], chars[0]
313
+ return ffi.cast("int *", chars)[0]
314
+
315
+ def get_pixel(self, x: int, y: int) -> int:
316
+ return self.reverse(self.pixels[y][x])
317
+
318
+ def set_pixel(self, x, y, color):
319
+ self.pixels[y][x] = self.reverse(color)
320
+
321
+
322
+ class _PyAccessF(PyAccess):
323
+ """32 bit float access"""
324
+
325
+ def _post_init(self, *args, **kwargs):
326
+ self.pixels = ffi.cast("float **", self.image32)
327
+
328
+ def get_pixel(self, x: int, y: int) -> float:
329
+ return self.pixels[y][x]
330
+
331
+ def set_pixel(self, x, y, color):
332
+ try:
333
+ # not a tuple
334
+ self.pixels[y][x] = color
335
+ except TypeError:
336
+ # tuple
337
+ self.pixels[y][x] = color[0]
338
+
339
+
340
+ mode_map = {
341
+ "1": _PyAccess8,
342
+ "L": _PyAccess8,
343
+ "P": _PyAccess8,
344
+ "I;16N": _PyAccessI16_N,
345
+ "LA": _PyAccess32_2,
346
+ "La": _PyAccess32_2,
347
+ "PA": _PyAccess32_2,
348
+ "RGB": _PyAccess32_3,
349
+ "LAB": _PyAccess32_3,
350
+ "HSV": _PyAccess32_3,
351
+ "YCbCr": _PyAccess32_3,
352
+ "RGBA": _PyAccess32_4,
353
+ "RGBa": _PyAccess32_4,
354
+ "RGBX": _PyAccess32_4,
355
+ "CMYK": _PyAccess32_4,
356
+ "F": _PyAccessF,
357
+ "I": _PyAccessI32_N,
358
+ }
359
+
360
+ if sys.byteorder == "little":
361
+ mode_map["I;16"] = _PyAccessI16_N
362
+ mode_map["I;16L"] = _PyAccessI16_N
363
+ mode_map["I;16B"] = _PyAccessI16_B
364
+
365
+ mode_map["I;32L"] = _PyAccessI32_N
366
+ mode_map["I;32B"] = _PyAccessI32_Swap
367
+ else:
368
+ mode_map["I;16"] = _PyAccessI16_L
369
+ mode_map["I;16L"] = _PyAccessI16_L
370
+ mode_map["I;16B"] = _PyAccessI16_N
371
+
372
+ mode_map["I;32L"] = _PyAccessI32_Swap
373
+ mode_map["I;32B"] = _PyAccessI32_N
374
+
375
+
376
+ def new(img: Image.Image, readonly: bool = False) -> PyAccess | None:
377
+ access_type = mode_map.get(img.mode, None)
378
+ if not access_type:
379
+ logger.debug("PyAccess Not Implemented: %s", img.mode)
380
+ return None
381
+ return access_type(img, readonly)
evalkit_tf437/lib/python3.10/site-packages/PIL/SpiderImagePlugin.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ #
4
+ # SPIDER image file handling
5
+ #
6
+ # History:
7
+ # 2004-08-02 Created BB
8
+ # 2006-03-02 added save method
9
+ # 2006-03-13 added support for stack images
10
+ #
11
+ # Copyright (c) 2004 by Health Research Inc. (HRI) RENSSELAER, NY 12144.
12
+ # Copyright (c) 2004 by William Baxter.
13
+ # Copyright (c) 2004 by Secret Labs AB.
14
+ # Copyright (c) 2004 by Fredrik Lundh.
15
+ #
16
+
17
+ ##
18
+ # Image plugin for the Spider image format. This format is used
19
+ # by the SPIDER software, in processing image data from electron
20
+ # microscopy and tomography.
21
+ ##
22
+
23
+ #
24
+ # SpiderImagePlugin.py
25
+ #
26
+ # The Spider image format is used by SPIDER software, in processing
27
+ # image data from electron microscopy and tomography.
28
+ #
29
+ # Spider home page:
30
+ # https://spider.wadsworth.org/spider_doc/spider/docs/spider.html
31
+ #
32
+ # Details about the Spider image format:
33
+ # https://spider.wadsworth.org/spider_doc/spider/docs/image_doc.html
34
+ #
35
+ from __future__ import annotations
36
+
37
+ import os
38
+ import struct
39
+ import sys
40
+ from typing import IO, TYPE_CHECKING, Any, Tuple, cast
41
+
42
+ from . import Image, ImageFile
43
+
44
+
45
+ def isInt(f: Any) -> int:
46
+ try:
47
+ i = int(f)
48
+ if f - i == 0:
49
+ return 1
50
+ else:
51
+ return 0
52
+ except (ValueError, OverflowError):
53
+ return 0
54
+
55
+
56
+ iforms = [1, 3, -11, -12, -21, -22]
57
+
58
+
59
+ # There is no magic number to identify Spider files, so just check a
60
+ # series of header locations to see if they have reasonable values.
61
+ # Returns no. of bytes in the header, if it is a valid Spider header,
62
+ # otherwise returns 0
63
+
64
+
65
+ def isSpiderHeader(t: tuple[float, ...]) -> int:
66
+ h = (99,) + t # add 1 value so can use spider header index start=1
67
+ # header values 1,2,5,12,13,22,23 should be integers
68
+ for i in [1, 2, 5, 12, 13, 22, 23]:
69
+ if not isInt(h[i]):
70
+ return 0
71
+ # check iform
72
+ iform = int(h[5])
73
+ if iform not in iforms:
74
+ return 0
75
+ # check other header values
76
+ labrec = int(h[13]) # no. records in file header
77
+ labbyt = int(h[22]) # total no. of bytes in header
78
+ lenbyt = int(h[23]) # record length in bytes
79
+ if labbyt != (labrec * lenbyt):
80
+ return 0
81
+ # looks like a valid header
82
+ return labbyt
83
+
84
+
85
+ def isSpiderImage(filename: str) -> int:
86
+ with open(filename, "rb") as fp:
87
+ f = fp.read(92) # read 23 * 4 bytes
88
+ t = struct.unpack(">23f", f) # try big-endian first
89
+ hdrlen = isSpiderHeader(t)
90
+ if hdrlen == 0:
91
+ t = struct.unpack("<23f", f) # little-endian
92
+ hdrlen = isSpiderHeader(t)
93
+ return hdrlen
94
+
95
+
96
+ class SpiderImageFile(ImageFile.ImageFile):
97
+ format = "SPIDER"
98
+ format_description = "Spider 2D image"
99
+ _close_exclusive_fp_after_loading = False
100
+
101
+ def _open(self) -> None:
102
+ # check header
103
+ n = 27 * 4 # read 27 float values
104
+ f = self.fp.read(n)
105
+
106
+ try:
107
+ self.bigendian = 1
108
+ t = struct.unpack(">27f", f) # try big-endian first
109
+ hdrlen = isSpiderHeader(t)
110
+ if hdrlen == 0:
111
+ self.bigendian = 0
112
+ t = struct.unpack("<27f", f) # little-endian
113
+ hdrlen = isSpiderHeader(t)
114
+ if hdrlen == 0:
115
+ msg = "not a valid Spider file"
116
+ raise SyntaxError(msg)
117
+ except struct.error as e:
118
+ msg = "not a valid Spider file"
119
+ raise SyntaxError(msg) from e
120
+
121
+ h = (99,) + t # add 1 value : spider header index starts at 1
122
+ iform = int(h[5])
123
+ if iform != 1:
124
+ msg = "not a Spider 2D image"
125
+ raise SyntaxError(msg)
126
+
127
+ self._size = int(h[12]), int(h[2]) # size in pixels (width, height)
128
+ self.istack = int(h[24])
129
+ self.imgnumber = int(h[27])
130
+
131
+ if self.istack == 0 and self.imgnumber == 0:
132
+ # stk=0, img=0: a regular 2D image
133
+ offset = hdrlen
134
+ self._nimages = 1
135
+ elif self.istack > 0 and self.imgnumber == 0:
136
+ # stk>0, img=0: Opening the stack for the first time
137
+ self.imgbytes = int(h[12]) * int(h[2]) * 4
138
+ self.hdrlen = hdrlen
139
+ self._nimages = int(h[26])
140
+ # Point to the first image in the stack
141
+ offset = hdrlen * 2
142
+ self.imgnumber = 1
143
+ elif self.istack == 0 and self.imgnumber > 0:
144
+ # stk=0, img>0: an image within the stack
145
+ offset = hdrlen + self.stkoffset
146
+ self.istack = 2 # So Image knows it's still a stack
147
+ else:
148
+ msg = "inconsistent stack header values"
149
+ raise SyntaxError(msg)
150
+
151
+ if self.bigendian:
152
+ self.rawmode = "F;32BF"
153
+ else:
154
+ self.rawmode = "F;32F"
155
+ self._mode = "F"
156
+
157
+ self.tile = [("raw", (0, 0) + self.size, offset, (self.rawmode, 0, 1))]
158
+ self._fp = self.fp # FIXME: hack
159
+
160
+ @property
161
+ def n_frames(self) -> int:
162
+ return self._nimages
163
+
164
+ @property
165
+ def is_animated(self) -> bool:
166
+ return self._nimages > 1
167
+
168
+ # 1st image index is zero (although SPIDER imgnumber starts at 1)
169
+ def tell(self) -> int:
170
+ if self.imgnumber < 1:
171
+ return 0
172
+ else:
173
+ return self.imgnumber - 1
174
+
175
+ def seek(self, frame: int) -> None:
176
+ if self.istack == 0:
177
+ msg = "attempt to seek in a non-stack file"
178
+ raise EOFError(msg)
179
+ if not self._seek_check(frame):
180
+ return
181
+ self.stkoffset = self.hdrlen + frame * (self.hdrlen + self.imgbytes)
182
+ self.fp = self._fp
183
+ self.fp.seek(self.stkoffset)
184
+ self._open()
185
+
186
+ # returns a byte image after rescaling to 0..255
187
+ def convert2byte(self, depth: int = 255) -> Image.Image:
188
+ extrema = self.getextrema()
189
+ assert isinstance(extrema[0], float)
190
+ minimum, maximum = cast(Tuple[float, float], extrema)
191
+ m: float = 1
192
+ if maximum != minimum:
193
+ m = depth / (maximum - minimum)
194
+ b = -m * minimum
195
+ return self.point(lambda i: i * m + b).convert("L")
196
+
197
+ if TYPE_CHECKING:
198
+ from . import ImageTk
199
+
200
+ # returns a ImageTk.PhotoImage object, after rescaling to 0..255
201
+ def tkPhotoImage(self) -> ImageTk.PhotoImage:
202
+ from . import ImageTk
203
+
204
+ return ImageTk.PhotoImage(self.convert2byte(), palette=256)
205
+
206
+
207
+ # --------------------------------------------------------------------
208
+ # Image series
209
+
210
+
211
+ # given a list of filenames, return a list of images
212
+ def loadImageSeries(filelist: list[str] | None = None) -> list[SpiderImageFile] | None:
213
+ """create a list of :py:class:`~PIL.Image.Image` objects for use in a montage"""
214
+ if filelist is None or len(filelist) < 1:
215
+ return None
216
+
217
+ imglist = []
218
+ for img in filelist:
219
+ if not os.path.exists(img):
220
+ print(f"unable to find {img}")
221
+ continue
222
+ try:
223
+ with Image.open(img) as im:
224
+ im = im.convert2byte()
225
+ except Exception:
226
+ if not isSpiderImage(img):
227
+ print(f"{img} is not a Spider image file")
228
+ continue
229
+ im.info["filename"] = img
230
+ imglist.append(im)
231
+ return imglist
232
+
233
+
234
+ # --------------------------------------------------------------------
235
+ # For saving images in Spider format
236
+
237
+
238
+ def makeSpiderHeader(im: Image.Image) -> list[bytes]:
239
+ nsam, nrow = im.size
240
+ lenbyt = nsam * 4 # There are labrec records in the header
241
+ labrec = int(1024 / lenbyt)
242
+ if 1024 % lenbyt != 0:
243
+ labrec += 1
244
+ labbyt = labrec * lenbyt
245
+ nvalues = int(labbyt / 4)
246
+ if nvalues < 23:
247
+ return []
248
+
249
+ hdr = [0.0] * nvalues
250
+
251
+ # NB these are Fortran indices
252
+ hdr[1] = 1.0 # nslice (=1 for an image)
253
+ hdr[2] = float(nrow) # number of rows per slice
254
+ hdr[3] = float(nrow) # number of records in the image
255
+ hdr[5] = 1.0 # iform for 2D image
256
+ hdr[12] = float(nsam) # number of pixels per line
257
+ hdr[13] = float(labrec) # number of records in file header
258
+ hdr[22] = float(labbyt) # total number of bytes in header
259
+ hdr[23] = float(lenbyt) # record length in bytes
260
+
261
+ # adjust for Fortran indexing
262
+ hdr = hdr[1:]
263
+ hdr.append(0.0)
264
+ # pack binary data into a string
265
+ return [struct.pack("f", v) for v in hdr]
266
+
267
+
268
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
269
+ if im.mode[0] != "F":
270
+ im = im.convert("F")
271
+
272
+ hdr = makeSpiderHeader(im)
273
+ if len(hdr) < 256:
274
+ msg = "Error creating Spider header"
275
+ raise OSError(msg)
276
+
277
+ # write the SPIDER header
278
+ fp.writelines(hdr)
279
+
280
+ rawmode = "F;32NF" # 32-bit native floating point
281
+ ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))])
282
+
283
+
284
+ def _save_spider(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
285
+ # get the filename extension and register it with Image
286
+ filename_ext = os.path.splitext(filename)[1]
287
+ ext = filename_ext.decode() if isinstance(filename_ext, bytes) else filename_ext
288
+ Image.register_extension(SpiderImageFile.format, ext)
289
+ _save(im, fp, filename)
290
+
291
+
292
+ # --------------------------------------------------------------------
293
+
294
+
295
+ Image.register_open(SpiderImageFile.format, SpiderImageFile)
296
+ Image.register_save(SpiderImageFile.format, _save_spider)
297
+
298
+ if __name__ == "__main__":
299
+ if len(sys.argv) < 2:
300
+ print("Syntax: python3 SpiderImagePlugin.py [infile] [outfile]")
301
+ sys.exit()
302
+
303
+ filename = sys.argv[1]
304
+ if not isSpiderImage(filename):
305
+ print("input image must be in Spider format")
306
+ sys.exit()
307
+
308
+ with Image.open(filename) as im:
309
+ print(f"image: {im}")
310
+ print(f"format: {im.format}")
311
+ print(f"size: {im.size}")
312
+ print(f"mode: {im.mode}")
313
+ print("max, min: ", end=" ")
314
+ print(im.getextrema())
315
+
316
+ if len(sys.argv) > 2:
317
+ outfile = sys.argv[2]
318
+
319
+ # perform some image operation
320
+ im = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
321
+ print(
322
+ f"saving a flipped version of {os.path.basename(filename)} "
323
+ f"as {outfile} "
324
+ )
325
+ im.save(outfile, SpiderImageFile.format)
evalkit_tf437/lib/python3.10/site-packages/PIL/TiffTags.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # TIFF tags
6
+ #
7
+ # This module provides clear-text names for various well-known
8
+ # TIFF tags. the TIFF codec works just fine without it.
9
+ #
10
+ # Copyright (c) Secret Labs AB 1999.
11
+ #
12
+ # See the README file for information on usage and redistribution.
13
+ #
14
+
15
+ ##
16
+ # This module provides constants and clear-text names for various
17
+ # well-known TIFF tags.
18
+ ##
19
+ from __future__ import annotations
20
+
21
+ from typing import NamedTuple
22
+
23
+
24
+ class _TagInfo(NamedTuple):
25
+ value: int | None
26
+ name: str
27
+ type: int | None
28
+ length: int | None
29
+ enum: dict[str, int]
30
+
31
+
32
+ class TagInfo(_TagInfo):
33
+ __slots__: list[str] = []
34
+
35
+ def __new__(cls, value=None, name="unknown", type=None, length=None, enum=None):
36
+ return super().__new__(cls, value, name, type, length, enum or {})
37
+
38
+ def cvt_enum(self, value):
39
+ # Using get will call hash(value), which can be expensive
40
+ # for some types (e.g. Fraction). Since self.enum is rarely
41
+ # used, it's usually better to test it first.
42
+ return self.enum.get(value, value) if self.enum else value
43
+
44
+
45
+ def lookup(tag, group=None):
46
+ """
47
+ :param tag: Integer tag number
48
+ :param group: Which :py:data:`~PIL.TiffTags.TAGS_V2_GROUPS` to look in
49
+
50
+ .. versionadded:: 8.3.0
51
+
52
+ :returns: Taginfo namedtuple, From the ``TAGS_V2`` info if possible,
53
+ otherwise just populating the value and name from ``TAGS``.
54
+ If the tag is not recognized, "unknown" is returned for the name
55
+
56
+ """
57
+
58
+ if group is not None:
59
+ info = TAGS_V2_GROUPS[group].get(tag) if group in TAGS_V2_GROUPS else None
60
+ else:
61
+ info = TAGS_V2.get(tag)
62
+ return info or TagInfo(tag, TAGS.get(tag, "unknown"))
63
+
64
+
65
+ ##
66
+ # Map tag numbers to tag info.
67
+ #
68
+ # id: (Name, Type, Length[, enum_values])
69
+ #
70
+ # The length here differs from the length in the tiff spec. For
71
+ # numbers, the tiff spec is for the number of fields returned. We
72
+ # agree here. For string-like types, the tiff spec uses the length of
73
+ # field in bytes. In Pillow, we are using the number of expected
74
+ # fields, in general 1 for string-like types.
75
+
76
+
77
+ BYTE = 1
78
+ ASCII = 2
79
+ SHORT = 3
80
+ LONG = 4
81
+ RATIONAL = 5
82
+ SIGNED_BYTE = 6
83
+ UNDEFINED = 7
84
+ SIGNED_SHORT = 8
85
+ SIGNED_LONG = 9
86
+ SIGNED_RATIONAL = 10
87
+ FLOAT = 11
88
+ DOUBLE = 12
89
+ IFD = 13
90
+ LONG8 = 16
91
+
92
+ _tags_v2 = {
93
+ 254: ("NewSubfileType", LONG, 1),
94
+ 255: ("SubfileType", SHORT, 1),
95
+ 256: ("ImageWidth", LONG, 1),
96
+ 257: ("ImageLength", LONG, 1),
97
+ 258: ("BitsPerSample", SHORT, 0),
98
+ 259: (
99
+ "Compression",
100
+ SHORT,
101
+ 1,
102
+ {
103
+ "Uncompressed": 1,
104
+ "CCITT 1d": 2,
105
+ "Group 3 Fax": 3,
106
+ "Group 4 Fax": 4,
107
+ "LZW": 5,
108
+ "JPEG": 6,
109
+ "PackBits": 32773,
110
+ },
111
+ ),
112
+ 262: (
113
+ "PhotometricInterpretation",
114
+ SHORT,
115
+ 1,
116
+ {
117
+ "WhiteIsZero": 0,
118
+ "BlackIsZero": 1,
119
+ "RGB": 2,
120
+ "RGB Palette": 3,
121
+ "Transparency Mask": 4,
122
+ "CMYK": 5,
123
+ "YCbCr": 6,
124
+ "CieLAB": 8,
125
+ "CFA": 32803, # TIFF/EP, Adobe DNG
126
+ "LinearRaw": 32892, # Adobe DNG
127
+ },
128
+ ),
129
+ 263: ("Threshholding", SHORT, 1),
130
+ 264: ("CellWidth", SHORT, 1),
131
+ 265: ("CellLength", SHORT, 1),
132
+ 266: ("FillOrder", SHORT, 1),
133
+ 269: ("DocumentName", ASCII, 1),
134
+ 270: ("ImageDescription", ASCII, 1),
135
+ 271: ("Make", ASCII, 1),
136
+ 272: ("Model", ASCII, 1),
137
+ 273: ("StripOffsets", LONG, 0),
138
+ 274: ("Orientation", SHORT, 1),
139
+ 277: ("SamplesPerPixel", SHORT, 1),
140
+ 278: ("RowsPerStrip", LONG, 1),
141
+ 279: ("StripByteCounts", LONG, 0),
142
+ 280: ("MinSampleValue", SHORT, 0),
143
+ 281: ("MaxSampleValue", SHORT, 0),
144
+ 282: ("XResolution", RATIONAL, 1),
145
+ 283: ("YResolution", RATIONAL, 1),
146
+ 284: ("PlanarConfiguration", SHORT, 1, {"Contiguous": 1, "Separate": 2}),
147
+ 285: ("PageName", ASCII, 1),
148
+ 286: ("XPosition", RATIONAL, 1),
149
+ 287: ("YPosition", RATIONAL, 1),
150
+ 288: ("FreeOffsets", LONG, 1),
151
+ 289: ("FreeByteCounts", LONG, 1),
152
+ 290: ("GrayResponseUnit", SHORT, 1),
153
+ 291: ("GrayResponseCurve", SHORT, 0),
154
+ 292: ("T4Options", LONG, 1),
155
+ 293: ("T6Options", LONG, 1),
156
+ 296: ("ResolutionUnit", SHORT, 1, {"none": 1, "inch": 2, "cm": 3}),
157
+ 297: ("PageNumber", SHORT, 2),
158
+ 301: ("TransferFunction", SHORT, 0),
159
+ 305: ("Software", ASCII, 1),
160
+ 306: ("DateTime", ASCII, 1),
161
+ 315: ("Artist", ASCII, 1),
162
+ 316: ("HostComputer", ASCII, 1),
163
+ 317: ("Predictor", SHORT, 1, {"none": 1, "Horizontal Differencing": 2}),
164
+ 318: ("WhitePoint", RATIONAL, 2),
165
+ 319: ("PrimaryChromaticities", RATIONAL, 6),
166
+ 320: ("ColorMap", SHORT, 0),
167
+ 321: ("HalftoneHints", SHORT, 2),
168
+ 322: ("TileWidth", LONG, 1),
169
+ 323: ("TileLength", LONG, 1),
170
+ 324: ("TileOffsets", LONG, 0),
171
+ 325: ("TileByteCounts", LONG, 0),
172
+ 330: ("SubIFDs", LONG, 0),
173
+ 332: ("InkSet", SHORT, 1),
174
+ 333: ("InkNames", ASCII, 1),
175
+ 334: ("NumberOfInks", SHORT, 1),
176
+ 336: ("DotRange", SHORT, 0),
177
+ 337: ("TargetPrinter", ASCII, 1),
178
+ 338: ("ExtraSamples", SHORT, 0),
179
+ 339: ("SampleFormat", SHORT, 0),
180
+ 340: ("SMinSampleValue", DOUBLE, 0),
181
+ 341: ("SMaxSampleValue", DOUBLE, 0),
182
+ 342: ("TransferRange", SHORT, 6),
183
+ 347: ("JPEGTables", UNDEFINED, 1),
184
+ # obsolete JPEG tags
185
+ 512: ("JPEGProc", SHORT, 1),
186
+ 513: ("JPEGInterchangeFormat", LONG, 1),
187
+ 514: ("JPEGInterchangeFormatLength", LONG, 1),
188
+ 515: ("JPEGRestartInterval", SHORT, 1),
189
+ 517: ("JPEGLosslessPredictors", SHORT, 0),
190
+ 518: ("JPEGPointTransforms", SHORT, 0),
191
+ 519: ("JPEGQTables", LONG, 0),
192
+ 520: ("JPEGDCTables", LONG, 0),
193
+ 521: ("JPEGACTables", LONG, 0),
194
+ 529: ("YCbCrCoefficients", RATIONAL, 3),
195
+ 530: ("YCbCrSubSampling", SHORT, 2),
196
+ 531: ("YCbCrPositioning", SHORT, 1),
197
+ 532: ("ReferenceBlackWhite", RATIONAL, 6),
198
+ 700: ("XMP", BYTE, 0),
199
+ 33432: ("Copyright", ASCII, 1),
200
+ 33723: ("IptcNaaInfo", UNDEFINED, 1),
201
+ 34377: ("PhotoshopInfo", BYTE, 0),
202
+ # FIXME add more tags here
203
+ 34665: ("ExifIFD", LONG, 1),
204
+ 34675: ("ICCProfile", UNDEFINED, 1),
205
+ 34853: ("GPSInfoIFD", LONG, 1),
206
+ 36864: ("ExifVersion", UNDEFINED, 1),
207
+ 37724: ("ImageSourceData", UNDEFINED, 1),
208
+ 40965: ("InteroperabilityIFD", LONG, 1),
209
+ 41730: ("CFAPattern", UNDEFINED, 1),
210
+ # MPInfo
211
+ 45056: ("MPFVersion", UNDEFINED, 1),
212
+ 45057: ("NumberOfImages", LONG, 1),
213
+ 45058: ("MPEntry", UNDEFINED, 1),
214
+ 45059: ("ImageUIDList", UNDEFINED, 0), # UNDONE, check
215
+ 45060: ("TotalFrames", LONG, 1),
216
+ 45313: ("MPIndividualNum", LONG, 1),
217
+ 45569: ("PanOrientation", LONG, 1),
218
+ 45570: ("PanOverlap_H", RATIONAL, 1),
219
+ 45571: ("PanOverlap_V", RATIONAL, 1),
220
+ 45572: ("BaseViewpointNum", LONG, 1),
221
+ 45573: ("ConvergenceAngle", SIGNED_RATIONAL, 1),
222
+ 45574: ("BaselineLength", RATIONAL, 1),
223
+ 45575: ("VerticalDivergence", SIGNED_RATIONAL, 1),
224
+ 45576: ("AxisDistance_X", SIGNED_RATIONAL, 1),
225
+ 45577: ("AxisDistance_Y", SIGNED_RATIONAL, 1),
226
+ 45578: ("AxisDistance_Z", SIGNED_RATIONAL, 1),
227
+ 45579: ("YawAngle", SIGNED_RATIONAL, 1),
228
+ 45580: ("PitchAngle", SIGNED_RATIONAL, 1),
229
+ 45581: ("RollAngle", SIGNED_RATIONAL, 1),
230
+ 40960: ("FlashPixVersion", UNDEFINED, 1),
231
+ 50741: ("MakerNoteSafety", SHORT, 1, {"Unsafe": 0, "Safe": 1}),
232
+ 50780: ("BestQualityScale", RATIONAL, 1),
233
+ 50838: ("ImageJMetaDataByteCounts", LONG, 0), # Can be more than one
234
+ 50839: ("ImageJMetaData", UNDEFINED, 1), # see Issue #2006
235
+ }
236
+ TAGS_V2_GROUPS = {
237
+ # ExifIFD
238
+ 34665: {
239
+ 36864: ("ExifVersion", UNDEFINED, 1),
240
+ 40960: ("FlashPixVersion", UNDEFINED, 1),
241
+ 40965: ("InteroperabilityIFD", LONG, 1),
242
+ 41730: ("CFAPattern", UNDEFINED, 1),
243
+ },
244
+ # GPSInfoIFD
245
+ 34853: {
246
+ 0: ("GPSVersionID", BYTE, 4),
247
+ 1: ("GPSLatitudeRef", ASCII, 2),
248
+ 2: ("GPSLatitude", RATIONAL, 3),
249
+ 3: ("GPSLongitudeRef", ASCII, 2),
250
+ 4: ("GPSLongitude", RATIONAL, 3),
251
+ 5: ("GPSAltitudeRef", BYTE, 1),
252
+ 6: ("GPSAltitude", RATIONAL, 1),
253
+ 7: ("GPSTimeStamp", RATIONAL, 3),
254
+ 8: ("GPSSatellites", ASCII, 0),
255
+ 9: ("GPSStatus", ASCII, 2),
256
+ 10: ("GPSMeasureMode", ASCII, 2),
257
+ 11: ("GPSDOP", RATIONAL, 1),
258
+ 12: ("GPSSpeedRef", ASCII, 2),
259
+ 13: ("GPSSpeed", RATIONAL, 1),
260
+ 14: ("GPSTrackRef", ASCII, 2),
261
+ 15: ("GPSTrack", RATIONAL, 1),
262
+ 16: ("GPSImgDirectionRef", ASCII, 2),
263
+ 17: ("GPSImgDirection", RATIONAL, 1),
264
+ 18: ("GPSMapDatum", ASCII, 0),
265
+ 19: ("GPSDestLatitudeRef", ASCII, 2),
266
+ 20: ("GPSDestLatitude", RATIONAL, 3),
267
+ 21: ("GPSDestLongitudeRef", ASCII, 2),
268
+ 22: ("GPSDestLongitude", RATIONAL, 3),
269
+ 23: ("GPSDestBearingRef", ASCII, 2),
270
+ 24: ("GPSDestBearing", RATIONAL, 1),
271
+ 25: ("GPSDestDistanceRef", ASCII, 2),
272
+ 26: ("GPSDestDistance", RATIONAL, 1),
273
+ 27: ("GPSProcessingMethod", UNDEFINED, 0),
274
+ 28: ("GPSAreaInformation", UNDEFINED, 0),
275
+ 29: ("GPSDateStamp", ASCII, 11),
276
+ 30: ("GPSDifferential", SHORT, 1),
277
+ },
278
+ # InteroperabilityIFD
279
+ 40965: {1: ("InteropIndex", ASCII, 1), 2: ("InteropVersion", UNDEFINED, 1)},
280
+ }
281
+
282
+ # Legacy Tags structure
283
+ # these tags aren't included above, but were in the previous versions
284
+ TAGS = {
285
+ 347: "JPEGTables",
286
+ 700: "XMP",
287
+ # Additional Exif Info
288
+ 32932: "Wang Annotation",
289
+ 33434: "ExposureTime",
290
+ 33437: "FNumber",
291
+ 33445: "MD FileTag",
292
+ 33446: "MD ScalePixel",
293
+ 33447: "MD ColorTable",
294
+ 33448: "MD LabName",
295
+ 33449: "MD SampleInfo",
296
+ 33450: "MD PrepDate",
297
+ 33451: "MD PrepTime",
298
+ 33452: "MD FileUnits",
299
+ 33550: "ModelPixelScaleTag",
300
+ 33723: "IptcNaaInfo",
301
+ 33918: "INGR Packet Data Tag",
302
+ 33919: "INGR Flag Registers",
303
+ 33920: "IrasB Transformation Matrix",
304
+ 33922: "ModelTiepointTag",
305
+ 34264: "ModelTransformationTag",
306
+ 34377: "PhotoshopInfo",
307
+ 34735: "GeoKeyDirectoryTag",
308
+ 34736: "GeoDoubleParamsTag",
309
+ 34737: "GeoAsciiParamsTag",
310
+ 34850: "ExposureProgram",
311
+ 34852: "SpectralSensitivity",
312
+ 34855: "ISOSpeedRatings",
313
+ 34856: "OECF",
314
+ 34864: "SensitivityType",
315
+ 34865: "StandardOutputSensitivity",
316
+ 34866: "RecommendedExposureIndex",
317
+ 34867: "ISOSpeed",
318
+ 34868: "ISOSpeedLatitudeyyy",
319
+ 34869: "ISOSpeedLatitudezzz",
320
+ 34908: "HylaFAX FaxRecvParams",
321
+ 34909: "HylaFAX FaxSubAddress",
322
+ 34910: "HylaFAX FaxRecvTime",
323
+ 36864: "ExifVersion",
324
+ 36867: "DateTimeOriginal",
325
+ 36868: "DateTimeDigitized",
326
+ 37121: "ComponentsConfiguration",
327
+ 37122: "CompressedBitsPerPixel",
328
+ 37724: "ImageSourceData",
329
+ 37377: "ShutterSpeedValue",
330
+ 37378: "ApertureValue",
331
+ 37379: "BrightnessValue",
332
+ 37380: "ExposureBiasValue",
333
+ 37381: "MaxApertureValue",
334
+ 37382: "SubjectDistance",
335
+ 37383: "MeteringMode",
336
+ 37384: "LightSource",
337
+ 37385: "Flash",
338
+ 37386: "FocalLength",
339
+ 37396: "SubjectArea",
340
+ 37500: "MakerNote",
341
+ 37510: "UserComment",
342
+ 37520: "SubSec",
343
+ 37521: "SubSecTimeOriginal",
344
+ 37522: "SubsecTimeDigitized",
345
+ 40960: "FlashPixVersion",
346
+ 40961: "ColorSpace",
347
+ 40962: "PixelXDimension",
348
+ 40963: "PixelYDimension",
349
+ 40964: "RelatedSoundFile",
350
+ 40965: "InteroperabilityIFD",
351
+ 41483: "FlashEnergy",
352
+ 41484: "SpatialFrequencyResponse",
353
+ 41486: "FocalPlaneXResolution",
354
+ 41487: "FocalPlaneYResolution",
355
+ 41488: "FocalPlaneResolutionUnit",
356
+ 41492: "SubjectLocation",
357
+ 41493: "ExposureIndex",
358
+ 41495: "SensingMethod",
359
+ 41728: "FileSource",
360
+ 41729: "SceneType",
361
+ 41730: "CFAPattern",
362
+ 41985: "CustomRendered",
363
+ 41986: "ExposureMode",
364
+ 41987: "WhiteBalance",
365
+ 41988: "DigitalZoomRatio",
366
+ 41989: "FocalLengthIn35mmFilm",
367
+ 41990: "SceneCaptureType",
368
+ 41991: "GainControl",
369
+ 41992: "Contrast",
370
+ 41993: "Saturation",
371
+ 41994: "Sharpness",
372
+ 41995: "DeviceSettingDescription",
373
+ 41996: "SubjectDistanceRange",
374
+ 42016: "ImageUniqueID",
375
+ 42032: "CameraOwnerName",
376
+ 42033: "BodySerialNumber",
377
+ 42034: "LensSpecification",
378
+ 42035: "LensMake",
379
+ 42036: "LensModel",
380
+ 42037: "LensSerialNumber",
381
+ 42112: "GDAL_METADATA",
382
+ 42113: "GDAL_NODATA",
383
+ 42240: "Gamma",
384
+ 50215: "Oce Scanjob Description",
385
+ 50216: "Oce Application Selector",
386
+ 50217: "Oce Identification Number",
387
+ 50218: "Oce ImageLogic Characteristics",
388
+ # Adobe DNG
389
+ 50706: "DNGVersion",
390
+ 50707: "DNGBackwardVersion",
391
+ 50708: "UniqueCameraModel",
392
+ 50709: "LocalizedCameraModel",
393
+ 50710: "CFAPlaneColor",
394
+ 50711: "CFALayout",
395
+ 50712: "LinearizationTable",
396
+ 50713: "BlackLevelRepeatDim",
397
+ 50714: "BlackLevel",
398
+ 50715: "BlackLevelDeltaH",
399
+ 50716: "BlackLevelDeltaV",
400
+ 50717: "WhiteLevel",
401
+ 50718: "DefaultScale",
402
+ 50719: "DefaultCropOrigin",
403
+ 50720: "DefaultCropSize",
404
+ 50721: "ColorMatrix1",
405
+ 50722: "ColorMatrix2",
406
+ 50723: "CameraCalibration1",
407
+ 50724: "CameraCalibration2",
408
+ 50725: "ReductionMatrix1",
409
+ 50726: "ReductionMatrix2",
410
+ 50727: "AnalogBalance",
411
+ 50728: "AsShotNeutral",
412
+ 50729: "AsShotWhiteXY",
413
+ 50730: "BaselineExposure",
414
+ 50731: "BaselineNoise",
415
+ 50732: "BaselineSharpness",
416
+ 50733: "BayerGreenSplit",
417
+ 50734: "LinearResponseLimit",
418
+ 50735: "CameraSerialNumber",
419
+ 50736: "LensInfo",
420
+ 50737: "ChromaBlurRadius",
421
+ 50738: "AntiAliasStrength",
422
+ 50740: "DNGPrivateData",
423
+ 50778: "CalibrationIlluminant1",
424
+ 50779: "CalibrationIlluminant2",
425
+ 50784: "Alias Layer Metadata",
426
+ }
427
+
428
+ TAGS_V2: dict[int, TagInfo] = {}
429
+
430
+
431
+ def _populate():
432
+ for k, v in _tags_v2.items():
433
+ # Populate legacy structure.
434
+ TAGS[k] = v[0]
435
+ if len(v) == 4:
436
+ for sk, sv in v[3].items():
437
+ TAGS[(k, sv)] = sk
438
+
439
+ TAGS_V2[k] = TagInfo(k, *v)
440
+
441
+ for tags in TAGS_V2_GROUPS.values():
442
+ for k, v in tags.items():
443
+ tags[k] = TagInfo(k, *v)
444
+
445
+
446
+ _populate()
447
+ ##
448
+ # Map type numbers to type names -- defined in ImageFileDirectory.
449
+
450
+ TYPES: dict[int, str] = {}
451
+
452
+ #
453
+ # These tags are handled by default in libtiff, without
454
+ # adding to the custom dictionary. From tif_dir.c, searching for
455
+ # case TIFFTAG in the _TIFFVSetField function:
456
+ # Line: item.
457
+ # 148: case TIFFTAG_SUBFILETYPE:
458
+ # 151: case TIFFTAG_IMAGEWIDTH:
459
+ # 154: case TIFFTAG_IMAGELENGTH:
460
+ # 157: case TIFFTAG_BITSPERSAMPLE:
461
+ # 181: case TIFFTAG_COMPRESSION:
462
+ # 202: case TIFFTAG_PHOTOMETRIC:
463
+ # 205: case TIFFTAG_THRESHHOLDING:
464
+ # 208: case TIFFTAG_FILLORDER:
465
+ # 214: case TIFFTAG_ORIENTATION:
466
+ # 221: case TIFFTAG_SAMPLESPERPIXEL:
467
+ # 228: case TIFFTAG_ROWSPERSTRIP:
468
+ # 238: case TIFFTAG_MINSAMPLEVALUE:
469
+ # 241: case TIFFTAG_MAXSAMPLEVALUE:
470
+ # 244: case TIFFTAG_SMINSAMPLEVALUE:
471
+ # 247: case TIFFTAG_SMAXSAMPLEVALUE:
472
+ # 250: case TIFFTAG_XRESOLUTION:
473
+ # 256: case TIFFTAG_YRESOLUTION:
474
+ # 262: case TIFFTAG_PLANARCONFIG:
475
+ # 268: case TIFFTAG_XPOSITION:
476
+ # 271: case TIFFTAG_YPOSITION:
477
+ # 274: case TIFFTAG_RESOLUTIONUNIT:
478
+ # 280: case TIFFTAG_PAGENUMBER:
479
+ # 284: case TIFFTAG_HALFTONEHINTS:
480
+ # 288: case TIFFTAG_COLORMAP:
481
+ # 294: case TIFFTAG_EXTRASAMPLES:
482
+ # 298: case TIFFTAG_MATTEING:
483
+ # 305: case TIFFTAG_TILEWIDTH:
484
+ # 316: case TIFFTAG_TILELENGTH:
485
+ # 327: case TIFFTAG_TILEDEPTH:
486
+ # 333: case TIFFTAG_DATATYPE:
487
+ # 344: case TIFFTAG_SAMPLEFORMAT:
488
+ # 361: case TIFFTAG_IMAGEDEPTH:
489
+ # 364: case TIFFTAG_SUBIFD:
490
+ # 376: case TIFFTAG_YCBCRPOSITIONING:
491
+ # 379: case TIFFTAG_YCBCRSUBSAMPLING:
492
+ # 383: case TIFFTAG_TRANSFERFUNCTION:
493
+ # 389: case TIFFTAG_REFERENCEBLACKWHITE:
494
+ # 393: case TIFFTAG_INKNAMES:
495
+
496
+ # Following pseudo-tags are also handled by default in libtiff:
497
+ # TIFFTAG_JPEGQUALITY 65537
498
+
499
+ # some of these are not in our TAGS_V2 dict and were included from tiff.h
500
+
501
+ # This list also exists in encode.c
502
+ LIBTIFF_CORE = {
503
+ 255,
504
+ 256,
505
+ 257,
506
+ 258,
507
+ 259,
508
+ 262,
509
+ 263,
510
+ 266,
511
+ 274,
512
+ 277,
513
+ 278,
514
+ 280,
515
+ 281,
516
+ 340,
517
+ 341,
518
+ 282,
519
+ 283,
520
+ 284,
521
+ 286,
522
+ 287,
523
+ 296,
524
+ 297,
525
+ 321,
526
+ 320,
527
+ 338,
528
+ 32995,
529
+ 322,
530
+ 323,
531
+ 32998,
532
+ 32996,
533
+ 339,
534
+ 32997,
535
+ 330,
536
+ 531,
537
+ 530,
538
+ 301,
539
+ 532,
540
+ 333,
541
+ # as above
542
+ 269, # this has been in our tests forever, and works
543
+ 65537,
544
+ }
545
+
546
+ LIBTIFF_CORE.remove(255) # We don't have support for subfiletypes
547
+ LIBTIFF_CORE.remove(322) # We don't have support for writing tiled images with libtiff
548
+ LIBTIFF_CORE.remove(323) # Tiled images
549
+ LIBTIFF_CORE.remove(333) # Ink Names either
550
+
551
+ # Note to advanced users: There may be combinations of these
552
+ # parameters and values that when added properly, will work and
553
+ # produce valid tiff images that may work in your application.
554
+ # It is safe to add and remove tags from this set from Pillow's point
555
+ # of view so long as you test against libtiff.
evalkit_tf437/lib/python3.10/site-packages/PIL/WalImageFile.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # WAL file handling
6
+ #
7
+ # History:
8
+ # 2003-04-23 fl created
9
+ #
10
+ # Copyright (c) 2003 by Fredrik Lundh.
11
+ #
12
+ # See the README file for information on usage and redistribution.
13
+ #
14
+
15
+ """
16
+ This reader is based on the specification available from:
17
+ https://www.flipcode.com/archives/Quake_2_BSP_File_Format.shtml
18
+ and has been tested with a few sample files found using google.
19
+
20
+ .. note::
21
+ This format cannot be automatically recognized, so the reader
22
+ is not registered for use with :py:func:`PIL.Image.open()`.
23
+ To open a WAL file, use the :py:func:`PIL.WalImageFile.open()` function instead.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ from . import Image, ImageFile
28
+ from ._binary import i32le as i32
29
+
30
+
31
+ class WalImageFile(ImageFile.ImageFile):
32
+ format = "WAL"
33
+ format_description = "Quake2 Texture"
34
+
35
+ def _open(self) -> None:
36
+ self._mode = "P"
37
+
38
+ # read header fields
39
+ header = self.fp.read(32 + 24 + 32 + 12)
40
+ self._size = i32(header, 32), i32(header, 36)
41
+ Image._decompression_bomb_check(self.size)
42
+
43
+ # load pixel data
44
+ offset = i32(header, 40)
45
+ self.fp.seek(offset)
46
+
47
+ # strings are null-terminated
48
+ self.info["name"] = header[:32].split(b"\0", 1)[0]
49
+ next_name = header[56 : 56 + 32].split(b"\0", 1)[0]
50
+ if next_name:
51
+ self.info["next_name"] = next_name
52
+
53
+ def load(self):
54
+ if not self.im:
55
+ self.im = Image.core.new(self.mode, self.size)
56
+ self.frombytes(self.fp.read(self.size[0] * self.size[1]))
57
+ self.putpalette(quake2palette)
58
+ return Image.Image.load(self)
59
+
60
+
61
+ def open(filename):
62
+ """
63
+ Load texture from a Quake2 WAL texture file.
64
+
65
+ By default, a Quake2 standard palette is attached to the texture.
66
+ To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method.
67
+
68
+ :param filename: WAL file name, or an opened file handle.
69
+ :returns: An image instance.
70
+ """
71
+ return WalImageFile(filename)
72
+
73
+
74
+ quake2palette = (
75
+ # default palette taken from piffo 0.93 by Hans Häggström
76
+ b"\x01\x01\x01\x0b\x0b\x0b\x12\x12\x12\x17\x17\x17\x1b\x1b\x1b\x1e"
77
+ b"\x1e\x1e\x22\x22\x22\x26\x26\x26\x29\x29\x29\x2c\x2c\x2c\x2f\x2f"
78
+ b"\x2f\x32\x32\x32\x35\x35\x35\x37\x37\x37\x3a\x3a\x3a\x3c\x3c\x3c"
79
+ b"\x24\x1e\x13\x22\x1c\x12\x20\x1b\x12\x1f\x1a\x10\x1d\x19\x10\x1b"
80
+ b"\x17\x0f\x1a\x16\x0f\x18\x14\x0d\x17\x13\x0d\x16\x12\x0d\x14\x10"
81
+ b"\x0b\x13\x0f\x0b\x10\x0d\x0a\x0f\x0b\x0a\x0d\x0b\x07\x0b\x0a\x07"
82
+ b"\x23\x23\x26\x22\x22\x25\x22\x20\x23\x21\x1f\x22\x20\x1e\x20\x1f"
83
+ b"\x1d\x1e\x1d\x1b\x1c\x1b\x1a\x1a\x1a\x19\x19\x18\x17\x17\x17\x16"
84
+ b"\x16\x14\x14\x14\x13\x13\x13\x10\x10\x10\x0f\x0f\x0f\x0d\x0d\x0d"
85
+ b"\x2d\x28\x20\x29\x24\x1c\x27\x22\x1a\x25\x1f\x17\x38\x2e\x1e\x31"
86
+ b"\x29\x1a\x2c\x25\x17\x26\x20\x14\x3c\x30\x14\x37\x2c\x13\x33\x28"
87
+ b"\x12\x2d\x24\x10\x28\x1f\x0f\x22\x1a\x0b\x1b\x14\x0a\x13\x0f\x07"
88
+ b"\x31\x1a\x16\x30\x17\x13\x2e\x16\x10\x2c\x14\x0d\x2a\x12\x0b\x27"
89
+ b"\x0f\x0a\x25\x0f\x07\x21\x0d\x01\x1e\x0b\x01\x1c\x0b\x01\x1a\x0b"
90
+ b"\x01\x18\x0a\x01\x16\x0a\x01\x13\x0a\x01\x10\x07\x01\x0d\x07\x01"
91
+ b"\x29\x23\x1e\x27\x21\x1c\x26\x20\x1b\x25\x1f\x1a\x23\x1d\x19\x21"
92
+ b"\x1c\x18\x20\x1b\x17\x1e\x19\x16\x1c\x18\x14\x1b\x17\x13\x19\x14"
93
+ b"\x10\x17\x13\x0f\x14\x10\x0d\x12\x0f\x0b\x0f\x0b\x0a\x0b\x0a\x07"
94
+ b"\x26\x1a\x0f\x23\x19\x0f\x20\x17\x0f\x1c\x16\x0f\x19\x13\x0d\x14"
95
+ b"\x10\x0b\x10\x0d\x0a\x0b\x0a\x07\x33\x22\x1f\x35\x29\x26\x37\x2f"
96
+ b"\x2d\x39\x35\x34\x37\x39\x3a\x33\x37\x39\x30\x34\x36\x2b\x31\x34"
97
+ b"\x27\x2e\x31\x22\x2b\x2f\x1d\x28\x2c\x17\x25\x2a\x0f\x20\x26\x0d"
98
+ b"\x1e\x25\x0b\x1c\x22\x0a\x1b\x20\x07\x19\x1e\x07\x17\x1b\x07\x14"
99
+ b"\x18\x01\x12\x16\x01\x0f\x12\x01\x0b\x0d\x01\x07\x0a\x01\x01\x01"
100
+ b"\x2c\x21\x21\x2a\x1f\x1f\x29\x1d\x1d\x27\x1c\x1c\x26\x1a\x1a\x24"
101
+ b"\x18\x18\x22\x17\x17\x21\x16\x16\x1e\x13\x13\x1b\x12\x12\x18\x10"
102
+ b"\x10\x16\x0d\x0d\x12\x0b\x0b\x0d\x0a\x0a\x0a\x07\x07\x01\x01\x01"
103
+ b"\x2e\x30\x29\x2d\x2e\x27\x2b\x2c\x26\x2a\x2a\x24\x28\x29\x23\x27"
104
+ b"\x27\x21\x26\x26\x1f\x24\x24\x1d\x22\x22\x1c\x1f\x1f\x1a\x1c\x1c"
105
+ b"\x18\x19\x19\x16\x17\x17\x13\x13\x13\x10\x0f\x0f\x0d\x0b\x0b\x0a"
106
+ b"\x30\x1e\x1b\x2d\x1c\x19\x2c\x1a\x17\x2a\x19\x14\x28\x17\x13\x26"
107
+ b"\x16\x10\x24\x13\x0f\x21\x12\x0d\x1f\x10\x0b\x1c\x0f\x0a\x19\x0d"
108
+ b"\x0a\x16\x0b\x07\x12\x0a\x07\x0f\x07\x01\x0a\x01\x01\x01\x01\x01"
109
+ b"\x28\x29\x38\x26\x27\x36\x25\x26\x34\x24\x24\x31\x22\x22\x2f\x20"
110
+ b"\x21\x2d\x1e\x1f\x2a\x1d\x1d\x27\x1b\x1b\x25\x19\x19\x21\x17\x17"
111
+ b"\x1e\x14\x14\x1b\x13\x12\x17\x10\x0f\x13\x0d\x0b\x0f\x0a\x07\x07"
112
+ b"\x2f\x32\x29\x2d\x30\x26\x2b\x2e\x24\x29\x2c\x21\x27\x2a\x1e\x25"
113
+ b"\x28\x1c\x23\x26\x1a\x21\x25\x18\x1e\x22\x14\x1b\x1f\x10\x19\x1c"
114
+ b"\x0d\x17\x1a\x0a\x13\x17\x07\x10\x13\x01\x0d\x0f\x01\x0a\x0b\x01"
115
+ b"\x01\x3f\x01\x13\x3c\x0b\x1b\x39\x10\x20\x35\x14\x23\x31\x17\x23"
116
+ b"\x2d\x18\x23\x29\x18\x3f\x3f\x3f\x3f\x3f\x39\x3f\x3f\x31\x3f\x3f"
117
+ b"\x2a\x3f\x3f\x20\x3f\x3f\x14\x3f\x3c\x12\x3f\x39\x0f\x3f\x35\x0b"
118
+ b"\x3f\x32\x07\x3f\x2d\x01\x3d\x2a\x01\x3b\x26\x01\x39\x21\x01\x37"
119
+ b"\x1d\x01\x34\x1a\x01\x32\x16\x01\x2f\x12\x01\x2d\x0f\x01\x2a\x0b"
120
+ b"\x01\x27\x07\x01\x23\x01\x01\x1d\x01\x01\x17\x01\x01\x10\x01\x01"
121
+ b"\x3d\x01\x01\x19\x19\x3f\x3f\x01\x01\x01\x01\x3f\x16\x16\x13\x10"
122
+ b"\x10\x0f\x0d\x0d\x0b\x3c\x2e\x2a\x36\x27\x20\x30\x21\x18\x29\x1b"
123
+ b"\x10\x3c\x39\x37\x37\x32\x2f\x31\x2c\x28\x2b\x26\x21\x30\x22\x20"
124
+ )
evalkit_tf437/lib/python3.10/site-packages/PIL/XVThumbImagePlugin.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # XV Thumbnail file handler by Charles E. "Gene" Cash
6
+ # (gcash@magicnet.net)
7
+ #
8
+ # see xvcolor.c and xvbrowse.c in the sources to John Bradley's XV,
9
+ # available from ftp://ftp.cis.upenn.edu/pub/xv/
10
+ #
11
+ # history:
12
+ # 98-08-15 cec created (b/w only)
13
+ # 98-12-09 cec added color palette
14
+ # 98-12-28 fl added to PIL (with only a few very minor modifications)
15
+ #
16
+ # To do:
17
+ # FIXME: make save work (this requires quantization support)
18
+ #
19
+ from __future__ import annotations
20
+
21
+ from . import Image, ImageFile, ImagePalette
22
+ from ._binary import o8
23
+
24
+ _MAGIC = b"P7 332"
25
+
26
+ # standard color palette for thumbnails (RGB332)
27
+ PALETTE = b""
28
+ for r in range(8):
29
+ for g in range(8):
30
+ for b in range(4):
31
+ PALETTE = PALETTE + (
32
+ o8((r * 255) // 7) + o8((g * 255) // 7) + o8((b * 255) // 3)
33
+ )
34
+
35
+
36
+ def _accept(prefix: bytes) -> bool:
37
+ return prefix[:6] == _MAGIC
38
+
39
+
40
+ ##
41
+ # Image plugin for XV thumbnail images.
42
+
43
+
44
+ class XVThumbImageFile(ImageFile.ImageFile):
45
+ format = "XVThumb"
46
+ format_description = "XV thumbnail image"
47
+
48
+ def _open(self) -> None:
49
+ # check magic
50
+ assert self.fp is not None
51
+
52
+ if not _accept(self.fp.read(6)):
53
+ msg = "not an XV thumbnail file"
54
+ raise SyntaxError(msg)
55
+
56
+ # Skip to beginning of next line
57
+ self.fp.readline()
58
+
59
+ # skip info comments
60
+ while True:
61
+ s = self.fp.readline()
62
+ if not s:
63
+ msg = "Unexpected EOF reading XV thumbnail file"
64
+ raise SyntaxError(msg)
65
+ if s[0] != 35: # ie. when not a comment: '#'
66
+ break
67
+
68
+ # parse header line (already read)
69
+ s = s.strip().split()
70
+
71
+ self._mode = "P"
72
+ self._size = int(s[0]), int(s[1])
73
+
74
+ self.palette = ImagePalette.raw("RGB", PALETTE)
75
+
76
+ self.tile = [("raw", (0, 0) + self.size, self.fp.tell(), (self.mode, 0, 1))]
77
+
78
+
79
+ # --------------------------------------------------------------------
80
+
81
+ Image.register_open(XVThumbImageFile.format, XVThumbImageFile, _accept)
evalkit_tf437/lib/python3.10/site-packages/PIL/__init__.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pillow (Fork of the Python Imaging Library)
2
+
3
+ Pillow is the friendly PIL fork by Jeffrey A. Clark and contributors.
4
+ https://github.com/python-pillow/Pillow/
5
+
6
+ Pillow is forked from PIL 1.1.7.
7
+
8
+ PIL is the Python Imaging Library by Fredrik Lundh and contributors.
9
+ Copyright (c) 1999 by Secret Labs AB.
10
+
11
+ Use PIL.__version__ for this Pillow version.
12
+
13
+ ;-)
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from . import _version
19
+
20
+ # VERSION was removed in Pillow 6.0.0.
21
+ # PILLOW_VERSION was removed in Pillow 9.0.0.
22
+ # Use __version__ instead.
23
+ __version__ = _version.__version__
24
+ del _version
25
+
26
+
27
+ _plugins = [
28
+ "BlpImagePlugin",
29
+ "BmpImagePlugin",
30
+ "BufrStubImagePlugin",
31
+ "CurImagePlugin",
32
+ "DcxImagePlugin",
33
+ "DdsImagePlugin",
34
+ "EpsImagePlugin",
35
+ "FitsImagePlugin",
36
+ "FliImagePlugin",
37
+ "FpxImagePlugin",
38
+ "FtexImagePlugin",
39
+ "GbrImagePlugin",
40
+ "GifImagePlugin",
41
+ "GribStubImagePlugin",
42
+ "Hdf5StubImagePlugin",
43
+ "IcnsImagePlugin",
44
+ "IcoImagePlugin",
45
+ "ImImagePlugin",
46
+ "ImtImagePlugin",
47
+ "IptcImagePlugin",
48
+ "JpegImagePlugin",
49
+ "Jpeg2KImagePlugin",
50
+ "McIdasImagePlugin",
51
+ "MicImagePlugin",
52
+ "MpegImagePlugin",
53
+ "MpoImagePlugin",
54
+ "MspImagePlugin",
55
+ "PalmImagePlugin",
56
+ "PcdImagePlugin",
57
+ "PcxImagePlugin",
58
+ "PdfImagePlugin",
59
+ "PixarImagePlugin",
60
+ "PngImagePlugin",
61
+ "PpmImagePlugin",
62
+ "PsdImagePlugin",
63
+ "QoiImagePlugin",
64
+ "SgiImagePlugin",
65
+ "SpiderImagePlugin",
66
+ "SunImagePlugin",
67
+ "TgaImagePlugin",
68
+ "TiffImagePlugin",
69
+ "WebPImagePlugin",
70
+ "WmfImagePlugin",
71
+ "XbmImagePlugin",
72
+ "XpmImagePlugin",
73
+ "XVThumbImagePlugin",
74
+ ]
75
+
76
+
77
+ class UnidentifiedImageError(OSError):
78
+ """
79
+ Raised in :py:meth:`PIL.Image.open` if an image cannot be opened and identified.
80
+
81
+ If a PNG image raises this error, setting :data:`.ImageFile.LOAD_TRUNCATED_IMAGES`
82
+ to true may allow the image to be opened after all. The setting will ignore missing
83
+ data and checksum failures.
84
+ """
85
+
86
+ pass
evalkit_tf437/lib/python3.10/site-packages/PIL/_binary.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # Binary input/output support routines.
6
+ #
7
+ # Copyright (c) 1997-2003 by Secret Labs AB
8
+ # Copyright (c) 1995-2003 by Fredrik Lundh
9
+ # Copyright (c) 2012 by Brian Crowell
10
+ #
11
+ # See the README file for information on usage and redistribution.
12
+ #
13
+
14
+
15
+ """Binary input/output support routines."""
16
+ from __future__ import annotations
17
+
18
+ from struct import pack, unpack_from
19
+
20
+
21
+ def i8(c: bytes) -> int:
22
+ return c[0]
23
+
24
+
25
+ def o8(i: int) -> bytes:
26
+ return bytes((i & 255,))
27
+
28
+
29
+ # Input, le = little endian, be = big endian
30
+ def i16le(c: bytes, o: int = 0) -> int:
31
+ """
32
+ Converts a 2-bytes (16 bits) string to an unsigned integer.
33
+
34
+ :param c: string containing bytes to convert
35
+ :param o: offset of bytes to convert in string
36
+ """
37
+ return unpack_from("<H", c, o)[0]
38
+
39
+
40
+ def si16le(c: bytes, o: int = 0) -> int:
41
+ """
42
+ Converts a 2-bytes (16 bits) string to a signed integer.
43
+
44
+ :param c: string containing bytes to convert
45
+ :param o: offset of bytes to convert in string
46
+ """
47
+ return unpack_from("<h", c, o)[0]
48
+
49
+
50
+ def si16be(c: bytes, o: int = 0) -> int:
51
+ """
52
+ Converts a 2-bytes (16 bits) string to a signed integer, big endian.
53
+
54
+ :param c: string containing bytes to convert
55
+ :param o: offset of bytes to convert in string
56
+ """
57
+ return unpack_from(">h", c, o)[0]
58
+
59
+
60
+ def i32le(c: bytes, o: int = 0) -> int:
61
+ """
62
+ Converts a 4-bytes (32 bits) string to an unsigned integer.
63
+
64
+ :param c: string containing bytes to convert
65
+ :param o: offset of bytes to convert in string
66
+ """
67
+ return unpack_from("<I", c, o)[0]
68
+
69
+
70
+ def si32le(c: bytes, o: int = 0) -> int:
71
+ """
72
+ Converts a 4-bytes (32 bits) string to a signed integer.
73
+
74
+ :param c: string containing bytes to convert
75
+ :param o: offset of bytes to convert in string
76
+ """
77
+ return unpack_from("<i", c, o)[0]
78
+
79
+
80
+ def si32be(c: bytes, o: int = 0) -> int:
81
+ """
82
+ Converts a 4-bytes (32 bits) string to a signed integer, big endian.
83
+
84
+ :param c: string containing bytes to convert
85
+ :param o: offset of bytes to convert in string
86
+ """
87
+ return unpack_from(">i", c, o)[0]
88
+
89
+
90
+ def i16be(c: bytes, o: int = 0) -> int:
91
+ return unpack_from(">H", c, o)[0]
92
+
93
+
94
+ def i32be(c: bytes, o: int = 0) -> int:
95
+ return unpack_from(">I", c, o)[0]
96
+
97
+
98
+ # Output, le = little endian, be = big endian
99
+ def o16le(i: int) -> bytes:
100
+ return pack("<H", i)
101
+
102
+
103
+ def o32le(i: int) -> bytes:
104
+ return pack("<I", i)
105
+
106
+
107
+ def o16be(i: int) -> bytes:
108
+ return pack(">H", i)
109
+
110
+
111
+ def o32be(i: int) -> bytes:
112
+ return pack(">I", i)
evalkit_tf437/lib/python3.10/site-packages/PIL/_imaging.pyi ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ class ImagingCore:
4
+ def __getattr__(self, name: str) -> Any: ...
5
+
6
+ class ImagingFont:
7
+ def __getattr__(self, name: str) -> Any: ...
8
+
9
+ class ImagingDraw:
10
+ def __getattr__(self, name: str) -> Any: ...
11
+
12
+ class PixelAccess:
13
+ def __getitem__(self, xy: tuple[int, int]) -> float | tuple[int, ...]: ...
14
+ def __setitem__(
15
+ self, xy: tuple[int, int], color: float | tuple[int, ...]
16
+ ) -> None: ...
17
+
18
+ class ImagingDecoder:
19
+ def __getattr__(self, name: str) -> Any: ...
20
+
21
+ class ImagingEncoder:
22
+ def __getattr__(self, name: str) -> Any: ...
23
+
24
+ class _Outline:
25
+ def close(self) -> None: ...
26
+ def __getattr__(self, name: str) -> Any: ...
27
+
28
+ def font(image: ImagingCore, glyphdata: bytes) -> ImagingFont: ...
29
+ def outline() -> _Outline: ...
30
+ def __getattr__(name: str) -> Any: ...
evalkit_tf437/lib/python3.10/site-packages/PIL/_imagingft.pyi ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, TypedDict
2
+
3
+ from . import _imaging
4
+
5
+ class _Axis(TypedDict):
6
+ minimum: int | None
7
+ default: int | None
8
+ maximum: int | None
9
+ name: bytes | None
10
+
11
+ class Font:
12
+ @property
13
+ def family(self) -> str | None: ...
14
+ @property
15
+ def style(self) -> str | None: ...
16
+ @property
17
+ def ascent(self) -> int: ...
18
+ @property
19
+ def descent(self) -> int: ...
20
+ @property
21
+ def height(self) -> int: ...
22
+ @property
23
+ def x_ppem(self) -> int: ...
24
+ @property
25
+ def y_ppem(self) -> int: ...
26
+ @property
27
+ def glyphs(self) -> int: ...
28
+ def render(
29
+ self,
30
+ string: str | bytes,
31
+ fill,
32
+ mode=...,
33
+ dir=...,
34
+ features=...,
35
+ lang=...,
36
+ stroke_width=...,
37
+ anchor=...,
38
+ foreground_ink_long=...,
39
+ x_start=...,
40
+ y_start=...,
41
+ /,
42
+ ) -> tuple[_imaging.ImagingCore, tuple[int, int]]: ...
43
+ def getsize(
44
+ self,
45
+ string: str | bytes | bytearray,
46
+ mode=...,
47
+ dir=...,
48
+ features=...,
49
+ lang=...,
50
+ anchor=...,
51
+ /,
52
+ ) -> tuple[tuple[int, int], tuple[int, int]]: ...
53
+ def getlength(
54
+ self, string: str | bytes, mode=..., dir=..., features=..., lang=..., /
55
+ ) -> float: ...
56
+ def getvarnames(self) -> list[bytes]: ...
57
+ def getvaraxes(self) -> list[_Axis] | None: ...
58
+ def setvarname(self, instance_index: int, /) -> None: ...
59
+ def setvaraxes(self, axes: list[float], /) -> None: ...
60
+
61
+ def getfont(
62
+ filename: str | bytes,
63
+ size: float,
64
+ index=...,
65
+ encoding=...,
66
+ font_bytes=...,
67
+ layout_engine=...,
68
+ ) -> Font: ...
69
+ def __getattr__(name: str) -> Any: ...
evalkit_tf437/lib/python3.10/site-packages/PIL/_tkinter_finder.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Find compiled module linking to Tcl / Tk libraries
2
+ """
3
+
4
+ from __future__ import annotations
5
+
6
+ import sys
7
+ import tkinter
8
+
9
+ tk = getattr(tkinter, "_tkinter")
10
+
11
+ try:
12
+ if hasattr(sys, "pypy_find_executable"):
13
+ TKINTER_LIB = tk.tklib_cffi.__file__
14
+ else:
15
+ TKINTER_LIB = tk.__file__
16
+ except AttributeError:
17
+ # _tkinter may be compiled directly into Python, in which case __file__ is
18
+ # not available. load_tkinter_funcs will check the binary first in any case.
19
+ TKINTER_LIB = None
20
+
21
+ tk_version = str(tkinter.TkVersion)
evalkit_tf437/lib/python3.10/site-packages/flash_attn/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (489 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/flash_attn/__pycache__/bert_padding.cpython-310.pyc ADDED
Binary file (6.94 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/flash_attn/__pycache__/fused_softmax.cpython-310.pyc ADDED
Binary file (5.76 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/flash_attn/losses/__init__.py ADDED
File without changes
evalkit_tf437/lib/python3.10/site-packages/flash_attn/losses/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (176 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/flash_attn/losses/__pycache__/cross_entropy.cpython-310.pyc ADDED
Binary file (2.75 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/flash_attn/losses/cross_entropy.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+ from flash_attn.ops.triton.cross_entropy import cross_entropy_loss
7
+
8
+
9
+ class CrossEntropyLoss(nn.Module):
10
+ def __init__(
11
+ self,
12
+ ignore_index=-100,
13
+ reduction="mean",
14
+ label_smoothing=0.0,
15
+ logit_scale=1.0,
16
+ lse_square_scale=0.0,
17
+ inplace_backward=False,
18
+ process_group=None,
19
+ return_z_loss=False,
20
+ ):
21
+ """
22
+ Arguments:
23
+ ignore_index: int. If labels == ignore_index, the loss is set to 0.0.
24
+ label_smoothing: float
25
+ lse_square_scale: float. If > 0, we add lse_square_scale * lse(logits) ^ 2 to the loss.
26
+ This is also referred to as "z-loss".
27
+ inplace_backward: bool. If True, we do the backward pass in-place by modifying the logits.
28
+ This saves memory.
29
+ process_group: if not None, we're doing Tensor Parallel: each process is responsible for
30
+ one part of the vocab. The loss will be aggregated across processes.
31
+ return_z_loss: bool. If True, we return the component of the loss contributed by
32
+ the lse_square_scale value. This value is only for logging and does not support
33
+ backprop.
34
+ """
35
+ super().__init__()
36
+ if reduction not in ["mean", "none", "sum"]:
37
+ raise NotImplementedError("Only support reduction = 'mean' or 'none' or 'sum'")
38
+ self.ignore_index = ignore_index
39
+ self.reduction = reduction
40
+ self.label_smoothing = label_smoothing
41
+ self.logit_scale = logit_scale
42
+ self.lse_square_scale = lse_square_scale
43
+ self.inplace_backward = inplace_backward
44
+ self.process_group = process_group
45
+ self.return_z_loss = return_z_loss
46
+
47
+ def forward(self, input, target):
48
+ """
49
+ Arguments:
50
+ input: (batch, vocab_size)
51
+ target: (batch,)
52
+ Returns:
53
+ losses: (batch,) if reduction is 'none', else (1,), dtype float
54
+ z_loss: (batch,) if reduction is 'none', else (1,), dtype float (if self.return_z_loss)
55
+ """
56
+ assert input.is_cuda and target.is_cuda, "Only support CUDA tensors"
57
+ loss, z_loss = cross_entropy_loss(
58
+ input,
59
+ target,
60
+ label_smoothing=self.label_smoothing,
61
+ logit_scale=self.logit_scale,
62
+ lse_square_scale=self.lse_square_scale,
63
+ ignore_index=self.ignore_index,
64
+ inplace_backward=self.inplace_backward,
65
+ process_group=self.process_group,
66
+ )
67
+ if self.reduction == "mean":
68
+ loss = loss.sum() / (target != self.ignore_index).sum()
69
+ elif self.reduction == "sum":
70
+ loss = loss.sum()
71
+ else:
72
+ loss = loss
73
+
74
+ if not self.return_z_loss:
75
+ return loss
76
+
77
+ if self.reduction == "mean":
78
+ z_loss = z_loss.sum() / (target != self.ignore_index).sum()
79
+ elif self.reduction == "sum":
80
+ z_loss = z_loss.sum()
81
+ else:
82
+ z_loss = z_loss
83
+
84
+ return loss, z_loss
evalkit_tf437/lib/python3.10/site-packages/flash_attn/models/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (176 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/flash_attn/models/__pycache__/baichuan.cpython-310.pyc ADDED
Binary file (4.56 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/flash_attn/models/__pycache__/bigcode.cpython-310.pyc ADDED
Binary file (7.1 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/flash_attn/models/__pycache__/btlm.cpython-310.pyc ADDED
Binary file (4.52 kB). View file