1
1
from __future__ import annotations
2
2
3
3
from pathlib import Path , PurePath
4
- from typing import Iterable , Mapping
4
+ from typing import Iterable , Mapping , Tuple , Union , Optional , List
5
5
6
- from PIL import Image
6
+ from PIL import Image as PILImageModule
7
+ from PIL .Image import Image
7
8
from PIL .Image import Resampling
8
9
from rich .console import Console , ConsoleOptions , RenderResult
9
10
from rich .segment import Segment , Segments
@@ -16,30 +17,30 @@ def __init__(self) -> None:
16
17
17
18
@staticmethod
18
19
def from_image (
19
- image : " Image" ,
20
+ image : Image ,
20
21
):
21
22
segments = Pixels ._segments_from_image (image )
22
23
return Pixels .from_segments (segments )
23
24
24
25
@staticmethod
25
26
def from_image_path (
26
- path : PurePath | str ,
27
- resize : tuple [ int , int ] | None = None ,
27
+ path : Union [ PurePath , str ] ,
28
+ resize : Optional [ Tuple [ int , int ]] = None ,
28
29
) -> Pixels :
29
30
"""Create a Pixels object from an image. Requires 'image' extra dependencies.
30
31
31
32
Args:
32
33
path: The path to the image file.
33
34
resize: A tuple of (width, height) to resize the image to.
34
35
"""
35
- with Image .open (Path (path )) as image :
36
+ with PILImageModule .open (Path (path )) as image :
36
37
segments = Pixels ._segments_from_image (image , resize )
37
38
38
39
return Pixels .from_segments (segments )
39
40
40
41
@staticmethod
41
42
def _segments_from_image (
42
- image : " Image" , resize : tuple [ int , int ] | None = None
43
+ image : Image , resize : Optional [ Tuple [ int , int ]] = None
43
44
) -> list [Segment ]:
44
45
if resize :
45
46
image = image .resize (resize , resample = Resampling .NEAREST )
@@ -52,7 +53,7 @@ def _segments_from_image(
52
53
segments = []
53
54
54
55
for y in range (height ):
55
- this_row = []
56
+ this_row : List [ Segment ] = []
56
57
row_append = this_row .append
57
58
58
59
for x in range (width ):
@@ -78,7 +79,9 @@ def from_segments(
78
79
return pixels
79
80
80
81
@staticmethod
81
- def from_ascii (grid : str , mapping : Mapping [str , Segment ] | None = None ) -> Pixels :
82
+ def from_ascii (
83
+ grid : str , mapping : Optional [Mapping [str , Segment ]] = None
84
+ ) -> Pixels :
82
85
"""
83
86
Create a Pixels object from a 2D-grid of ASCII characters.
84
87
Each ASCII character can be mapped to a Segment (a character and style combo),
@@ -108,7 +111,7 @@ def __rich_console__(
108
111
yield self ._segments or ""
109
112
110
113
111
- if __name__ == ' __main__' :
114
+ if __name__ == " __main__" :
112
115
console = Console ()
113
116
images_path = Path (__file__ ).parent / "../tests/.sample_data/images"
114
117
pixels = Pixels .from_image_path (images_path / "bulbasaur.png" )
0 commit comments