pixel-map 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pixel_map/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ __app_name__ = "pixel-map"
2
+ __version__ = "0.1.1"
pixel_map/__main__.py ADDED
@@ -0,0 +1,102 @@
1
+ """Main CLI module."""
2
+
3
+ from typing import Annotated, Optional, cast
4
+
5
+ import click
6
+ import typer
7
+
8
+ from pixel_map import __app_name__, __version__
9
+
10
+ app = typer.Typer(
11
+ context_settings={"help_option_names": ["-h", "--help"]}, rich_markup_mode="rich"
12
+ )
13
+
14
+ # TODO:
15
+ # - add option to select colours (pass list - must match number of files)
16
+ # - add option to select colours per type (polygon, linestring, point)
17
+ # (pass list(s) - must match number of files)
18
+ # - define default colour schemes with option to select
19
+ # --light (positron + blue)
20
+ # or --dark (darkmatter + orange?) [default]
21
+ # or --street (voyager + ???)
22
+ # - add option to select tileset (or no tileset) by name
23
+ # - add option to pass map height and width
24
+
25
+
26
+ def _version_callback(value: bool) -> None:
27
+ if value:
28
+ typer.echo(f"{__app_name__} {__version__}")
29
+ raise typer.Exit()
30
+
31
+
32
+ class BboxGeometryParser(click.ParamType): # type: ignore
33
+ """Parser for bounding boxes."""
34
+
35
+ name = "BBOX"
36
+
37
+ def convert(self, value, param=None, ctx=None): # type: ignore
38
+ """Convert parameter value."""
39
+ try:
40
+ bbox_values = tuple(float(x.strip()) for x in value.split(","))
41
+ if len(bbox_values) == 4:
42
+ return bbox_values
43
+ except ValueError: # ValueError raised when passing non-numbers to float()
44
+ pass
45
+
46
+ raise typer.BadParameter(
47
+ "Cannot parse provided bounding box."
48
+ " Valid value must contain 4 floating point numbers"
49
+ " separated by commas."
50
+ ) from None
51
+
52
+
53
+ @app.command() # type: ignore
54
+ def plot(
55
+ files: Annotated[
56
+ list[str],
57
+ typer.Argument(
58
+ help="List of files to display. Those could be any that can be opened by GeoPandas.",
59
+ show_default=False,
60
+ ),
61
+ ],
62
+ bbox: Annotated[
63
+ Optional[str],
64
+ typer.Option(
65
+ help=(
66
+ "Clip the map to a given [bold dark_orange]bounding box[/bold dark_orange]."
67
+ " Expects 4 floating point numbers separated by commas."
68
+ ),
69
+ click_type=BboxGeometryParser(),
70
+ show_default=False,
71
+ ),
72
+ ] = None,
73
+ version: Annotated[
74
+ Optional[bool],
75
+ typer.Option(
76
+ "--version",
77
+ "-v",
78
+ help="Show the application's version and exit.",
79
+ callback=_version_callback,
80
+ is_eager=True,
81
+ ),
82
+ ] = None,
83
+ ) -> None:
84
+ """Plot the geodata in the terminal."""
85
+ import warnings
86
+
87
+ from pixel_map.plotter import plot_geo_data
88
+
89
+ with warnings.catch_warnings():
90
+ warnings.filterwarnings("ignore")
91
+ plot_geo_data(
92
+ files, bbox=cast(Optional[tuple[float, float, float, float]], bbox)
93
+ )
94
+
95
+
96
+ def main() -> None:
97
+ """Run the CLI."""
98
+ app(prog_name=__app_name__) # pragma: no cover
99
+
100
+
101
+ if __name__ == "__main__":
102
+ app(prog_name=__app_name__) # pragma: no cover
pixel_map/plotter.py ADDED
@@ -0,0 +1,262 @@
1
+ """
2
+ Plotting functionality.
3
+
4
+ Generates a Matplotlib canvas that is rendered to an image and later transformed into a list of
5
+ unicode characters.
6
+ """
7
+
8
+ from pathlib import Path
9
+ from typing import Any, Optional
10
+
11
+ import contextily as cx
12
+ import geopandas as gpd
13
+ import img2unicode
14
+ import numpy as np
15
+ from matplotlib import pyplot as plt
16
+ from matplotlib.axes import Axes
17
+ from pyproj import Transformer
18
+ from pyproj.enums import TransformDirection
19
+ from rich import get_console
20
+ from rich.box import HEAVY
21
+ from rich.panel import Panel
22
+ from rich.progress import Progress, SpinnerColumn, TextColumn
23
+
24
+ TRANSFORMER = Transformer.from_crs("EPSG:4326", "EPSG:3857", always_xy=True)
25
+
26
+
27
+ def plot_geo_data(
28
+ files: list[str], bbox: Optional[tuple[float, float, float, float]] = None
29
+ ) -> None:
30
+ """
31
+ Plot a geo data into a terminal.
32
+
33
+ Generates a Matplotlib canvas that is rendered to an image and later transformed into a list of
34
+ unicode characters.
35
+
36
+ Args:
37
+ files (list[str]): List of files to plot.
38
+ bbox (Optional[tuple[float, float, float, float]], optional): Bounding box used to clip the
39
+ geo data. Defaults to None.
40
+ """
41
+ console = get_console()
42
+
43
+ # terminal_width = console.width
44
+ # terminal_height = console.height - 1
45
+
46
+ terminal_width = console.width - 2
47
+ terminal_height = console.height - 3
48
+
49
+ map_width = terminal_width
50
+ map_height = terminal_height * 2
51
+
52
+ map_ratio = map_width / map_height
53
+
54
+ with Progress(
55
+ SpinnerColumn(),
56
+ TextColumn("[progress.description]{task.description}"),
57
+ transient=True,
58
+ console=console,
59
+ ) as progress:
60
+ progress.add_task("Calculating bounding box", total=None)
61
+ bbox_axes_bounds = None
62
+ if bbox:
63
+ bbox, bbox_axes_bounds = _expand_bbox_to_match_ratio(bbox, ratio=map_ratio)
64
+
65
+ with Progress(
66
+ SpinnerColumn(),
67
+ TextColumn("[progress.description]{task.description}"),
68
+ transient=True,
69
+ console=console,
70
+ ) as progress:
71
+ progress.add_task("Loading Geo data", total=None)
72
+ gdf = _load_geo_data(files, bbox=bbox)
73
+ if bbox:
74
+ gdf = gdf.clip_by_rect(*bbox)
75
+
76
+ with Progress(
77
+ SpinnerColumn(),
78
+ TextColumn("[progress.description]{task.description}"),
79
+ transient=True,
80
+ console=console,
81
+ ) as progress:
82
+ progress.add_task("Plotting geo data", total=None)
83
+ f, ax = plt.subplots(figsize=(map_width, map_height), dpi=10)
84
+ f.patch.set_facecolor("black")
85
+ canvas = f.canvas
86
+ # gdf.to_crs(3857).plot(ax=ax, alpha=0.4)
87
+ gdf.to_crs(3857).plot(ax=ax)
88
+ ax.axis("off")
89
+ ax.margins(0)
90
+
91
+ if bbox_axes_bounds:
92
+ left, bottom, right, top = bbox_axes_bounds
93
+ ax.set_xlim([left, right])
94
+ ax.set_ylim([bottom, top])
95
+
96
+ left, bottom, right, top = _expand_axes_limit_to_match_ratio(ax, ratio=map_ratio)
97
+ # cx.add_basemap(
98
+ # ax,
99
+ # source=cx.providers.CartoDB.PositronNoLabels,
100
+ # crs=3857,
101
+ # attribution=False,
102
+ # )
103
+ cx.add_basemap(
104
+ ax,
105
+ source=cx.providers.CartoDB.DarkMatterNoLabels,
106
+ crs=3857,
107
+ attribution=False,
108
+ )
109
+ # cx.add_basemap(
110
+ # ax,
111
+ # source=cx.providers.CartoDB.VoyagerNoLabels,
112
+ # crs=3857,
113
+ # attribution=False,
114
+ # )
115
+ f.tight_layout()
116
+ canvas.draw()
117
+ image_flat = np.frombuffer(canvas.tostring_rgb(), dtype="uint8") # (H * W * 3,)
118
+ image = image_flat.reshape(*reversed(canvas.get_width_height()), 3)
119
+
120
+ with Progress(
121
+ SpinnerColumn(),
122
+ TextColumn("[progress.description]{task.description}"),
123
+ transient=True,
124
+ console=console,
125
+ ) as progress:
126
+ progress.add_task("Rendering geo data", total=None)
127
+ fast_renderer = img2unicode.Renderer(
128
+ # img2unicode.FastGenericDualOptimizer(),
129
+ # img2unicode.ExactGenericDualOptimizer("block"),
130
+ # img2unicode.FastQuadDualOptimizer(),
131
+ img2unicode.FastGenericDualOptimizer("block"),
132
+ # img2unicode.ExactGammaOptimizer("no_block"),
133
+ max_h=terminal_height,
134
+ max_w=terminal_width,
135
+ allow_upscale=True,
136
+ )
137
+ characters, foreground_colors, background_colors = fast_renderer.render_numpy(image)
138
+ # braille_renderer = img2unicode.GammaRenderer(
139
+ # img2unicode.BestGammaOptimizer(True, "braille"),
140
+ # max_h=terminal_height,
141
+ # max_w=terminal_width,
142
+ # allow_upscale=True,
143
+ # )
144
+ # characters, foreground_colors, background_colors = braille_renderer.render_numpy(image)
145
+ full_rich_string = _construct_full_rich_string(
146
+ characters, foreground_colors, background_colors
147
+ )
148
+ # with Live(console=console, auto_refresh=False, screen=True, transient=False) as live:
149
+ # # my_console.print("[bold blue]Starting work!")
150
+ map_minx, map_miny = TRANSFORMER.transform(left, bottom, direction=TransformDirection.INVERSE)
151
+ map_maxx, map_maxy = TRANSFORMER.transform(right, top, direction=TransformDirection.INVERSE)
152
+ file_paths = [Path(f).name for f in files]
153
+ title = file_paths[0]
154
+
155
+ if len(file_paths) == 2:
156
+ title = f"{file_paths[0]} + 1 other file"
157
+ elif len(file_paths) > 2:
158
+ title = f"{file_paths[0]} + {len(file_paths) - 1} other files"
159
+
160
+ console.print(
161
+ Panel(
162
+ full_rich_string,
163
+ padding=0,
164
+ title=title,
165
+ subtitle=f"BBOX: {map_minx:.5f},{map_miny:.5f},{map_maxx:.5f},{map_maxy:.5f}",
166
+ box=HEAVY,
167
+ )
168
+ )
169
+ # console.print(full_rich_string)
170
+
171
+
172
+ def _load_geo_data(
173
+ files: list[str], bbox: Optional[tuple[float, float, float, float]] = None
174
+ ) -> gpd.GeoSeries:
175
+ paths = [Path(file_path) for file_path in files]
176
+ return gpd.pd.concat(
177
+ [
178
+ (
179
+ _read_geoparquet_file(path, bbox=bbox).geometry
180
+ if path.suffix == ".parquet"
181
+ else gpd.read_file(path, bbox=bbox).geometry
182
+ )
183
+ for path in paths
184
+ ]
185
+ )
186
+
187
+
188
+ def _read_geoparquet_file(
189
+ path: Path, bbox: Optional[tuple[float, float, float, float]] = None
190
+ ) -> gpd.GeoDataFrame:
191
+ try:
192
+ return gpd.read_parquet(path, bbox=bbox)
193
+ except Exception:
194
+ return gpd.read_parquet(path)
195
+
196
+
197
+ def _expand_bbox_to_match_ratio(
198
+ bbox: tuple[float, float, float, float], ratio: float
199
+ ) -> tuple[tuple[float, float, float, float], tuple[float, float, float, float]]:
200
+ minx, miny, maxx, maxy = bbox
201
+
202
+ left, bottom = TRANSFORMER.transform(minx, miny)
203
+ right, top = TRANSFORMER.transform(maxx, maxy)
204
+
205
+ width = right - left
206
+ height = top - bottom
207
+ current_ratio = width / height
208
+ if current_ratio < ratio:
209
+ new_width = (ratio / current_ratio) * width
210
+ width_padding = (new_width - width) / 2
211
+ left = left - width_padding
212
+ right = right + width_padding
213
+ else:
214
+ new_height = (current_ratio / ratio) * height
215
+ height_padding = (new_height - height) / 2
216
+ bottom = bottom - height_padding
217
+ top = top + height_padding
218
+
219
+ new_minx, new_miny = TRANSFORMER.transform(left, bottom, direction=TransformDirection.INVERSE)
220
+ new_maxx, new_maxy = TRANSFORMER.transform(right, top, direction=TransformDirection.INVERSE)
221
+
222
+ return (new_minx, new_miny, new_maxx, new_maxy), (left, bottom, right, top)
223
+
224
+
225
+ def _expand_axes_limit_to_match_ratio(ax: Axes, ratio: float) -> tuple[float, float, float, float]:
226
+ left, right = ax.get_xlim()
227
+ bottom, top = ax.get_ylim()
228
+ width = right - left
229
+ height = top - bottom
230
+ current_ratio = width / height
231
+ if current_ratio < ratio:
232
+ new_width = (ratio / current_ratio) * width
233
+ width_padding = (new_width - width) / 2
234
+ left = left - width_padding
235
+ right = right + width_padding
236
+ ax.set_xlim([left, right])
237
+ else:
238
+ new_height = (current_ratio / ratio) * height
239
+ height_padding = (new_height - height) / 2
240
+ bottom = bottom - height_padding
241
+ top = top + height_padding
242
+ ax.set_ylim([bottom, top])
243
+
244
+ return left, bottom, right, top
245
+
246
+
247
+ def _construct_full_rich_string(
248
+ characters: Any, foreground_colors: Any, background_colors: Any
249
+ ) -> str:
250
+ result = ""
251
+ for y in range(characters.shape[0]):
252
+ for x in range(characters.shape[1]):
253
+ idx = y, x
254
+ res = characters[idx]
255
+ char = chr(res)
256
+ fg_color = ",".join(map(str, foreground_colors[idx]))
257
+ bg_color = ",".join(map(str, background_colors[idx]))
258
+ result += (
259
+ f"[rgb({fg_color}) ON rgb({bg_color})]{char}[/rgb({fg_color}) ON rgb({bg_color})]"
260
+ )
261
+ result += "\n"
262
+ return result[:-1]
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.1
2
+ Name: pixel-map
3
+ Version: 0.1.1
4
+ Summary: A Python CLI tool for plotting geo files in the terminal
5
+ Author-Email: Kamil Raczycki <kraczycki@kraina.ai>
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Requires-Dist: rich>=12.0.0
9
+ Requires-Dist: typer[all]>=0.9.0
10
+ Requires-Dist: img2unicode[n2]>=0.1a11; sys_platform != "win32"
11
+ Requires-Dist: img2unicode>=0.1a11; sys_platform == "win32"
12
+ Requires-Dist: geopandas>=0.6
13
+ Requires-Dist: numpy>=1.26.0
14
+ Requires-Dist: shapely>=2
15
+ Requires-Dist: contextily
16
+ Requires-Dist: matplotlib
17
+ Requires-Dist: pillow
18
+ Requires-Dist: pyarrow>=16.0.0
19
+ Description-Content-Type: text/markdown
20
+
21
+ # pixel-map
@@ -0,0 +1,8 @@
1
+ pixel_map-0.1.1.dist-info/METADATA,sha256=LurkEUwjJsVmQ08f2Dej9yO7Zir5GEKr8ubX2Z3x6jo,634
2
+ pixel_map-0.1.1.dist-info/WHEEL,sha256=pM0IBB6ZwH3nkEPhtcp50KvKNX-07jYtnb1g1m6Z4Co,90
3
+ pixel_map-0.1.1.dist-info/entry_points.txt,sha256=NVQKj1QQWDeX-QWDB7ZF1e9ZvLt0wdnGQJNKLtdtASE,70
4
+ pixel_map-0.1.1.dist-info/licenses/LICENSE,sha256=ArLZ5TTwQWp7UQ1_EUe_9DI3U6W0-ismyPttIVVBopA,1071
5
+ pixel_map/__init__.py,sha256=suddPsmn_A758q380R1YjZNJlE6Cq1FixHCDNR7oXYw,48
6
+ pixel_map/__main__.py,sha256=0kRRulWTqBkwpOCSDIShcIT57wr9I4OSlN3NA3PW_pw,2949
7
+ pixel_map/plotter.py,sha256=Ax1X9_B08E5Rztk1kLcFb-UwexFp-In5sVa26AAdUDY,8906
8
+ pixel_map-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: pdm-backend (2.4.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,5 @@
1
+ [console_scripts]
2
+ pixel-map = pixel_map.__main__:main
3
+
4
+ [gui_scripts]
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Kamil Raczycki
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.