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.
meteo/utils.py ADDED
@@ -0,0 +1,473 @@
1
+ """Shared utilities for the Meteostat CLI.
2
+
3
+ Provides date parsing, station/coordinate disambiguation, output formatting,
4
+ and common option patterns shared across time-series commands.
5
+ """
6
+
7
+ import sys
8
+ from datetime import date, datetime, timedelta
9
+ from pathlib import Path
10
+ from typing import Any, Literal
11
+
12
+ import pandas as pd
13
+ import typer
14
+
15
+ from meteo.config import CLI_CONFIG_KEYS, load_config
16
+
17
+ # Mapping of file extensions to format names
18
+ EXT_FORMAT_MAP = {
19
+ ".csv": "csv",
20
+ ".json": "json",
21
+ ".xlsx": "xlsx",
22
+ ".parquet": "parquet",
23
+ ".png": "png",
24
+ ".svg": "svg",
25
+ }
26
+
27
+
28
+ def parse_date(value: str | None, is_end: bool = False) -> date | datetime | None:
29
+ """Parse a date string in various formats.
30
+
31
+ Supports: YYYY-MM-DD, YYYY-MM, YYYY, YYYY-MM-DDTHH:MM:SSZ
32
+ For YYYY-MM: if is_end, uses last day of month.
33
+ For YYYY: if is_end, uses Dec 31.
34
+ Returns a datetime when the input contains a time component (ISO 8601 with T).
35
+ """
36
+ if value is None:
37
+ return None
38
+
39
+ try:
40
+ # ISO 8601 with time component
41
+ if "T" in value:
42
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
43
+
44
+ parts = value.split("-")
45
+
46
+ if len(parts) == 3:
47
+ return date(int(parts[0]), int(parts[1]), int(parts[2]))
48
+
49
+ if len(parts) == 2:
50
+ year, month = int(parts[0]), int(parts[1])
51
+ if is_end:
52
+ # Last day of the month
53
+ if month == 12:
54
+ return date(year, 12, 31)
55
+ return date(year, month + 1, 1) - timedelta(days=1)
56
+ return date(year, month, 1)
57
+
58
+ if len(parts) == 1:
59
+ year = int(parts[0])
60
+ if is_end:
61
+ return date(year, 12, 31)
62
+ return date(year, 1, 1)
63
+
64
+ raise typer.BadParameter(f"Invalid date format: {value}")
65
+ except ValueError:
66
+ # Normalize numeric/date parsing errors to a clean CLI error
67
+ raise typer.BadParameter(f"Invalid date format: {value}") from None
68
+
69
+
70
+ def parse_datetime(value: str | None, is_end: bool = False) -> datetime | None:
71
+ """Parse a date string and return a datetime object."""
72
+ result = parse_date(value, is_end)
73
+ if result is None:
74
+ return None
75
+ if isinstance(result, datetime):
76
+ return result
77
+ return datetime(result.year, result.month, result.day)
78
+
79
+
80
+ def resolve_station_or_point(
81
+ *stations: str,
82
+ ) -> (
83
+ tuple[Literal["station"], str]
84
+ | tuple[Literal["stations"], list[Any]]
85
+ | tuple[Literal["point"], float, float]
86
+ ):
87
+ """Disambiguate station ID(s) vs lat/lon coordinates.
88
+
89
+ Returns:
90
+ ("station", id), ("stations", [id, ...]), or ("point", lat, lon)
91
+ """
92
+ if len(stations) == 1 and "," in stations[0]:
93
+ parts = stations[0].split(",", 1)
94
+ try:
95
+ lat_f = float(parts[0])
96
+ lon_f = float(parts[1])
97
+ except ValueError:
98
+ raise typer.BadParameter(f"Invalid coordinates: {stations[0]}") from None
99
+ if not (-90 <= lat_f <= 90):
100
+ raise typer.BadParameter(
101
+ f"Latitude must be between -90 and 90, got {lat_f}"
102
+ )
103
+ if not (-180 <= lon_f <= 180):
104
+ raise typer.BadParameter(
105
+ f"Longitude must be between -180 and 180, got {lon_f}"
106
+ )
107
+ return ("point", lat_f, lon_f)
108
+
109
+ if len(stations) == 1:
110
+ return ("station", stations[0])
111
+
112
+ return ("stations", list(stations))
113
+
114
+
115
+ def get_interpolation_radius() -> int:
116
+ """Get the configured interpolation radius for coordinate-based queries."""
117
+ data = load_config()
118
+ key = "interpolation_radius"
119
+ if key in data:
120
+ return int(data[key])
121
+ return CLI_CONFIG_KEYS["interpolation_radius"]
122
+
123
+
124
+ def detect_format(fmt: str | None, output: str | None) -> str:
125
+ """Detect the output format from explicit flag or file extension."""
126
+ if fmt is not None:
127
+ return fmt
128
+
129
+ if output is not None:
130
+ ext = Path(output).suffix.lower()
131
+ if ext in EXT_FORMAT_MAP:
132
+ return EXT_FORMAT_MAP[ext]
133
+
134
+ return "text"
135
+
136
+
137
+ def output_df(
138
+ df: pd.DataFrame | None,
139
+ fmt: str,
140
+ output: str | None = None,
141
+ no_header: bool = False,
142
+ plot_params: dict | None = None,
143
+ show_all: bool = False,
144
+ ) -> None:
145
+ """Output a DataFrame in the specified format.
146
+
147
+ Handles CSV, JSON, XLSX, Parquet output, and PNG/SVG plotting.
148
+ When fmt is "text" and show_all is False (default), uses Pandas'
149
+ standard truncated display. Pass show_all=True (--all flag) to
150
+ print the full table.
151
+ """
152
+ if df is None or df.empty:
153
+ typer.echo("No data available.", err=True)
154
+ raise typer.Exit(1)
155
+
156
+ if fmt in ("png", "svg"):
157
+ if output is None:
158
+ typer.echo(
159
+ f"Error: {fmt.upper()} format requires --output to specify a file path.",
160
+ err=True,
161
+ )
162
+ raise typer.Exit(2)
163
+ from meteo.plotting import plot_dataframe
164
+
165
+ plot_dataframe(df, output, fmt, **(plot_params or {}))
166
+ return
167
+
168
+ if fmt == "text":
169
+ if show_all:
170
+ text = df.to_string(max_rows=None, max_cols=None)
171
+ else:
172
+ text = df.to_string(
173
+ max_rows=pd.get_option("display.max_rows"),
174
+ max_cols=pd.get_option("display.max_columns"),
175
+ )
176
+ if output:
177
+ Path(output).parent.mkdir(parents=True, exist_ok=True)
178
+ Path(output).write_text(text + "\n")
179
+ else:
180
+ sys.stdout.write(text + "\n")
181
+
182
+ elif fmt == "csv":
183
+ text = df.reset_index().to_csv(index=False, header=not no_header)
184
+ assert text is not None
185
+ if output:
186
+ Path(output).parent.mkdir(parents=True, exist_ok=True)
187
+ Path(output).write_text(text)
188
+ else:
189
+ sys.stdout.write(text)
190
+
191
+ elif fmt == "json":
192
+ text = df.reset_index().to_json(orient="records", indent=2, date_format="iso")
193
+ assert text is not None
194
+ if output:
195
+ Path(output).parent.mkdir(parents=True, exist_ok=True)
196
+ Path(output).write_text(text)
197
+ else:
198
+ sys.stdout.write(text)
199
+ sys.stdout.write("\n")
200
+
201
+ elif fmt == "xlsx":
202
+ if output is None:
203
+ typer.echo(
204
+ "Error: XLSX format requires --output to specify a file path.",
205
+ err=True,
206
+ )
207
+ raise typer.Exit(2)
208
+ Path(output).parent.mkdir(parents=True, exist_ok=True)
209
+ try:
210
+ df.reset_index().to_excel(output, index=False)
211
+ except ImportError:
212
+ typer.echo(
213
+ "Error: openpyxl is required for XLSX output. "
214
+ "Install with: pip install openpyxl",
215
+ err=True,
216
+ )
217
+ raise typer.Exit(1) from None
218
+
219
+ elif fmt == "parquet":
220
+ if output is None:
221
+ typer.echo(
222
+ "Error: Parquet format requires --output to specify a file path.",
223
+ err=True,
224
+ )
225
+ raise typer.Exit(2)
226
+ Path(output).parent.mkdir(parents=True, exist_ok=True)
227
+ try:
228
+ df.to_parquet(output, index=True)
229
+ except ImportError:
230
+ typer.echo(
231
+ "Error: pyarrow is required for Parquet output. "
232
+ "Install with: pip install pyarrow",
233
+ err=True,
234
+ )
235
+ raise typer.Exit(1) from None
236
+
237
+ else:
238
+ typer.echo(f"Error: Unknown format '{fmt}'.", err=True)
239
+ raise typer.Exit(2)
240
+
241
+
242
+ def apply_no_cache() -> None:
243
+ """Disable Meteostat cache for the current request."""
244
+ import meteostat as ms
245
+
246
+ ms.config.cache_enable = False
247
+
248
+
249
+ def apply_no_models() -> None:
250
+ """Exclude model data for the current request."""
251
+ import meteostat as ms
252
+
253
+ ms.config.include_model_data = False
254
+
255
+
256
+ def parse_parameters(value: str | None) -> list | None:
257
+ """Parse comma-separated parameter names into Parameter enums."""
258
+ if value is None:
259
+ return None
260
+ from meteostat.enumerations import Parameter
261
+
262
+ params = []
263
+ for name in value.split(","):
264
+ name = name.strip().upper()
265
+ try:
266
+ params.append(Parameter[name])
267
+ except KeyError:
268
+ # Try by value (lowercase)
269
+ try:
270
+ params.append(Parameter(name.lower()))
271
+ except ValueError:
272
+ typer.echo(
273
+ f"Error: Unknown parameter '{name}'.",
274
+ err=True,
275
+ )
276
+ raise typer.Exit(2) from None
277
+ return params
278
+
279
+
280
+ def parse_providers(value: str | None) -> list | None:
281
+ """Parse comma-separated provider names into Provider enums."""
282
+ if value is None:
283
+ return None
284
+ from meteostat.enumerations import Provider
285
+
286
+ providers = []
287
+ for name in value.split(","):
288
+ name = name.strip()
289
+ try:
290
+ providers.append(Provider[name.upper()])
291
+ except KeyError:
292
+ try:
293
+ providers.append(Provider(name.lower()))
294
+ except ValueError:
295
+ typer.echo(
296
+ f"Error: Unknown provider '{name}'.",
297
+ err=True,
298
+ )
299
+ raise typer.Exit(2) from None
300
+ return providers
301
+
302
+
303
+ def fetch_timeseries(
304
+ granularity: str,
305
+ stations: list[str],
306
+ start: str | None = None,
307
+ end: str | None = None,
308
+ timezone: str | None = None,
309
+ parameters: str | None = None,
310
+ providers: str | None = None,
311
+ no_models: bool = False,
312
+ with_sources: bool = False,
313
+ no_cache: bool = False,
314
+ fmt: str | None = None,
315
+ output: str | None = None,
316
+ no_header: bool = False,
317
+ show_all: bool = False,
318
+ agg: str | None = None,
319
+ ) -> None:
320
+ """Shared logic for hourly/daily/monthly/normals time-series commands."""
321
+ import meteostat as ms
322
+
323
+ if no_cache:
324
+ apply_no_cache()
325
+ if no_models:
326
+ apply_no_models()
327
+
328
+ resolved = resolve_station_or_point(*stations)
329
+ # Always pass station IDs as a list so the API returns a station-indexed
330
+ # MultiIndex DataFrame, ensuring --agg always shows the station ID.
331
+ if resolved[0] == "station":
332
+ resolved: tuple[Literal["stations"], list[Any]] = ("stations", [resolved[1]])
333
+ param_list = parse_parameters(parameters)
334
+ provider_list = parse_providers(providers)
335
+
336
+ # Build kwargs for the API call
337
+ kwargs: dict = {}
338
+ if param_list is not None:
339
+ kwargs["parameters"] = param_list
340
+ if provider_list is not None:
341
+ kwargs["providers"] = provider_list
342
+
343
+ # Select the API function and parse dates appropriately
344
+ if granularity == "normals":
345
+ try:
346
+ start_val = int(start) if start else 1991
347
+ end_val = int(end) if end else 2020
348
+ except ValueError:
349
+ raise typer.BadParameter(
350
+ "Start and end for normals must be a 4-digit year (e.g. 1991)."
351
+ ) from None
352
+ if not (1000 <= start_val <= 9999) or not (1000 <= end_val <= 9999):
353
+ raise typer.BadParameter(
354
+ "Start and end for normals must be a 4-digit year (e.g. 1991)."
355
+ )
356
+ if start_val > end_val:
357
+ raise typer.BadParameter(
358
+ f"Start year ({start_val}) must be before end year ({end_val})."
359
+ )
360
+ if resolved[0] == "station" or resolved[0] == "stations":
361
+ ts = ms.normals(resolved[1], start_val, end_val, **kwargs)
362
+ else:
363
+ point = ms.Point(resolved[1], resolved[2])
364
+ radius = get_interpolation_radius()
365
+ nearby = ms.stations.nearby(point, radius=radius)
366
+ if nearby.empty:
367
+ typer.echo(
368
+ "No weather stations found within the specified radius.",
369
+ err=True,
370
+ )
371
+ raise typer.Exit(1)
372
+ ts = ms.normals(nearby, start_val, end_val, **kwargs)
373
+ ts = ms.interpolate(ts, point)
374
+ else:
375
+ api_fn = getattr(ms, granularity)
376
+
377
+ if granularity == "hourly":
378
+ default_start = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
379
+ default_end = datetime.now().strftime("%Y-%m-%d")
380
+ start_dt = parse_datetime(start or default_start)
381
+ end_dt = parse_datetime(end or default_end, is_end=True)
382
+ if start_dt and end_dt and start_dt > end_dt:
383
+ raise typer.BadParameter(
384
+ f"Start date ({start_dt.date()}) must be before end date ({end_dt.date()})."
385
+ )
386
+ extra_kwargs: dict = {}
387
+ if timezone:
388
+ extra_kwargs["timezone"] = timezone
389
+ if resolved[0] == "station" or resolved[0] == "stations":
390
+ ts = api_fn(
391
+ resolved[1],
392
+ start_dt,
393
+ end_dt,
394
+ **extra_kwargs,
395
+ **kwargs,
396
+ )
397
+ else:
398
+ point = ms.Point(resolved[1], resolved[2])
399
+ radius = get_interpolation_radius()
400
+ nearby = ms.stations.nearby(point, radius=radius)
401
+ if nearby.empty:
402
+ typer.echo(
403
+ "No weather stations found within the specified radius.",
404
+ err=True,
405
+ )
406
+ raise typer.Exit(1)
407
+ ts = api_fn(
408
+ nearby,
409
+ start_dt,
410
+ end_dt,
411
+ **extra_kwargs,
412
+ **kwargs,
413
+ )
414
+ ts = ms.interpolate(ts, point)
415
+ else:
416
+ # daily/monthly
417
+ if granularity == "daily":
418
+ default_start = (datetime.now() - timedelta(days=30)).strftime(
419
+ "%Y-%m-%d"
420
+ )
421
+ else:
422
+ default_start = (datetime.now() - timedelta(days=365)).strftime(
423
+ "%Y-%m-%d"
424
+ )
425
+ default_end = datetime.now().strftime("%Y-%m-%d")
426
+ start_dt = parse_datetime(start or default_start)
427
+ end_dt = parse_datetime(end or default_end, is_end=True)
428
+ if start_dt and end_dt and start_dt > end_dt:
429
+ raise typer.BadParameter(
430
+ f"Start date ({start_dt.date()}) must be before end date ({end_dt.date()})."
431
+ )
432
+ if resolved[0] == "station" or resolved[0] == "stations":
433
+ ts = api_fn(resolved[1], start_dt, end_dt, **kwargs)
434
+ else:
435
+ point = ms.Point(resolved[1], resolved[2])
436
+ radius = get_interpolation_radius()
437
+ nearby = ms.stations.nearby(point, radius=radius)
438
+ if nearby.empty:
439
+ typer.echo(
440
+ "No weather stations found within the specified radius.",
441
+ err=True,
442
+ )
443
+ raise typer.Exit(1)
444
+ ts = api_fn(nearby, start_dt, end_dt, **kwargs)
445
+ ts = ms.interpolate(ts, point)
446
+
447
+ # Determine humanize setting (CLI config, default True)
448
+ config_data = load_config()
449
+ humanize = config_data.get("humanize", CLI_CONFIG_KEYS["humanize"])
450
+
451
+ # Fetch the DataFrame
452
+ df = ts.fetch(sources=with_sources, humanize=humanize)
453
+
454
+ if df is None or df.empty:
455
+ typer.echo("No data available.", err=True)
456
+ raise typer.Exit(1)
457
+
458
+ # Apply aggregation if requested
459
+ if agg is not None:
460
+ try:
461
+ if "station" in df.index.names:
462
+ df = df.groupby(level="station").agg(agg)
463
+ else:
464
+ result = df.agg(agg)
465
+ df = result.to_frame().T if isinstance(result, pd.Series) else result
466
+ except (AttributeError, TypeError, ValueError) as exc:
467
+ typer.echo(f"Error: Invalid aggregation function '{agg}': {exc}", err=True)
468
+ raise typer.Exit(2) from None
469
+
470
+ # Determine output format
471
+ actual_fmt = detect_format(fmt, output)
472
+
473
+ output_df(df, actual_fmt, output, no_header, None, show_all)