heatmap_cli 0.29.2__tar.gz → 0.29.3__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.
Files changed (55) hide show
  1. {heatmap_cli-0.29.2/src/heatmap_cli.egg-info → heatmap_cli-0.29.3}/PKG-INFO +1 -1
  2. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/pyproject.toml +1 -1
  3. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/src/heatmap_cli/heatmap.py +135 -50
  4. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3/src/heatmap_cli.egg-info}/PKG-INFO +1 -1
  5. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_heatmap_direct.py +24 -0
  6. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_heatmap_errors.py +45 -1
  7. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_iso_53_week_year.py +1 -1
  8. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/LICENSE.md +0 -0
  9. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/README.md +0 -0
  10. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/setup.cfg +0 -0
  11. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/src/heatmap_cli/__init__.py +0 -0
  12. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/src/heatmap_cli/__main__.py +0 -0
  13. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/src/heatmap_cli/cli.py +0 -0
  14. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/src/heatmap_cli/py.typed +0 -0
  15. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/src/heatmap_cli.egg-info/SOURCES.txt +0 -0
  16. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/src/heatmap_cli.egg-info/dependency_links.txt +0 -0
  17. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/src/heatmap_cli.egg-info/entry_points.txt +0 -0
  18. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/src/heatmap_cli.egg-info/requires.txt +0 -0
  19. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/src/heatmap_cli.egg-info/top_level.txt +0 -0
  20. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_agg_backend.py +0 -0
  21. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_animate_by_week.py +0 -0
  22. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_animate_future_day.py +0 -0
  23. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_animate_no_frames.py +0 -0
  24. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_animate_open.py +0 -0
  25. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_annotate_flag.py +0 -0
  26. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_annotation_truncation.py +0 -0
  27. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_cbar_flag.py +0 -0
  28. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_cmap_option.py +0 -0
  29. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_cmax_option.py +0 -0
  30. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_cmin_option.py +0 -0
  31. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_configure_cbar.py +0 -0
  32. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_debug_flag.py +0 -0
  33. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_demo_option.py +0 -0
  34. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_end_date_option.py +0 -0
  35. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_env_flag.py +0 -0
  36. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_heatmap_open.py +0 -0
  37. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_heatmap_style_option.py +0 -0
  38. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_heatmap_utils.py +0 -0
  39. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_heatmap_wrapper.py +0 -0
  40. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_help_flag.py +0 -0
  41. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_main.py +0 -0
  42. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_no_annotate.py +0 -0
  43. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_open_heatmap.py +0 -0
  44. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_output_dir_option.py +0 -0
  45. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_purge_flag.py +0 -0
  46. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_quiet_flag.py +0 -0
  47. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_refresh_output_dir.py +0 -0
  48. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_setup_logging.py +0 -0
  49. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_start_date_option.py +0 -0
  50. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_supported_formats.py +0 -0
  51. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_title_option.py +0 -0
  52. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_version_flag.py +0 -0
  53. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_week_option.py +0 -0
  54. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_year_option.py +0 -0
  55. {heatmap_cli-0.29.2 → heatmap_cli-0.29.3}/tests/test_yes_flag.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: heatmap_cli
3
- Version: 0.29.2
3
+ Version: 0.29.3
4
4
  Summary: A console program that generates a yearly calendar heatmap.
5
5
  Author-email: Kian-Meng Ang <kianmeng@cpan.org>
6
6
  License-Expression: AGPL-3.0-or-later
@@ -28,7 +28,7 @@ classifiers = [
28
28
  "Programming Language :: Python",
29
29
  "Topic :: Scientific/Engineering :: Visualization",
30
30
  ]
31
- version = "0.29.2"
31
+ version = "0.29.3"
32
32
  keywords = ["heatmap", "cli", "visualization", "calendar", "data-viz"]
33
33
  dependencies = [
34
34
  "matplotlib",
@@ -20,14 +20,15 @@ from __future__ import annotations
20
20
  import copy
21
21
  import io
22
22
  import logging
23
+ import math
23
24
  import multiprocessing
24
25
  import os
25
26
  import re
26
27
  import shutil
27
28
  import webbrowser
28
- from datetime import UTC, date, datetime, timedelta
29
+ from datetime import date, datetime, timedelta
29
30
  from pathlib import Path
30
- from typing import TYPE_CHECKING, Any, cast
31
+ from typing import TYPE_CHECKING, Any, Literal, cast, overload
31
32
 
32
33
  if TYPE_CHECKING:
33
34
  import argparse
@@ -205,11 +206,10 @@ def _week_start_date(year: int, week: int) -> date:
205
206
  Returns:
206
207
  date: The date of the Monday that starts the week.
207
208
  """
208
- return (
209
- datetime.strptime(f"{year}-W{week}-1", "%G-W%V-%u")
210
- .replace(tzinfo=UTC)
211
- .date()
212
- )
209
+ return datetime.strptime( # noqa: DTZ007
210
+ f"{year}-W{week}-1",
211
+ "%G-W%V-%u",
212
+ ).date()
213
213
 
214
214
 
215
215
  def _generate_animated_heatmap(
@@ -270,7 +270,7 @@ def _generate_animated_heatmap(
270
270
  return_image=True,
271
271
  )
272
272
  if frame:
273
- frames.append(cast("Image.Image", frame))
273
+ frames.append(frame)
274
274
 
275
275
  if not frames:
276
276
  logger.warning("no frames generated to create GIF animation.")
@@ -342,15 +342,12 @@ def _generate_static_heatmaps(
342
342
  # still returning the generated file so opening works as before.
343
343
  seq, cmap = args[0][:2] # (seq, cmap, ...)
344
344
  generated_files = [
345
- cast(
346
- "Path | None",
347
- _generate_heatmap(
348
- seq,
349
- cmap,
350
- config,
351
- pivoted_dataframe,
352
- return_image=False,
353
- ),
345
+ _generate_heatmap(
346
+ seq,
347
+ cmap,
348
+ config,
349
+ pivoted_dataframe,
350
+ return_image=False,
354
351
  )
355
352
  ]
356
353
  else:
@@ -379,16 +376,67 @@ def _generate_heatmap_wrapper(
379
376
  Workers always save to disk (``return_image=False``), so the result is a
380
377
  file Path, never an in-memory image.
381
378
  """
382
- return cast(
383
- "Path | None",
384
- _generate_heatmap(
385
- seq,
386
- cmap,
387
- config,
388
- dataframe,
389
- return_image=False,
390
- ),
379
+ return _generate_heatmap(
380
+ seq,
381
+ cmap,
382
+ config,
383
+ dataframe,
384
+ return_image=False,
385
+ )
386
+
387
+
388
+ def _find_invalid_count_line(filename: str | Path) -> int | None:
389
+ """Find the line number of the first invalid count in a CSV file.
390
+
391
+ Called only after pandas has rejected the count column. It re-reads the
392
+ counts as text, leaving accepted input unchanged, so the parser's generic
393
+ error can be reported with the offending row's line number.
394
+
395
+ Args:
396
+ filename (str | Path): The CSV file that failed to parse.
397
+
398
+ Returns:
399
+ int | None: The 1-based line number of the first invalid count, or
400
+ None if the problem could not be located.
401
+ """
402
+ path = Path(filename)
403
+ try:
404
+ counts = pd.read_csv(
405
+ path,
406
+ header=None,
407
+ names=["date", "count"],
408
+ dtype="string",
409
+ )["count"]
410
+ except ValueError:
411
+ return None
412
+
413
+ if counts.empty:
414
+ return None
415
+
416
+ numeric = pd.to_numeric(counts, errors="coerce").astype("float64")
417
+ invalid = ~numeric.map(
418
+ lambda value: math.isfinite(value) and float(value).is_integer(),
419
+ )
420
+ first_invalid = next(
421
+ (index for index, is_invalid in enumerate(invalid) if is_invalid),
422
+ None,
391
423
  )
424
+ if first_invalid is None:
425
+ return None
426
+
427
+ try:
428
+ with path.open(encoding="utf-8") as handle:
429
+ # pandas skips blank lines, so map the row position onto the
430
+ # physical line number of the corresponding non-blank line.
431
+ data_lines = [
432
+ line_number
433
+ for line_number, line in enumerate(handle, 1)
434
+ if line.strip()
435
+ ]
436
+ except OSError:
437
+ return None
438
+
439
+ return data_lines[first_invalid]
392
440
 
393
441
 
394
442
  def _read_and_prepare_data(config: argparse.Namespace) -> pd.DataFrame:
@@ -421,9 +469,11 @@ def _read_and_prepare_data(config: argparse.Namespace) -> pd.DataFrame:
421
469
  logger.error("Input file not found: %s", config.input_filename)
422
470
  raise
423
471
  except ValueError as error:
472
+ line = _find_invalid_count_line(config.input_filename)
473
+ location = f" (line {line})" if line is not None else ""
424
474
  msg = (
425
475
  "Invalid count values in input CSV: "
426
- f"{config.input_filename}, expected an integer."
476
+ f"{config.input_filename}, expected an integer{location}."
427
477
  )
428
478
  raise ValueError(msg) from error
429
479
 
@@ -459,7 +509,7 @@ def _read_and_prepare_data(config: argparse.Namespace) -> pd.DataFrame:
459
509
  msg = f"Duplicate dates found: {dup_dates_str}"
460
510
  raise ValueError(msg)
461
511
 
462
- dataframe["weekday"] = dataframe["date"].dt.weekday + 1
512
+ dataframe["weekday"] = dataframe["date"].dt.day_of_week + 1
463
513
  dataframe["year"] = dataframe["date"].dt.isocalendar().year
464
514
  dataframe["week"] = (
465
515
  dataframe["date"].dt.isocalendar().week.astype(str).str.zfill(2)
@@ -526,7 +576,9 @@ def _filter_and_pivot_data(
526
576
  logger.debug("end date: %s", end_date)
527
577
  full_year_dates = pd.date_range(start=start_date, end=end_date, freq="D")
528
578
  full_year_structure = pd.DataFrame({"date": full_year_dates})
529
- full_year_structure["weekday"] = full_year_structure["date"].dt.weekday + 1
579
+ full_year_structure["weekday"] = (
580
+ full_year_structure["date"].dt.day_of_week + 1
581
+ )
530
582
  full_year_structure["week"] = (
531
583
  full_year_structure["date"]
532
584
  .dt.isocalendar()
@@ -621,6 +673,28 @@ def _setup_plot_artists(
621
673
  return fig, axis
622
674
 
623
675
 
676
+ @overload
677
+ def _generate_heatmap(
678
+ seq: int,
679
+ cmap: str,
680
+ config: argparse.Namespace,
681
+ dataframe: pd.DataFrame,
682
+ *,
683
+ return_image: Literal[True],
684
+ ) -> Image.Image: ...
685
+
686
+
687
+ @overload
688
+ def _generate_heatmap(
689
+ seq: int,
690
+ cmap: str,
691
+ config: argparse.Namespace,
692
+ dataframe: pd.DataFrame,
693
+ *,
694
+ return_image: Literal[False] = False,
695
+ ) -> Path: ...
696
+
697
+
624
698
  def _generate_heatmap(
625
699
  seq: int,
626
700
  cmap: str,
@@ -628,7 +702,7 @@ def _generate_heatmap(
628
702
  dataframe: pd.DataFrame,
629
703
  *,
630
704
  return_image: bool = False,
631
- ) -> Image.Image | Path | None:
705
+ ) -> Image.Image | Path:
632
706
  """Generate a heatmap.
633
707
 
634
708
  Args:
@@ -641,8 +715,8 @@ def _generate_heatmap(
641
715
  saving to disk.
642
716
 
643
717
  Returns:
644
- Optional[Image.Image | Path]: The PIL Image object if return_image is
645
- True, otherwise the Path of the saved heatmap file.
718
+ Image.Image | Path: The PIL Image object if return_image is True,
719
+ otherwise the Path of the saved heatmap file.
646
720
  """
647
721
  fig, axis = _setup_plot_artists(cmap, config, dataframe)
648
722
 
@@ -915,17 +989,24 @@ def _render_heatmap_image(fig: Figure) -> Image.Image:
915
989
  Returns:
916
990
  Image.Image: The rendered heatmap as a PIL Image object.
917
991
  """
918
- fig.tight_layout()
919
- buffer = io.BytesIO()
920
- fig.savefig(
921
- buffer,
922
- bbox_inches="tight",
923
- transparent=False,
924
- dpi=DEFAULT_DPI,
925
- format="png",
926
- )
927
- buffer.seek(0)
928
- return Image.open(buffer).copy()
992
+ try:
993
+ fig.tight_layout()
994
+ buffer = io.BytesIO()
995
+ fig.savefig(
996
+ buffer,
997
+ bbox_inches="tight",
998
+ transparent=False,
999
+ dpi=DEFAULT_DPI,
1000
+ format="png",
1001
+ )
1002
+ buffer.seek(0)
1003
+ return Image.open(buffer).copy()
1004
+ finally:
1005
+ # Figures use the object-oriented API, so pyplot never registers them
1006
+ # and plt.close() would be a no-op. Clearing releases the axes,
1007
+ # artists, and image data right away instead of waiting for the GC,
1008
+ # which keeps memory flat across animation frames and colormaps.
1009
+ fig.clear()
929
1010
 
930
1011
 
931
1012
  def _save_heatmap_figure(
@@ -952,13 +1033,17 @@ def _save_heatmap_figure(
952
1033
  img_filename = output_dir / _generate_filename(config, seq, cmap, title)
953
1034
  img_filename.parent.mkdir(parents=True, exist_ok=True)
954
1035
 
955
- fig.savefig(
956
- img_filename,
957
- bbox_inches="tight",
958
- transparent=False,
959
- dpi=DEFAULT_DPI,
960
- format=config.format,
961
- )
1036
+ try:
1037
+ fig.savefig(
1038
+ img_filename,
1039
+ bbox_inches="tight",
1040
+ transparent=False,
1041
+ dpi=DEFAULT_DPI,
1042
+ format=config.format,
1043
+ )
1044
+ finally:
1045
+ # See _render_heatmap_image: pyplot does not track these figures.
1046
+ fig.clear()
962
1047
  return img_filename
963
1048
 
964
1049
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: heatmap_cli
3
- Version: 0.29.2
3
+ Version: 0.29.3
4
4
  Summary: A console program that generates a yearly calendar heatmap.
5
5
  Author-email: Kian-Meng Ang <kianmeng@cpan.org>
6
6
  License-Expression: AGPL-3.0-or-later
@@ -22,6 +22,7 @@ from PIL import Image
22
22
  from heatmap_cli.heatmap import (
23
23
  _generate_heatmap,
24
24
  _render_heatmap_image,
25
+ _save_heatmap_figure,
25
26
  _setup_plot_artists,
26
27
  )
27
28
 
@@ -70,3 +71,26 @@ def test_render_heatmap_image(tmpdir):
70
71
  image = _render_heatmap_image(fig)
71
72
 
72
73
  assert isinstance(image, Image.Image)
74
+ # The figure is released after rendering so long batch runs do not keep
75
+ # every rendered figure and its artists alive.
76
+ assert fig.axes == []
77
+
78
+
79
+ def test_save_heatmap_figure_releases_figure(tmpdir):
80
+ config = argparse.Namespace(
81
+ annotate=False,
82
+ cbar=False,
83
+ cmap_min=None,
84
+ cmap_max=None,
85
+ output_dir=str(tmpdir),
86
+ format="png",
87
+ heatmap_style="number",
88
+ )
89
+
90
+ df = pd.DataFrame([[10, 20], [30, 40]], index=[1, 2], columns=["01", "02"])
91
+
92
+ fig, _axis = _setup_plot_artists("vlag", config, df)
93
+ img_filename = _save_heatmap_figure(fig, config, 1, "vlag", "Test Title")
94
+
95
+ assert img_filename.exists()
96
+ assert fig.axes == []
@@ -19,7 +19,11 @@ from unittest.mock import patch
19
19
 
20
20
  import pytest
21
21
 
22
- from heatmap_cli.heatmap import _read_and_prepare_data, _refresh_output_dir
22
+ from heatmap_cli.heatmap import (
23
+ _find_invalid_count_line,
24
+ _read_and_prepare_data,
25
+ _refresh_output_dir,
26
+ )
23
27
 
24
28
 
25
29
  def test_file_not_found_error_direct(tmpdir):
@@ -112,6 +116,46 @@ def test_invalid_count_error_cli(cli_runner, tmpdir):
112
116
  assert ret.returncode == 1
113
117
 
114
118
 
119
+ def test_invalid_count_error_reports_line_number(tmpdir):
120
+ """The error points at the physical line, even across blank lines."""
121
+ csv_path = _write_csv(
122
+ tmpdir,
123
+ "bad_count.csv",
124
+ ["2023-01-01,10", "2023-01-02,20", "", "2023-01-03,abc"],
125
+ )
126
+
127
+ config = argparse.Namespace(input_filename=str(csv_path), annotate=False)
128
+ with pytest.raises(ValueError, match=r"expected an integer \(line 4\)"):
129
+ _read_and_prepare_data(config)
130
+
131
+
132
+ def test_invalid_count_error_omits_line_when_unlocatable(tmpdir):
133
+ """A CSV that cannot be re-read still gets the original error."""
134
+ csv_path = Path(tmpdir) / "unclosed.csv"
135
+ csv_path.write_text('2023-01-01,"10\n')
136
+
137
+ config = argparse.Namespace(input_filename=str(csv_path), annotate=False)
138
+ with pytest.raises(ValueError, match="expected an integer") as exc_info:
139
+ _read_and_prepare_data(config)
140
+ assert "(line" not in str(exc_info.value)
141
+
142
+
143
+ def test_find_invalid_count_line_returns_none_if_file_cannot_be_opened(tmpdir):
144
+ csv_path = _write_csv(tmpdir, "valid.csv", ["2023-01-01,10"])
145
+
146
+ with patch.object(Path, "open", side_effect=OSError("boom")):
147
+ assert _find_invalid_count_line(csv_path) is None
148
+
149
+
150
+ def test_find_invalid_count_line_returns_none_for_valid_or_empty_csv(tmpdir):
151
+ valid = _write_csv(tmpdir, "valid.csv", ["2023-01-01,10"])
152
+ empty = Path(tmpdir) / "empty.csv"
153
+ empty.write_text("")
154
+
155
+ assert _find_invalid_count_line(valid) is None
156
+ assert _find_invalid_count_line(empty) is None
157
+
158
+
115
159
  def test_empty_csv_error_cli(cli_runner, tmpdir):
116
160
  csv_path = Path(tmpdir) / "empty.csv"
117
161
  csv_path.write_text("")
@@ -37,7 +37,7 @@ def _base_dataframe(rows: list[tuple[str, int]]) -> pd.DataFrame:
37
37
  """Build a prepared DataFrame as done by _read_and_prepare_data."""
38
38
  df = pd.DataFrame(rows, columns=["date", "count"])
39
39
  df["date"] = pd.to_datetime(df["date"])
40
- df["weekday"] = df["date"].dt.weekday + 1
40
+ df["weekday"] = df["date"].dt.day_of_week + 1
41
41
  df["year"] = df["date"].dt.isocalendar().year
42
42
  df["week"] = df["date"].dt.isocalendar().week.astype(str).str.zfill(2)
43
43
  return df
File without changes
File without changes
File without changes