pixel-map 0.1.1__tar.gz → 0.2.0__tar.gz

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.
@@ -1,20 +1,18 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pixel-map
3
- Version: 0.1.1
3
+ Version: 0.2.0
4
4
  Summary: A Python CLI tool for plotting geo files in the terminal
5
5
  Author-Email: Kamil Raczycki <kraczycki@kraina.ai>
6
6
  License: MIT
7
7
  Requires-Python: >=3.9
8
8
  Requires-Dist: rich>=12.0.0
9
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"
10
+ Requires-Dist: img2unicode[n2]>=0.1a11; sys_platform != "win32" and sys_platform != "darwin"
11
+ Requires-Dist: img2unicode>=0.1a11; sys_platform == "win32" or sys_platform == "darwin"
12
12
  Requires-Dist: geopandas>=0.6
13
13
  Requires-Dist: numpy>=1.26.0
14
- Requires-Dist: shapely>=2
15
- Requires-Dist: contextily
16
- Requires-Dist: matplotlib
17
- Requires-Dist: pillow
14
+ Requires-Dist: contextily>=1
15
+ Requires-Dist: matplotlib>=3.2.0
18
16
  Requires-Dist: pyarrow>=16.0.0
19
17
  Description-Content-Type: text/markdown
20
18
 
@@ -0,0 +1,4 @@
1
+ """Pixel-map library."""
2
+
3
+ __app_name__ = "pixel-map"
4
+ __version__ = "0.2.0"
@@ -0,0 +1,307 @@
1
+ """Main CLI module."""
2
+
3
+ from contextlib import suppress
4
+ from typing import Annotated, Optional, cast
5
+
6
+ import click
7
+ import typer
8
+
9
+ from pixel_map import __app_name__, __version__
10
+ from pixel_map.renderers import AVAILABLE_RENDERERS
11
+
12
+ renderer_help_string = ", ".join(
13
+ f"[bold dark_orange]{renderer}[/bold dark_orange]"
14
+ for renderer in sorted(AVAILABLE_RENDERERS.keys())
15
+ )
16
+ VALID_EXAMPLE_FILES = ["london_buildings", "london_park", "london_water", "monaco_buildings"]
17
+ example_files_help_string = ", ".join(
18
+ f"[bold dark_orange]{example}[/bold dark_orange]" for example in sorted(VALID_EXAMPLE_FILES)
19
+ )
20
+
21
+ app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]}, rich_markup_mode="rich")
22
+
23
+ # TODO:
24
+ # - add option to select colours (pass list - must match number of files)
25
+ # - add option to select colours per type (polygon, linestring, point)
26
+ # (pass list(s) - must match number of files)
27
+ # - define default colour schemes with option to select
28
+ # --light (positron + blue)
29
+ # or --dark (darkmatter + orange?) [default]
30
+ # or --street (voyager + ???)
31
+ # - add option to select tileset (or no tileset) by name
32
+ # - add option to pass map height and width
33
+ # - add option to remove the panel (border)
34
+
35
+
36
+ def _version_callback(value: bool) -> None:
37
+ if value:
38
+ typer.echo(f"{__app_name__} {__version__}")
39
+ raise typer.Exit()
40
+
41
+
42
+ class BboxParser(click.ParamType): # type: ignore
43
+ """Parser for bounding boxes."""
44
+
45
+ name = "BBOX"
46
+
47
+ def convert(self, value, param=None, ctx=None): # type: ignore
48
+ """Convert parameter value."""
49
+ with suppress(ValueError): # ValueError raised when passing non-numbers to float()
50
+ bbox_values = tuple(float(x.strip()) for x in value.split(","))
51
+ if len(bbox_values) == 4:
52
+ return bbox_values
53
+
54
+ raise typer.BadParameter(
55
+ "Cannot parse provided bounding box."
56
+ " Valid value must contain 4 floating point numbers"
57
+ " separated by commas."
58
+ ) from None
59
+
60
+
61
+ class ColorParser(click.ParamType): # type: ignore
62
+ """Parser for colours."""
63
+
64
+ name = "COLOR"
65
+
66
+ def convert(self, value, param=None, ctx=None): # type: ignore
67
+ """Convert parameter value."""
68
+ with suppress(ValueError): # ValueError raised when passing non-numbers to float()
69
+ colors = [x.strip() for x in value.split(",")]
70
+ return colors
71
+
72
+
73
+ class AlphaParser(click.ParamType): # type: ignore
74
+ """Parser for bounding boxes."""
75
+
76
+ name = "FLOAT"
77
+
78
+ def convert(self, value, param=None, ctx=None): # type: ignore
79
+ """Convert parameter value."""
80
+ with suppress(ValueError): # ValueError raised when passing non-numbers to float()
81
+ alpha_values = [float(x.strip()) for x in value.split(",")]
82
+ return alpha_values
83
+
84
+ raise typer.BadParameter(
85
+ "Cannot parse provided alpha values."
86
+ " Valid value must contain floating point numbers"
87
+ " separated by commas."
88
+ ) from None
89
+
90
+
91
+ @app.command() # type: ignore
92
+ def plot(
93
+ files: Annotated[
94
+ list[str],
95
+ typer.Argument(
96
+ help="List of files to display. Those could be any that can be opened by GeoPandas.",
97
+ show_default=False,
98
+ ),
99
+ ],
100
+ bbox: Annotated[
101
+ Optional[str],
102
+ typer.Option(
103
+ "--bbox",
104
+ "-b",
105
+ help=(
106
+ "Clip the map to a given [bold dark_orange]bounding box[/bold dark_orange]."
107
+ " Expects 4 floating point numbers separated by commas."
108
+ ),
109
+ click_type=BboxParser(),
110
+ show_default=False,
111
+ ),
112
+ ] = None,
113
+ renderer: Annotated[
114
+ str,
115
+ typer.Option(
116
+ "--renderer",
117
+ "-r",
118
+ help=(
119
+ "Renderer used for generating terminal output."
120
+ f" Possible values: {renderer_help_string}."
121
+ ),
122
+ case_sensitive=False,
123
+ show_default="block",
124
+ is_eager=True,
125
+ ),
126
+ ] = "block",
127
+ is_dark_style: Annotated[
128
+ bool,
129
+ typer.Option(
130
+ "--dark/--light",
131
+ help=(
132
+ "Uses the predefined dark or light style. Can be overriden with user defined style."
133
+ ),
134
+ show_default=True,
135
+ ),
136
+ ] = True,
137
+ colors: Annotated[
138
+ Optional[str],
139
+ typer.Option(
140
+ "--color",
141
+ "-c",
142
+ help=("Pass color or list of colours per each geo file."),
143
+ click_type=ColorParser(),
144
+ show_default=False,
145
+ ),
146
+ ] = None,
147
+ alphas: Annotated[
148
+ Optional[str],
149
+ typer.Option(
150
+ "--alpha",
151
+ "--opacity",
152
+ "-a",
153
+ help=("Pass opacity or list of opacities per each geo file."),
154
+ click_type=AlphaParser(),
155
+ show_default=False,
156
+ ),
157
+ ] = None,
158
+ basemap_provider: Annotated[
159
+ Optional[str],
160
+ typer.Option(
161
+ "--basemap",
162
+ "--tileset",
163
+ "-t",
164
+ metavar="TILES",
165
+ help=(
166
+ "Set the basemap provider. Can be any value parsed by xyzservices library."
167
+ " Defaults to [bold dark_orange]CartoDB.DarkMatterNoLabels[/bold dark_orange]"
168
+ " if --dark or [bold dark_orange]CartoDB.PositronNoLabels[/bold dark_orange]"
169
+ " if --light."
170
+ ),
171
+ show_default=False,
172
+ ),
173
+ ] = None,
174
+ no_border: Annotated[
175
+ bool,
176
+ typer.Option(
177
+ "--no-border/",
178
+ "--fullscreen/",
179
+ "-f/",
180
+ help=("Removes the border around the map."),
181
+ show_default=False,
182
+ ),
183
+ ] = False,
184
+ no_background: Annotated[
185
+ bool,
186
+ typer.Option(
187
+ "--no-background/",
188
+ "--no-bg/",
189
+ help=("Removes the background of the map and plots only geo data."),
190
+ show_default=False,
191
+ ),
192
+ ] = False,
193
+ background_color: Annotated[
194
+ Optional[str],
195
+ typer.Option(
196
+ "--background-color",
197
+ "--bg-color",
198
+ metavar="COLOR",
199
+ help=("Set the background color. Can be used together with --no-background."),
200
+ show_default=False,
201
+ ),
202
+ ] = None,
203
+ example_files: Annotated[
204
+ bool,
205
+ typer.Option(
206
+ "--example/",
207
+ "--example-files/",
208
+ help=(
209
+ "Can be used to load one of example files based on name."
210
+ f" Possible values: {example_files_help_string}."
211
+ ),
212
+ show_default=False,
213
+ ),
214
+ ] = False,
215
+ version: Annotated[
216
+ Optional[bool],
217
+ typer.Option(
218
+ "--version",
219
+ "-v",
220
+ help="Show the application's version and exit.",
221
+ callback=_version_callback,
222
+ is_eager=True,
223
+ ),
224
+ ] = None,
225
+ ) -> None:
226
+ """
227
+ Plot the geo data into a terminal.
228
+
229
+ Generates a Matplotlib canvas that is rendered to an image and later transformed into a list of
230
+ unicode characters.
231
+ """
232
+ import warnings
233
+
234
+ from pixel_map.plotter import (
235
+ get_predefined_dark_style,
236
+ get_predefined_light_style,
237
+ plot_geo_data,
238
+ )
239
+
240
+ if renderer not in AVAILABLE_RENDERERS:
241
+ raise typer.BadParameter(f"Provided renderer {renderer} doesn't exist.") from None
242
+
243
+ if example_files:
244
+ from pathlib import Path
245
+
246
+ loaded_example_files = []
247
+ for file_name in files:
248
+ if file_name not in VALID_EXAMPLE_FILES:
249
+ raise typer.BadParameter(
250
+ f"Provided file {file_name} doesn't exist in examples."
251
+ ) from None
252
+ loaded_example_files.append(
253
+ (Path(__file__).parent / "example_files" / f"{file_name}.parquet").as_posix()
254
+ )
255
+ files = loaded_example_files
256
+
257
+ if is_dark_style:
258
+ provider, color = get_predefined_dark_style()
259
+ else:
260
+ provider, color = get_predefined_light_style()
261
+
262
+ if not basemap_provider:
263
+ basemap_provider = provider
264
+
265
+ parsed_colors: Optional[list[str]] = colors # type: ignore[assignment]
266
+ if not parsed_colors:
267
+ parsed_colors = [color]
268
+
269
+ parsed_alphas: Optional[list[float]] = alphas # type: ignore[assignment]
270
+ if not parsed_alphas:
271
+ parsed_alphas = [1]
272
+
273
+ if len(parsed_colors) > 1 and len(parsed_colors) != len(files):
274
+ raise typer.BadParameter(
275
+ f"Number of colors ({len(parsed_colors)}) and geo files ({len(files)}) doesn't match."
276
+ ) from None
277
+
278
+ if len(parsed_alphas) > 1 and len(parsed_alphas) != len(files):
279
+ raise typer.BadParameter(
280
+ f"Number of alphas ({len(parsed_alphas)}) and geo files ({len(files)}) doesn't match."
281
+ ) from None
282
+
283
+ if no_background:
284
+ basemap_provider = None
285
+ background_color = background_color or ("black" if is_dark_style else "white")
286
+
287
+ with warnings.catch_warnings():
288
+ warnings.filterwarnings("ignore")
289
+ plot_geo_data(
290
+ files,
291
+ renderer=renderer,
292
+ bbox=cast(Optional[tuple[float, float, float, float]], bbox),
293
+ color=parsed_colors,
294
+ alpha=parsed_alphas,
295
+ basemap_provider=basemap_provider,
296
+ background_color=background_color or "black",
297
+ no_border=no_border,
298
+ )
299
+
300
+
301
+ def main() -> None:
302
+ """Run the CLI."""
303
+ app(prog_name=__app_name__) # pragma: no cover
304
+
305
+
306
+ if __name__ == "__main__":
307
+ app(prog_name=__app_name__) # pragma: no cover
@@ -6,11 +6,10 @@ unicode characters.
6
6
  """
7
7
 
8
8
  from pathlib import Path
9
- from typing import Any, Optional
9
+ from typing import Any, Optional, Union
10
10
 
11
11
  import contextily as cx
12
12
  import geopandas as gpd
13
- import img2unicode
14
13
  import numpy as np
15
14
  from matplotlib import pyplot as plt
16
15
  from matplotlib.axes import Axes
@@ -18,33 +17,57 @@ from pyproj import Transformer
18
17
  from pyproj.enums import TransformDirection
19
18
  from rich import get_console
20
19
  from rich.box import HEAVY
20
+ from rich.color import Color
21
21
  from rich.panel import Panel
22
22
  from rich.progress import Progress, SpinnerColumn, TextColumn
23
+ from rich.style import Style
24
+ from rich.text import Text
25
+
26
+ from pixel_map.renderers import AVAILABLE_RENDERERS
23
27
 
24
28
  TRANSFORMER = Transformer.from_crs("EPSG:4326", "EPSG:3857", always_xy=True)
25
29
 
26
30
 
27
31
  def plot_geo_data(
28
- files: list[str], bbox: Optional[tuple[float, float, float, float]] = None
32
+ files: list[str],
33
+ renderer: str,
34
+ bbox: Optional[tuple[float, float, float, float]] = None,
35
+ color: Union[str, list[str]] = "C0",
36
+ alpha: Union[float, list[float]] = 1.0,
37
+ basemap_provider: Optional[str] = None,
38
+ background_color: Optional[str] = None,
39
+ no_border: bool = False,
29
40
  ) -> None:
30
41
  """
31
- Plot a geo data into a terminal.
42
+ Plot the geo data into a terminal.
32
43
 
33
44
  Generates a Matplotlib canvas that is rendered to an image and later transformed into a list of
34
45
  unicode characters.
35
46
 
36
47
  Args:
37
48
  files (list[str]): List of files to plot.
49
+ renderer (str): A name for the renderer used to generate terminal output.
50
+ Defaults to "block".
38
51
  bbox (Optional[tuple[float, float, float, float]], optional): Bounding box used to clip the
39
52
  geo data. Defaults to None.
53
+ color (Union[str, list[str]], optional): Color or list of colors used to plot geo data.
54
+ If a list, must be the same length as a number of files. Defaults to "C0".
55
+ alpha (Union[str, list[float]], optional): Opacity or list of opacities used to plot
56
+ geo data. If a list, must be the same length as a number of files. Defaults to 1.
57
+ basemap_provider (str, optional): A basemap used to plot under the geo data.
58
+ Defaults to None.
59
+ background_color (str, optional): Background color. Used then basemap_provider is None.
60
+ Defaults to None.
61
+ no_border (bool, optional): Removes the border around the map. Defaults to False.
40
62
  """
41
63
  console = get_console()
42
64
 
43
- # terminal_width = console.width
44
- # terminal_height = console.height - 1
45
-
46
- terminal_width = console.width - 2
47
- terminal_height = console.height - 3
65
+ if no_border:
66
+ terminal_width = console.width
67
+ terminal_height = console.height - 1
68
+ else:
69
+ terminal_width = console.width - 2
70
+ terminal_height = console.height - 3 # 2 for panel and 1 for new line
48
71
 
49
72
  map_width = terminal_width
50
73
  map_height = terminal_height * 2
@@ -69,9 +92,9 @@ def plot_geo_data(
69
92
  console=console,
70
93
  ) as progress:
71
94
  progress.add_task("Loading Geo data", total=None)
72
- gdf = _load_geo_data(files, bbox=bbox)
95
+ gdfs = _load_geo_data(files, bbox=bbox)
73
96
  if bbox:
74
- gdf = gdf.clip_by_rect(*bbox)
97
+ gdfs = [gdf.clip_by_rect(*bbox) for gdf in gdfs]
75
98
 
76
99
  with Progress(
77
100
  SpinnerColumn(),
@@ -81,12 +104,18 @@ def plot_geo_data(
81
104
  ) as progress:
82
105
  progress.add_task("Plotting geo data", total=None)
83
106
  f, ax = plt.subplots(figsize=(map_width, map_height), dpi=10)
84
- f.patch.set_facecolor("black")
107
+ f.patch.set_facecolor(background_color)
85
108
  canvas = f.canvas
86
109
  # gdf.to_crs(3857).plot(ax=ax, alpha=0.4)
87
- gdf.to_crs(3857).plot(ax=ax)
110
+ if isinstance(color, str):
111
+ color = [color]
112
+ if isinstance(alpha, (int, float)):
113
+ alpha = [alpha]
114
+ for idx, gdf in enumerate(gdfs):
115
+ plot_color = color[idx % len(color)]
116
+ plot_alpha = alpha[idx % len(alpha)]
117
+ gdf.to_crs(3857).plot(ax=ax, color=plot_color, alpha=plot_alpha)
88
118
  ax.axis("off")
89
- ax.margins(0)
90
119
 
91
120
  if bbox_axes_bounds:
92
121
  left, bottom, right, top = bbox_axes_bounds
@@ -94,25 +123,16 @@ def plot_geo_data(
94
123
  ax.set_ylim([bottom, top])
95
124
 
96
125
  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()
126
+
127
+ if basemap_provider:
128
+ cx.add_basemap(
129
+ ax,
130
+ source=basemap_provider,
131
+ crs=3857,
132
+ attribution=False,
133
+ )
134
+
135
+ ax.set_position((0, 0, 1, 1))
116
136
  canvas.draw()
117
137
  image_flat = np.frombuffer(canvas.tostring_rgb(), dtype="uint8") # (H * W * 3,)
118
138
  image = image_flat.reshape(*reversed(canvas.get_width_height()), 3)
@@ -124,65 +144,60 @@ def plot_geo_data(
124
144
  console=console,
125
145
  ) as progress:
126
146
  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,
147
+ renderer_object = AVAILABLE_RENDERERS[renderer](
148
+ terminal_width=terminal_width, terminal_height=terminal_height
136
149
  )
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)
150
+ characters, foreground_colors, background_colors = renderer_object.render_numpy(image)
145
151
  full_rich_string = _construct_full_rich_string(
146
152
  characters, foreground_colors, background_colors
147
153
  )
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,
154
+
155
+ if no_border:
156
+ console.print(full_rich_string)
157
+ else:
158
+ title = _generate_panel_title(files, terminal_width)
159
+
160
+ map_minx, map_miny = TRANSFORMER.transform(
161
+ left, bottom, direction=TransformDirection.INVERSE
162
+ )
163
+ map_maxx, map_maxy = TRANSFORMER.transform(right, top, direction=TransformDirection.INVERSE)
164
+ subtitle = _generate_panel_subtitle(
165
+ map_minx, map_miny, map_maxx, map_maxy, terminal_width, terminal_height
167
166
  )
168
- )
169
- # console.print(full_rich_string)
167
+
168
+ console.print(
169
+ Panel.fit(
170
+ full_rich_string,
171
+ padding=0,
172
+ title=title,
173
+ subtitle=subtitle,
174
+ box=HEAVY,
175
+ )
176
+ )
177
+
178
+
179
+ def get_predefined_dark_style() -> tuple[str, str]:
180
+ """Get default background and color for dark style."""
181
+ return "CartoDB.DarkMatterNoLabels", "C1"
182
+
183
+
184
+ def get_predefined_light_style() -> tuple[str, str]:
185
+ """Get default background and color for light style."""
186
+ return "CartoDB.PositronNoLabels", "C0"
170
187
 
171
188
 
172
189
  def _load_geo_data(
173
190
  files: list[str], bbox: Optional[tuple[float, float, float, float]] = None
174
- ) -> gpd.GeoSeries:
191
+ ) -> list[gpd.GeoSeries]:
175
192
  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
- )
193
+ return [
194
+ (
195
+ _read_geoparquet_file(path, bbox=bbox).geometry
196
+ if path.suffix == ".parquet"
197
+ else gpd.read_file(path, bbox=bbox).geometry
198
+ )
199
+ for path in paths
200
+ ]
186
201
 
187
202
 
188
203
  def _read_geoparquet_file(
@@ -246,17 +261,66 @@ def _expand_axes_limit_to_match_ratio(ax: Axes, ratio: float) -> tuple[float, fl
246
261
 
247
262
  def _construct_full_rich_string(
248
263
  characters: Any, foreground_colors: Any, background_colors: Any
249
- ) -> str:
250
- result = ""
264
+ ) -> Text:
265
+ has_fg_color = foreground_colors is not None
266
+ has_bg_color = background_colors is not None
267
+ result = Text()
251
268
  for y in range(characters.shape[0]):
252
269
  for x in range(characters.shape[1]):
253
270
  idx = y, x
254
271
  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})]"
272
+ result.append(
273
+ chr(res),
274
+ style=Style(
275
+ color=(Color.from_rgb(*foreground_colors[idx]) if has_fg_color else None),
276
+ bgcolor=(Color.from_rgb(*background_colors[idx]) if has_bg_color else None),
277
+ ),
260
278
  )
261
- result += "\n"
279
+ result.append("\n")
262
280
  return result[:-1]
281
+
282
+
283
+ def _generate_panel_title(files: list[str], terminal_width: int) -> str:
284
+ file_paths = [Path(f).name for f in files]
285
+
286
+ if len(file_paths) == 1:
287
+ title = "1 file"
288
+ else:
289
+ title = f"{len(file_paths)} files"
290
+
291
+ file_names_in_title = []
292
+ file_names_left = file_paths
293
+ while file_names_left:
294
+ current_file_name = file_names_left.pop(0)
295
+ file_names_in_title.append(current_file_name)
296
+ titles_joined = ", ".join(file_names_in_title)
297
+ titles_left = len(file_names_left)
298
+ if titles_left == 0:
299
+ new_title = titles_joined
300
+ elif titles_left == 1:
301
+ new_title = f"{titles_joined} + 1 other file"
302
+ else:
303
+ new_title = f"{titles_joined} + {titles_left} other files"
304
+
305
+ if len(new_title) > (terminal_width - 4):
306
+ break
307
+
308
+ title = new_title
309
+
310
+ return title
311
+
312
+
313
+ def _generate_panel_subtitle(
314
+ minx: float, miny: float, maxx: float, maxy: float, terminal_width: int, terminal_height: int
315
+ ) -> str:
316
+ bbox_str = f"BBOX: {minx:.5f},{miny:.5f},{maxx:.5f},{maxy:.5f}"
317
+ terminal_wh_str = f"MAP W:{terminal_width} H:{terminal_height}"
318
+
319
+ subtitle = f"{bbox_str} | {terminal_wh_str}"
320
+
321
+ if len(subtitle) <= (terminal_width - 4):
322
+ return subtitle
323
+ elif len(bbox_str) <= (terminal_width - 4):
324
+ return bbox_str
325
+ else:
326
+ return ""
@@ -0,0 +1,129 @@
1
+ """
2
+ Wrappers around img2unicode.Renderers.
3
+
4
+ Look https://github.com/matrach/img2unicode/tree/master/examples for more information
5
+ about renderers.
6
+ """
7
+
8
+ from typing import TYPE_CHECKING
9
+
10
+ if TYPE_CHECKING:
11
+ from img2unicode import Renderer
12
+
13
+
14
+ def get_fast_block_renderer(terminal_width: int, terminal_height: int) -> "Renderer":
15
+ """Fast block renderer."""
16
+ import img2unicode
17
+
18
+ return img2unicode.Renderer(
19
+ img2unicode.FastGenericDualOptimizer("block"),
20
+ max_h=terminal_height,
21
+ max_w=terminal_width,
22
+ allow_upscale=True,
23
+ )
24
+
25
+
26
+ def get_fast_all_renderer(terminal_width: int, terminal_height: int) -> "Renderer":
27
+ """Fast all renderer."""
28
+ import img2unicode
29
+
30
+ return img2unicode.Renderer(
31
+ img2unicode.FastGenericDualOptimizer(),
32
+ max_h=terminal_height,
33
+ max_w=terminal_width,
34
+ allow_upscale=True,
35
+ )
36
+
37
+
38
+ def get_fast_ascii_renderer(terminal_width: int, terminal_height: int) -> "Renderer":
39
+ """Fast all renderer."""
40
+ import img2unicode
41
+
42
+ return img2unicode.Renderer(
43
+ img2unicode.FastGenericDualOptimizer("ascii"),
44
+ max_h=terminal_height,
45
+ max_w=terminal_width,
46
+ allow_upscale=True,
47
+ )
48
+
49
+
50
+ def get_space_renderer(terminal_width: int, terminal_height: int) -> "Renderer":
51
+ """Space renderer."""
52
+ import img2unicode
53
+
54
+ return img2unicode.Renderer(
55
+ img2unicode.SpaceDualOptimizer(),
56
+ max_h=terminal_height,
57
+ max_w=terminal_width,
58
+ allow_upscale=True,
59
+ )
60
+
61
+
62
+ def get_half_renderer(terminal_width: int, terminal_height: int) -> "Renderer":
63
+ """Half renderer."""
64
+ import img2unicode
65
+
66
+ return img2unicode.Renderer(
67
+ img2unicode.HalfBlockDualOptimizer(),
68
+ max_h=terminal_height,
69
+ max_w=terminal_width,
70
+ allow_upscale=True,
71
+ )
72
+
73
+
74
+ def get_quad_renderer(terminal_width: int, terminal_height: int) -> "Renderer":
75
+ """Quad renderer."""
76
+ import img2unicode
77
+
78
+ return img2unicode.Renderer(
79
+ img2unicode.FastQuadDualOptimizer(),
80
+ max_h=terminal_height,
81
+ max_w=terminal_width,
82
+ allow_upscale=True,
83
+ )
84
+
85
+
86
+ def get_braille_renderer(terminal_width: int, terminal_height: int) -> "Renderer":
87
+ """Braille renderer."""
88
+ import img2unicode
89
+
90
+ return img2unicode.GammaRenderer(
91
+ img2unicode.BestGammaOptimizer(use_color=True, charmask="braille"),
92
+ max_h=terminal_height,
93
+ max_w=terminal_width,
94
+ allow_upscale=True,
95
+ )
96
+
97
+ def get_ascii_bw_renderer(terminal_width: int, terminal_height: int) -> "Renderer":
98
+ """ASCII black-white renderer."""
99
+ import img2unicode
100
+
101
+ return img2unicode.GammaRenderer(
102
+ img2unicode.BestGammaOptimizer(use_color=False, charmask="ascii"),
103
+ max_h=terminal_height,
104
+ max_w=terminal_width,
105
+ allow_upscale=True,
106
+ )
107
+
108
+ def get_braille_bw_renderer(terminal_width: int, terminal_height: int) -> "Renderer":
109
+ """Braille renderer."""
110
+ import img2unicode
111
+
112
+ return img2unicode.GammaRenderer(
113
+ img2unicode.BestGammaOptimizer(use_color=False, charmask="braille"),
114
+ max_h=terminal_height,
115
+ max_w=terminal_width,
116
+ allow_upscale=True,
117
+ )
118
+
119
+ AVAILABLE_RENDERERS = {
120
+ "block": get_fast_block_renderer,
121
+ "all": get_fast_all_renderer,
122
+ "ascii": get_fast_ascii_renderer,
123
+ "space": get_space_renderer,
124
+ "half": get_half_renderer,
125
+ "quad": get_quad_renderer,
126
+ "braille": get_braille_renderer,
127
+ "braille-bw": get_braille_bw_renderer,
128
+ "ascii-bw": get_ascii_bw_renderer,
129
+ }
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pixel-map"
3
- version = "0.1.1"
3
+ version = "0.2.0"
4
4
  description = "A Python CLI tool for plotting geo files in the terminal"
5
5
  authors = [
6
6
  { name = "Kamil Raczycki", email = "kraczycki@kraina.ai" },
@@ -8,14 +8,12 @@ authors = [
8
8
  dependencies = [
9
9
  "rich>=12.0.0",
10
10
  "typer[all]>=0.9.0",
11
- "img2unicode[n2]>=0.1a11; sys_platform != 'win32'",
12
- "img2unicode>=0.1a11; sys_platform == 'win32'",
11
+ "img2unicode[n2]>=0.1a11; sys_platform != 'win32' and sys_platform != 'darwin'",
12
+ "img2unicode>=0.1a11; sys_platform == 'win32' or sys_platform == 'darwin'",
13
13
  "geopandas>=0.6",
14
14
  "numpy>=1.26.0",
15
- "shapely>=2",
16
- "contextily",
17
- "matplotlib",
18
- "pillow",
15
+ "contextily>=1",
16
+ "matplotlib>=3.2.0",
19
17
  "pyarrow>=16.0.0",
20
18
  ]
21
19
  requires-python = ">=3.9"
@@ -56,6 +54,10 @@ test = [
56
54
  "pytest-check>=2.3.1",
57
55
  "pytest-parametrization>=2022.2.1",
58
56
  ]
57
+ license = [
58
+ "licensecheck",
59
+ "pipdeptree",
60
+ ]
59
61
 
60
62
  [tool.pdm.scripts]
61
63
  post_install = "pre-commit install"
@@ -127,7 +129,7 @@ close-quotes-on-newline = true
127
129
  wrap-one-line = true
128
130
 
129
131
  [tool.bumpver]
130
- current_version = "0.1.1"
132
+ current_version = "0.2.0"
131
133
  version_pattern = "MAJOR.MINOR.PATCH[PYTAGNUM]"
132
134
  commit_message = "chore(CI/CD): bump version {old_version} -> {new_version}"
133
135
  commit = true
@@ -7,7 +7,7 @@ import pytest
7
7
  import typer
8
8
  from parametrization import Parametrization as P
9
9
 
10
- from pixel_map.__main__ import BboxGeometryParser
10
+ from pixel_map.__main__ import BboxParser
11
11
 
12
12
 
13
13
  @P.parameters("value", "expectation") # type: ignore
@@ -44,6 +44,6 @@ from pixel_map.__main__ import BboxGeometryParser
44
44
  def test_bbox_loading(value: str, expectation: Any) -> None:
45
45
  """Test if extracts finding by name works."""
46
46
  with expectation:
47
- bbox = BboxGeometryParser().convert(value) # type: ignore[no-untyped-call]
47
+ bbox = BboxParser().convert(value) # type: ignore[no-untyped-call]
48
48
  assert len(bbox) == 4
49
49
  assert all(isinstance(v, float) for v in bbox)
@@ -1,2 +0,0 @@
1
- __app_name__ = "pixel-map"
2
- __version__ = "0.1.1"
@@ -1,102 +0,0 @@
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
File without changes
File without changes
File without changes