skyan1002's picture
v1.0 manifest covering all 806 testbeds; docs/CLI corrected; mirror Zenodo qc/ and code/pipeline/; DOI 10.5281/zenodo.22100899
378f073 verified
Raw History Blame Contribute Delete
1.88 kB
"""io.py — small shared utilities: id normalization, HTTP, time formatting, logging.
Faithful extraction from the original l3_lib.py (logic unchanged).
"""
import time
import logging
import pandas as pd
import requests
import config
def norm_gage_id(x) -> str:
"""Normalize a USGS site number to 8-digit zero-padded string.
Site numbers longer than 8 digits are preserved at their natural length."""
if pd.isna(x) or str(x).strip() == "":
return ""
s = str(x).strip()
try:
i = int(float(s))
nat = str(i)
return nat.zfill(8) if len(nat) <= 8 else nat
except (ValueError, TypeError):
return s
def safe_float(v, default=None):
try:
return float(v)
except (ValueError, TypeError):
return default
def dt_to_nwis(dt: pd.Timestamp) -> str:
return pd.Timestamp(dt).strftime("%Y-%m-%dT%H:%MZ")
def to_utc(ts: pd.Timestamp) -> pd.Timestamp:
ts = pd.Timestamp(ts)
return ts.tz_localize("UTC") if ts.tzinfo is None else ts.tz_convert("UTC")
def http_get(url, params=None, timeout=20):
"""GET with a fixed inter-call delay; returns Response or None on any error.
In OFFLINE (cache-frozen) mode, suppress the network entirely (returns None),
so cache-miss queries behave as the original run's failure/miss."""
if config.OFFLINE:
return None
try:
time.sleep(config.RATE_DELAY)
r = requests.get(url, params=params, timeout=timeout)
r.raise_for_status()
return r
except Exception:
return None
def get_logger(name="pipeline"):
logger = logging.getLogger(name)
if not logger.handlers:
h = logging.StreamHandler()
h.setFormatter(logging.Formatter("%(asctime)s %(levelname)-7s %(message)s", "%H:%M:%S"))
logger.addHandler(h)
logger.setLevel(logging.INFO)
return logger