meteostat-cli 0.1.0__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.
@@ -0,0 +1,175 @@
1
+ """Station command for the Meteostat CLI."""
2
+
3
+ import pandas as pd
4
+ import typer
5
+
6
+ from meteo.utils import detect_format, output_df
7
+
8
+
9
+ def station_cmd(
10
+ station_id: str | None = typer.Argument(
11
+ None, help="Meteostat station ID. If omitted, lists stations."
12
+ ),
13
+ country: str | None = typer.Option(
14
+ None, "--country", "-c", help="ISO 3166-1 alpha-2 country code."
15
+ ),
16
+ state: str | None = typer.Option(None, "--state", help="State or region code."),
17
+ name: str | None = typer.Option(
18
+ None, "--name", "-n", help="Station name (partial match)."
19
+ ),
20
+ sql: str | None = typer.Option(None, "--sql", help="Arbitrary SQL query."),
21
+ wmo: str | None = typer.Option(None, "--wmo", "-w", help="WMO station ID."),
22
+ icao: str | None = typer.Option(None, "--icao", "-i", help="ICAO station ID."),
23
+ iata: str | None = typer.Option(None, "--iata", help="IATA station ID."),
24
+ national: str | None = typer.Option(
25
+ None, "--national", "-N", help="National station ID."
26
+ ),
27
+ bbox: str | None = typer.Option(
28
+ None, "--bbox", help="Bounding box (lon_min,lat_min,lon_max,lat_max)."
29
+ ),
30
+ fmt: str | None = typer.Option(None, "--format", "-f", help="Output format."),
31
+ output: str | None = typer.Option(None, "--output", "-o", help="Output file path."),
32
+ no_header: bool = typer.Option(
33
+ False, "--no-header", help="Omit header row from CSV output."
34
+ ),
35
+ show_all: bool = typer.Option(
36
+ False, "--all", "-A", help="Print full table instead of truncated display."
37
+ ),
38
+ ) -> None:
39
+ """Get metadata for a weather station, or list stations with optional filters."""
40
+ import meteostat as ms
41
+
42
+ actual_fmt = detect_format(fmt, output)
43
+
44
+ if station_id is not None:
45
+ meta = ms.stations.meta(station_id)
46
+
47
+ if meta is None:
48
+ typer.echo(f"Error: Station '{station_id}' not found.", err=True)
49
+ raise typer.Exit(1)
50
+
51
+ data = {
52
+ "id": meta.id,
53
+ "name": meta.name,
54
+ "country": meta.country,
55
+ "region": meta.region,
56
+ "latitude": meta.latitude,
57
+ "longitude": meta.longitude,
58
+ "elevation": meta.elevation,
59
+ "timezone": meta.timezone,
60
+ }
61
+ for key, value in meta.identifiers.items():
62
+ data[key] = value
63
+
64
+ df = pd.DataFrame([data]).set_index("id")
65
+
66
+ if actual_fmt == "text" and output is None:
67
+ from rich.console import Console
68
+ from rich.table import Table
69
+
70
+ table = Table(show_header=False, show_lines=True, padding=(0, 2, 0, 0))
71
+ table.add_column(style="bold")
72
+ table.add_column()
73
+ for field, value in data.items():
74
+ display = str(value) if value is not None else ""
75
+ if field == "elevation" and value is not None:
76
+ display = f"{value} m"
77
+ table.add_row(field, display)
78
+ Console().print(table)
79
+ else:
80
+ output_df(df, actual_fmt, output, no_header, show_all=show_all)
81
+ else:
82
+ if sql:
83
+ df = ms.stations.query(sql, index_col="id")
84
+ else:
85
+ conditions: list[str] = []
86
+ params: list[str] = []
87
+
88
+ if country:
89
+ conditions.append("`stations`.`country` = ?")
90
+ params.append(country.upper())
91
+
92
+ if state:
93
+ conditions.append("`stations`.`region` = ?")
94
+ params.append(state.upper())
95
+
96
+ if name:
97
+ conditions.append("`names`.`name` LIKE ?")
98
+ params.append(f"%{name}%")
99
+
100
+ if wmo:
101
+ conditions.append(
102
+ "`stations`.`id` IN (SELECT `station` FROM `identifiers` WHERE `key` = 'wmo' AND `value` LIKE ?)"
103
+ )
104
+ params.append(f"%{wmo.upper()}%")
105
+
106
+ if icao:
107
+ conditions.append(
108
+ "`stations`.`id` IN (SELECT `station` FROM `identifiers` WHERE `key` = 'icao' AND `value` LIKE ?)"
109
+ )
110
+ params.append(f"%{icao.upper()}%")
111
+
112
+ if iata:
113
+ conditions.append(
114
+ "`stations`.`id` IN (SELECT `station` FROM `identifiers` WHERE `key` = 'iata' AND `value` LIKE ?)"
115
+ )
116
+ params.append(f"%{iata.upper()}%")
117
+
118
+ if national:
119
+ conditions.append(
120
+ "`stations`.`id` IN (SELECT `station` FROM `identifiers` WHERE `key` = 'national' AND `value` LIKE ?)"
121
+ )
122
+ params.append(f"%{national.upper()}%")
123
+
124
+ if bbox:
125
+ parts = bbox.split(",")
126
+ if len(parts) != 4:
127
+ typer.echo(
128
+ "Error: --bbox requires 4 comma-separated values: lon_min,lat_min,lon_max,lat_max",
129
+ err=True,
130
+ )
131
+ raise typer.Exit(2)
132
+ try:
133
+ lon_min_f, lat_min_f, lon_max_f, lat_max_f = (
134
+ float(p) for p in parts
135
+ )
136
+ except ValueError:
137
+ typer.echo(
138
+ "Error: --bbox values must be numeric floats.",
139
+ err=True,
140
+ )
141
+ raise typer.Exit(2) from None
142
+ conditions.append("`stations`.`longitude` >= ?")
143
+ params.append(str(lon_min_f))
144
+ conditions.append("`stations`.`latitude` >= ?")
145
+ params.append(str(lat_min_f))
146
+ conditions.append("`stations`.`longitude` <= ?")
147
+ params.append(str(lon_max_f))
148
+ conditions.append("`stations`.`latitude` <= ?")
149
+ params.append(str(lat_max_f))
150
+
151
+ query = """
152
+ SELECT
153
+ `stations`.`id`,
154
+ `names`.`name`,
155
+ `stations`.`country`,
156
+ `stations`.`region`,
157
+ `stations`.`latitude`,
158
+ `stations`.`longitude`,
159
+ `stations`.`elevation`,
160
+ `stations`.`timezone`
161
+ FROM `stations`
162
+ LEFT JOIN `names` ON `stations`.`id` = `names`.`station`
163
+ AND `names`.`language` = 'en'
164
+ """
165
+
166
+ if conditions:
167
+ query += " WHERE " + " AND ".join(conditions)
168
+
169
+ query += " ORDER BY `stations`.`id`"
170
+
171
+ df = ms.stations.query(
172
+ query, index_col="id", params=tuple(params) if params else None
173
+ )
174
+
175
+ output_df(df, actual_fmt, output, no_header, show_all=show_all)
meteo/config.py ADDED
@@ -0,0 +1,175 @@
1
+ """Configuration management for the Meteostat CLI.
2
+
3
+ Handles loading/saving CLI configuration from cli.yml, applying Meteostat
4
+ library config overrides, and type coercion between YAML and Python values.
5
+ """
6
+
7
+ import json
8
+ from pathlib import Path
9
+ from typing import Any, get_args, get_origin
10
+
11
+ import typer
12
+ import yaml
13
+
14
+ # CLI-specific config keys (not part of Meteostat library config)
15
+ CLI_CONFIG_KEYS = {
16
+ "interpolation_radius": 25000,
17
+ "humanize": True,
18
+ }
19
+
20
+
21
+ def _get_config_dir() -> Path:
22
+ """Get the CLI config directory path."""
23
+ return Path(typer.get_app_dir("meteostat"))
24
+
25
+
26
+ def _get_config_path() -> Path:
27
+ """Get the CLI config file path."""
28
+ return _get_config_dir() / "cli.yml"
29
+
30
+
31
+ def load_config() -> dict[str, Any]:
32
+ """Load configuration from cli.yml."""
33
+ path = _get_config_path()
34
+ if not path.exists():
35
+ return {}
36
+ try:
37
+ with open(path) as f:
38
+ data = yaml.safe_load(f)
39
+ except yaml.YAMLError as exc:
40
+ typer.echo(
41
+ f"Warning: Could not parse config file {path}: {exc}. Using defaults.",
42
+ err=True,
43
+ )
44
+ return {}
45
+ return data if isinstance(data, dict) else {}
46
+
47
+
48
+ def save_config(data: dict[str, Any]) -> None:
49
+ """Save configuration to cli.yml."""
50
+ path = _get_config_path()
51
+ path.parent.mkdir(parents=True, exist_ok=True)
52
+ with open(path, "w") as f:
53
+ yaml.dump(data, f, default_flow_style=False, sort_keys=True)
54
+
55
+
56
+ def get_meteostat_config_keys() -> dict[str, Any]:
57
+ """Discover all Meteostat config options at runtime.
58
+
59
+ Uses both __annotations__ and class-level attributes from the Config class
60
+ to catch annotated AND unannotated attributes.
61
+ """
62
+ from meteostat.api.config import Config
63
+
64
+ keys: dict[str, Any] = {}
65
+
66
+ # Collect from class hierarchy annotations
67
+ for cls in Config.__mro__:
68
+ for attr_name, _ in getattr(cls, "__annotations__", {}).items():
69
+ if not attr_name.startswith("_") and attr_name != "prefix":
70
+ keys[attr_name] = getattr(Config, attr_name, None)
71
+
72
+ # Also scan class-level attributes (catches unannotated ones)
73
+ for attr_name in vars(Config):
74
+ if attr_name.startswith("_") or attr_name == "prefix":
75
+ continue
76
+ val = getattr(Config, attr_name)
77
+ if callable(val) and not isinstance(val, (list, dict)):
78
+ continue
79
+ if attr_name not in keys:
80
+ keys[attr_name] = val
81
+
82
+ return keys
83
+
84
+
85
+ def get_config_type(key: str) -> type | None:
86
+ """Get the type annotation for a Meteostat config key."""
87
+ from meteostat.api.config import Config
88
+
89
+ for cls in Config.__mro__:
90
+ annotations = getattr(cls, "__annotations__", {})
91
+ if key in annotations:
92
+ ann = annotations[key]
93
+ origin = get_origin(ann)
94
+ if origin is not None:
95
+ # Handle Optional[X] -> extract X
96
+ args = get_args(ann)
97
+ if type(None) in args:
98
+ # Optional type - get the non-None type
99
+ non_none = [a for a in args if a is not type(None)]
100
+ if non_none:
101
+ return non_none[0]
102
+ return origin
103
+ return ann
104
+ return None
105
+
106
+
107
+ def coerce_value(key: str, value: str) -> Any:
108
+ """Coerce a string value to the appropriate Python type for a config key.
109
+
110
+ Uses the Config class annotations to determine the target type.
111
+ """
112
+ if key in CLI_CONFIG_KEYS:
113
+ # CLI-specific keys use their default type
114
+ default = CLI_CONFIG_KEYS[key]
115
+ target_type: type | None = type(default)
116
+ else:
117
+ target_type = get_config_type(key)
118
+
119
+ if target_type is None:
120
+ # No annotation found — try JSON parsing, fall back to string
121
+ try:
122
+ return json.loads(value)
123
+ except (json.JSONDecodeError, ValueError):
124
+ return value
125
+
126
+ if target_type is bool:
127
+ if value.lower() in ("true", "1", "yes"):
128
+ return True
129
+ if value.lower() in ("false", "0", "no"):
130
+ return False
131
+ raise ValueError(f"Cannot convert '{value}' to bool")
132
+
133
+ if target_type is int:
134
+ return int(value)
135
+
136
+ if target_type is float:
137
+ return float(value)
138
+
139
+ if target_type is str:
140
+ return value
141
+
142
+ if target_type in (list, dict):
143
+ return json.loads(value)
144
+
145
+ # Fallback: try JSON, then string
146
+ try:
147
+ return json.loads(value)
148
+ except (json.JSONDecodeError, ValueError):
149
+ return value
150
+
151
+
152
+ def format_value(value: Any) -> str:
153
+ """Format a Python value for display."""
154
+ if isinstance(value, bool):
155
+ return str(value).lower()
156
+ if isinstance(value, (list, dict)):
157
+ return json.dumps(value)
158
+ if value is None:
159
+ return "null"
160
+ return str(value)
161
+
162
+
163
+ def apply_config() -> None:
164
+ """Load CLI config and apply Meteostat library config overrides.
165
+
166
+ Called during app startup (before any command runs).
167
+ """
168
+ import meteostat as ms
169
+
170
+ data = load_config()
171
+ ms_keys = get_meteostat_config_keys()
172
+
173
+ for key, value in data.items():
174
+ if key in ms_keys:
175
+ setattr(ms.config, key, value)
meteo/plotting.py ADDED
@@ -0,0 +1,172 @@
1
+ """Plotting module for the Meteostat CLI.
2
+
3
+ Provides plot_dataframe() for generating PNG/SVG charts from weather data.
4
+ Matplotlib is lazily imported so it's only required when plotting is used.
5
+ """
6
+
7
+ from pathlib import Path
8
+
9
+ import pandas as pd
10
+
11
+ # Pre-configured colors per parameter
12
+ PARAMETER_COLORS = {
13
+ "temp": "#e74c3c",
14
+ "tmin": "#3498db",
15
+ "tmax": "#e67e22",
16
+ "txmn": "#2980b9",
17
+ "txmx": "#c0392b",
18
+ "dwpt": "#1abc9c",
19
+ "prcp": "#2ecc71",
20
+ "pday": "#27ae60",
21
+ "snow": "#95a5a6",
22
+ "snwd": "#bdc3c7",
23
+ "wspd": "#9b59b6",
24
+ "wpgt": "#8e44ad",
25
+ "wdir": "#34495e",
26
+ "rhum": "#16a085",
27
+ "pres": "#f39c12",
28
+ "tsun": "#f1c40f",
29
+ "cldc": "#7f8c8d",
30
+ "vsby": "#2c3e50",
31
+ "sghi": "#e74c3c",
32
+ "sdni": "#e67e22",
33
+ "sdhi": "#f39c12",
34
+ "coco": "#7f8c8d",
35
+ }
36
+
37
+
38
+ def _get_param_label(col_str: str) -> str:
39
+ """Get display label for a parameter column using parameter_service."""
40
+ try:
41
+ from meteostat.core.parameters import parameter_service
42
+ from meteostat.enumerations import Granularity, Parameter
43
+
44
+ param = Parameter(col_str)
45
+ for granularity in Granularity:
46
+ spec = parameter_service.get_parameter(param, granularity)
47
+ if spec is not None:
48
+ unit = spec.unit.value if spec.unit else None
49
+ return f"{spec.name} ({unit})" if unit else spec.name
50
+ except (ValueError, Exception):
51
+ pass
52
+ return col_str
53
+
54
+
55
+ # Default color cycle for unknown parameters
56
+ DEFAULT_COLORS = [
57
+ "#e74c3c",
58
+ "#3498db",
59
+ "#2ecc71",
60
+ "#f39c12",
61
+ "#9b59b6",
62
+ "#1abc9c",
63
+ "#e67e22",
64
+ "#34495e",
65
+ ]
66
+
67
+
68
+ def plot_dataframe(
69
+ df,
70
+ output: str,
71
+ fmt: str,
72
+ title: str | None = None,
73
+ width: float = 10,
74
+ height: float = 6,
75
+ ) -> None:
76
+ """Generate a plot from a DataFrame and save to file.
77
+
78
+ Parameters
79
+ ----------
80
+ df : pd.DataFrame
81
+ The data to plot.
82
+ output : str
83
+ Output file path.
84
+ fmt : str
85
+ Output format ('png' or 'svg').
86
+ title : str, optional
87
+ Custom plot title.
88
+ width : float
89
+ Plot width in inches.
90
+ height : float
91
+ Plot height in inches.
92
+ """
93
+ try:
94
+ import matplotlib
95
+
96
+ matplotlib.use("Agg")
97
+ import matplotlib.pyplot as plt
98
+ except ImportError:
99
+ import typer
100
+
101
+ typer.echo(
102
+ "Error: Matplotlib is required for plot output. "
103
+ "Install with: pip install meteostat-cli[plot]",
104
+ err=True,
105
+ )
106
+ raise typer.Exit(1) from None
107
+
108
+ # Flatten MultiIndex (e.g. normals returns a (station, month) index)
109
+ if isinstance(df.index, pd.MultiIndex):
110
+ try:
111
+ df = df.droplevel(list(range(df.index.nlevels - 1)))
112
+ except ValueError:
113
+ df = df.reset_index(drop=True)
114
+
115
+ # Filter out source columns (they contain provider names, not numeric data)
116
+ # Also filter out non-numeric columns that cannot be plotted
117
+ plot_cols = [
118
+ col
119
+ for col in df.columns
120
+ if not str(col).endswith("_source") and pd.api.types.is_numeric_dtype(df[col])
121
+ ]
122
+
123
+ if not plot_cols:
124
+ import typer
125
+
126
+ typer.echo("Error: No plottable numeric data columns found.", err=True)
127
+ raise typer.Exit(1)
128
+
129
+ fig, ax = plt.subplots(figsize=(width, height))
130
+
131
+ color_idx = 0
132
+ plotted = 0
133
+ for col in plot_cols:
134
+ col_str = str(col)
135
+ label = _get_param_label(col_str)
136
+ color = PARAMETER_COLORS.get(
137
+ col_str, DEFAULT_COLORS[color_idx % len(DEFAULT_COLORS)]
138
+ )
139
+ if col_str not in PARAMETER_COLORS:
140
+ color_idx += 1
141
+
142
+ # Drop NaN values for cleaner plots
143
+ series = df[col].dropna()
144
+ if series.empty:
145
+ continue
146
+
147
+ ax.plot(series.index, series.values, label=label, color=color, linewidth=1.2)
148
+ plotted += 1
149
+
150
+ if plotted == 0:
151
+ import typer
152
+
153
+ plt.close(fig)
154
+ typer.echo(
155
+ "Error: All data columns are empty (all NaN). Nothing to plot.", err=True
156
+ )
157
+ raise typer.Exit(1)
158
+
159
+ ax.set_xlabel("Time")
160
+ ax.set_ylabel("Value")
161
+
162
+ if title:
163
+ ax.set_title(title)
164
+
165
+ ax.legend(loc="best", fontsize="small")
166
+ ax.grid(True, alpha=0.3)
167
+ fig.autofmt_xdate()
168
+ fig.tight_layout()
169
+
170
+ Path(output).parent.mkdir(parents=True, exist_ok=True)
171
+ fig.savefig(output, format=fmt, dpi=150, bbox_inches="tight")
172
+ plt.close(fig)