# Zip Weather 48h

> Use this when someone wants the weather, a forecast, or a 48-hour outlook in 4-hour blocks for any location worldwide (a US zip code, a city like "Paris" or "Tokyo", a city plus country, or a postal code), with an animated radar map.

- Skill: `shixuuu/zip-weather-48h` (Agent Skill)
- Install (CLI): `npx get-skill add shixuuu/zip-weather-48h`
- Raw SKILL.md: https://api.skillmd.com/api/skills/shixuuu/zip-weather-48h/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: Shixuuu (https://skillmd.com/u/shixuuu)
- Updated: 2026-11-24
- Page: https://skillmd.com/skills/shixuuu/zip-weather-48h

---


# 48-hour forecast in 4-hour blocks for any location, plus an animated radar

**Data sources are fixed:** in the US, the forecast always comes from the US National Weather Service (api.weather.gov) and the radar from NOAA NEXRAD radar and the HRRR model via the Iowa Environmental Mesonet. Everywhere else, the forecast comes from Open-Meteo (MET Norway steps in automatically if Open-Meteo is busy) and the radar from RainViewer's global radar network. The scripts pick the source by themselves. Never ask the user to pick a weather provider, API, or source, never suggest a weather connector or plugin, and never ask for an API key.

Everything used is free and needs no key or sign-up. Zippopotam.us turns a US zip into a location, and Open-Meteo geocoding handles everything else: city names ("Paris", "Tokyo"), city plus country or state ("London, Ontario", "Paris TX"), and postal codes worldwide ("SW1A 1AA", "75001 France"). Zippopotam is the fallback for postal codes Open-Meteo doesn't know. US places use the National Weather Service hourly forecast, other places the Open-Meteo hourly forecast. Radar tiles come from the Iowa Environmental Mesonet (US lower 48) or RainViewer (everywhere else, for personal use, credited on the map), over an OpenStreetMap basemap.

## Steps
1. Make sure the scripts exist on your computer. If `/workspace/zipweather/wxlocate.py`, `/workspace/zipweather/zipweather.py` or `/workspace/zipweather/zipradar.py` is missing, create it from the scripts below; all three sit in the same folder. If `python3 -c "import PIL, requests"` fails, run `pip install --user --break-system-packages pillow requests`. For the MP4 copy of the radar, `ffmpeg` should be on the PATH. If `which ffmpeg` finds nothing, run `pip install --user --break-system-packages imageio-ffmpeg`. The script picks up either one, and without them it just skips the MP4.
2. Run `python3 /workspace/zipweather/zipweather.py "<LOCATION>"` for the table data and `python3 /workspace/zipweather/zipradar.py "<LOCATION>"` for the radar (usually 5 to 40 seconds). Quote the location if it has spaces. It can be a US zip code, a city, a city with its country or state, or a postal code, preferably with its country. The radar prints the GIF path on the first line and the MP4 path on the second when ffmpeg is available. The file is `/workspace/zipweather/radar_<ZIP>.gif` for a zip. For other places it is the location in lower case with underscores, e.g. `radar_london.gif` or `radar_75001_france.gif`. Progress notes and warnings go to stderr. Both scripts can run at the same time. Map tiles are cached under `/workspace/zipweather/cache` (safe to delete). If no location is given, use the saved home location from memory, or ask for one.
3. Check the first line of the forecast. It names the place that was picked (e.g. "48-hour forecast for London, England, United Kingdom"). If that is clearly not the place meant (e.g. London, Ontario instead of London, UK), run both scripts again with the country or state added. Mention the place you used in the reply whenever the name was ambiguous.
4. Handle problems:
   - "Couldn't find US zip code": ask the person to double-check the zip.
   - "Couldn't find a place called ...": ask for a more specific name, for example with the country added.
   - "Couldn't look up ... right now", or a weather service error: retry once after a few seconds. If it still fails, say it's temporarily unavailable.
   - The radar prints "No radar coverage at ..." (exit code 3): there is no animation. Send the forecast and say plainly that there is no weather radar coverage at that location. This is normal in much of Africa, Russia, Central Asia, parts of the Middle East and South America, and over open ocean.
   - If only the radar fails for any other reason, still send the forecast and say the radar map is unavailable right now.
5. Reply in one message with:
   - One or two plain sentences on the big picture first (for example: "Rain most of Sunday, heaviest in the evening with a chance of thunderstorms. Monday morning clears up.").
   - Then a table with one row per 4-hour block: Time, Conditions, Temp, Rain chance, Humidity, Wind. Use the units the script prints. The US uses °F and mph. Everywhere else uses °C and km/h, and the Rain chance column adds the expected amount in mm when the script shows it (e.g. "74% (11.4 mm)"). If the script says "rain chance n/a" (backup source), show just the amount, or "none expected".
   - Then one practical tip if something stands out (umbrella, strong wind, heat, freezing temps).
   - The radar GIF (1280x720) attached as an image on that same message, so it shows below the table.
     - US lower 48: the first frames are real radar every 5 minutes over the past hour, and the one marked "Now" pauses briefly. The rest are the HRRR forecast every 15 minutes for the next 8 hours. On heavy-rain days the script may drop the forecast to every 30 minutes (or 1024x576) to keep the GIF under about 8 MB; it says so on stderr.
     - Outside the US (and in Alaska, Hawaii and the territories): the past hour of real radar every 10 minutes, ending and holding on "Now". There are no forecast frames there, so don't promise a radar forecast. Grey shading on the map marks areas outside radar coverage, where blank does not mean dry.
     - The strip above the legend shows where each frame falls. Where video works better (for example X posts), send the MP4 instead. It always has every frame and is smaller.
   - Outside the US, end with a short credit line such as "Forecast: Open-Meteo.com · Radar: RainViewer.com". Use the "Forecast data:" line the script prints, since it names the backup source when one was used. The radar image already carries its own credits.
6. Keep the times in the location's local time, as the scripts print them.

## wxlocate.py
```python
#!/usr/bin/env python3
"""Turn any location text into coordinates for the weather scripts. Free, no keys.
US 5-digit zips are left to the scripts' original Zippopotam + NWS path; everything else (city, "city, country",
non-US postal code) goes through Open-Meteo geocoding, with Zippopotam as a postal-code fallback."""
import json, re, sys, time, unicodedata, urllib.error, urllib.parse, urllib.request

UA = {"User-Agent": "grok-bot-zip-weather (contact: weather-bot)"}
GEO = "https://geocoding-api.open-meteo.com/v1/search"
US_LIKE = {"US", "PR", "VI", "GU", "AS", "MP"}          # NWS forecast territory, °F / mph
STATES = {"Alabama": "AL", "Alaska": "AK", "Arizona": "AZ", "Arkansas": "AR", "California": "CA", "Colorado": "CO",
    "Connecticut": "CT", "Delaware": "DE", "District of Columbia": "DC", "Florida": "FL", "Georgia": "GA", "Hawaii": "HI",
    "Idaho": "ID", "Illinois": "IL", "Indiana": "IN", "Iowa": "IA", "Kansas": "KS", "Kentucky": "KY", "Louisiana": "LA",
    "Maine": "ME", "Maryland": "MD", "Massachusetts": "MA", "Michigan": "MI", "Minnesota": "MN", "Mississippi": "MS",
    "Missouri": "MO", "Montana": "MT", "Nebraska": "NE", "Nevada": "NV", "New Hampshire": "NH", "New Jersey": "NJ",
    "New Mexico": "NM", "New York": "NY", "North Carolina": "NC", "North Dakota": "ND", "Ohio": "OH", "Oklahoma": "OK",
    "Oregon": "OR", "Pennsylvania": "PA", "Rhode Island": "RI", "South Carolina": "SC", "South Dakota": "SD",
    "Tennessee": "TN", "Texas": "TX", "Utah": "UT", "Vermont": "VT", "Virginia": "VA", "Washington": "WA",
    "West Virginia": "WV", "Wisconsin": "WI", "Wyoming": "WY", "Puerto Rico": "PR"}
ALIAS = {"uk": "GB", "u.k.": "GB", "britain": "GB", "great britain": "GB", "united kingdom": "GB", "england": "GB",
    "scotland": "GB", "wales": "GB", "northern ireland": "GB", "us": "US", "u.s.": "US", "usa": "US", "u.s.a.": "US",
    "america": "US", "united states": "US", "uae": "AE", "emirates": "AE", "korea": "KR", "south korea": "KR",
    "holland": "NL", "the netherlands": "NL", "czechia": "CZ", "czech republic": "CZ", "russia": "RU", "vietnam": "VN",
    "turkey": "TR", "türkiye": "TR", "ivory coast": "CI", "hong kong": "HK", "taiwan": "TW",
    # countries Zippopotam knows postal codes for (fallback when Open-Meteo has no match for a postal code)
    "germany": "DE", "deutschland": "DE", "france": "FR", "spain": "ES", "italy": "IT", "netherlands": "NL",
    "belgium": "BE", "switzerland": "CH", "austria": "AT", "japan": "JP", "australia": "AU", "new zealand": "NZ",
    "canada": "CA", "india": "IN", "brazil": "BR", "mexico": "MX", "sweden": "SE", "norway": "NO", "denmark": "DK",
    "finland": "FI", "poland": "PL", "portugal": "PT", "ireland": "IE", "argentina": "AR", "south africa": "ZA",
    "hungary": "HU", "slovakia": "SK", "croatia": "HR", "luxembourg": "LU", "iceland": "IS", "sri lanka": "LK",
    "thailand": "TH", "malaysia": "MY", "philippines": "PH", "pakistan": "PK", "dominican republic": "DO"}
UK_PC = re.compile(r"^([A-Z]{1,2}\d[A-Z\d]?)\s*\d[A-Z]{2}$")
CA_PC = re.compile(r"^([A-Z]\d[A-Z])\s*\d[A-Z]\d$")

def is_us_zip(q): return bool(re.fullmatch(r"\d{5}", q.strip()))

def territory_zip(zipcode):
    """Zippopotam lists Puerto Rico, USVI, Guam, N. Mariana and American Samoa zips under their own codes, not 'us'.
    Returns a place in the 'us' response shape (state abbreviation = territory code), or None."""
    for cc in ("pr", "vi", "gu", "mp", "as"):
        try: places = get(f"https://api.zippopotam.us/{cc}/{zipcode}").get("places")
        except Exception: continue
        if places: return dict(places[0], **{"state abbreviation": cc.upper()})
    return None

def get(url):
    with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=20) as r:
        return json.load(r)

def norm(s): return "".join(c for c in unicodedata.normalize("NFKD", s or "") if not unicodedata.combining(c)).lower().strip(" .")

class LookupError_(RuntimeError): pass

def search(name, count=20):
    q = urllib.parse.urlencode({"name": name, "count": count, "language": "en", "format": "json"})
    for k in range(3):   # transient errors / 429: wait and retry, then report the service as down (not "not found")
        try: return get(f"{GEO}?{q}").get("results") or []
        except Exception as e:
            if isinstance(e, urllib.error.HTTPError) and e.code == 400: return []
            err = e; time.sleep(2 * (k + 1))
    raise LookupError_(f"location lookup (Open-Meteo geocoding) unavailable: {err}")

def matches(r, qual):
    """Does result r fit a qualifier like 'France', 'FR', 'UK', 'Ontario' or 'TX'?"""
    q = norm(qual)
    cc = (r.get("country_code") or "").upper()
    if ALIAS.get(q) == cc or q.upper() == cc and len(q) == 2 and cc not in US_LIKE: return True
    if q in (norm(r.get("country")), norm(r.get("admin1")), norm(r.get("admin2"))): return True
    if cc in US_LIKE and q.upper() == STATES.get(r.get("admin1"), "-"): return True
    if ALIAS.get(q) == "GB" and q in ("england", "scotland", "wales", "northern ireland"): return norm(r.get("admin1")) == q
    return False

def rank(results, head):
    """Open-Meteo already orders by relevance and population; prefer exact name or postal-code hits and real towns."""
    h, hp = norm(head), head.upper().replace(" ", "")
    def key(ir):
        i, r = ir
        exact = norm(r.get("name")) == h or hp in [p.upper().replace(" ", "") for p in r.get("postcodes") or []]
        return (not exact, not (r.get("feature_code") or "").startswith("PPL"), i)
    return [r for _, r in sorted(enumerate(results), key=key)]

def pack(r, query, postal=""):
    cc = (r.get("country_code") or "").upper()
    name, a1, country = r.get("name") or query, r.get("admin1") or "", r.get("country") or cc
    us = cc in US_LIKE
    if us: short = f"{name}, {STATES.get(a1, a1 or cc)}"; label = short
    else:
        short = f"{name}, {country}" if norm(name) != norm(country) else name
        label = ", ".join(dict.fromkeys(x for x in (name, a1, country) if x))
    slug = re.sub(r"[^a-z0-9]+", "_", norm(query)).strip("_") or "place"
    return {"query": query, "lat": float(r["latitude"]), "lon": float(r["longitude"]), "name": name, "short": short,
            "label": label, "country_code": cc, "us": us, "tz": r.get("timezone"), "postal": postal, "slug": slug}

def zippopotam(code, cc):
    try: d = get(f"https://api.zippopotam.us/{cc.lower()}/{urllib.parse.quote(code)}")
    except Exception: return None
    p = d["places"][0]
    return {"name": p["place name"].split(" (")[0], "latitude": p["latitude"], "longitude": p["longitude"],
            "admin1": p.get("state") or "", "country": d.get("country"), "country_code": cc.upper()}

def resolve(query):
    """Best match for free text, or None if nothing matches. Raises LookupError_ if the lookup service was down."""
    errs = []
    r = _resolve(query, errs)
    if r is None and errs: raise errs[0]
    return r

def _resolve(query, errors_out):
    """Best match for free text, or None. Tries 'place, qualifier' and 'place qualifier' splits, then the whole text,
    then postal-code shortcuts (UK outward code, Canadian FSA, Zippopotam)."""
    q = " ".join(query.strip().split())
    if not q: return None
    words = q.replace(",", " ").split()
    splits = []
    if "," in q:
        head, rest = q.split(",", 1)
        splits.append((head.strip(), [p.strip() for p in rest.split(",") if p.strip()]))
    else:
        for n in (1, 2):
            if len(words) > n: splits.append((" ".join(words[:-n]), [" ".join(words[-n:])]))
    cache, errors = {}, errors_out
    def find(name):
        if name not in cache:
            try: cache[name] = search(name, 100)
            except LookupError_ as e: cache[name] = []; errors.append(e)
        return cache[name]
    postal_of = lambda s: s.upper() if any(ch.isdigit() for ch in s) else ""
    for head, quals in splits:          # e.g. "Paris, France", "75001 France", "London Ontario", "Portland, ME"
        hits = [r for r in find(head) if any(matches(r, x) for x in quals)]
        if hits: return pack(rank(hits, head)[0], q, postal_of(head))
    hits = find(q)
    if any(ch.isdigit() for ch in q) and splits:   # "10115 Germany": never jump to a fuzzy hit in another country
        hits = [r for r in hits if any(matches(r, x) for _, quals in splits for x in quals)]
    if hits: return pack(rank(hits, q)[0], q, postal_of(q))
    up = q.upper()
    cc_hint = next((ALIAS.get(norm(x)) or (x.upper() if len(x) == 2 else None) for _, quals in splits for x in quals), None)
    code = full = up
    for pat, cc in ((UK_PC, "GB"), (CA_PC, "CA")):   # full UK / Canadian postcodes -> outward code / FSA
        m = pat.match(up if not splits else splits[0][0].upper()) or pat.match(up)
        if m: code, full, cc_hint = m.group(1), m.group(0), cc_hint or cc; break
    else:
        if splits and any(ch.isdigit() for ch in splits[0][0]): code = full = splits[0][0].upper()
    if any(ch.isdigit() for ch in code):
        hits = [r for r in find(code) if not cc_hint or (r.get("country_code") or "").upper() == cc_hint]
        if hits: return pack(rank(hits, code)[0], q, full)
        if cc_hint:
            r = zippopotam(code, cc_hint)
            if r:
                r["timezone"] = tz_near(float(r["latitude"]), float(r["longitude"]), cc_hint, (r["name"], r["admin1"]), find)
                return pack(r, q, full)
    return None

def tz_near(lat, lon, cc, names, find):
    """Time zone of the nearest Open-Meteo place in the same country (Zippopotam results carry none)."""
    for n in names:
        rs = [r for r in find(n) if (r.get("country_code") or "").upper() == cc and r.get("timezone")] if n else []
        if rs: return min(rs, key=lambda r: (r["latitude"] - lat) ** 2 + (r["longitude"] - lon) ** 2)["timezone"]
    return None

if __name__ == "__main__":
    print(json.dumps(resolve(" ".join(sys.argv[1:])), ensure_ascii=False, indent=1))
```

## zipweather.py
```python
#!/usr/bin/env python3
"""48-hour forecast in 4-hour blocks for any location, all free and keyless.
US zip codes: Zippopotam + US National Weather Service (unchanged). Other text (city, "city, country", non-US
postal code): Open-Meteo geocoding; US places still use NWS, everywhere else the Open-Meteo forecast
(°C, km/h, mm), with MET Norway as an automatic backup if Open-Meteo is down or rate-limited."""
import json, os, sys, urllib.error, urllib.parse, urllib.request
from collections import Counter
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from wxlocate import is_us_zip, resolve, territory_zip, LookupError_

UA = {"User-Agent": "grok-bot-zip-weather (contact: weather-bot)", "Accept": "application/geo+json"}

def get(url):
    with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=20) as r:
        return json.load(r)

def print_nws(hourly):
    for i in range(0, len(hourly), 4):
        blk = hourly[i:i+4]
        start = datetime.fromisoformat(blk[0]["startTime"]); end = datetime.fromisoformat(blk[-1]["endTime"])
        temps = [p["temperature"] for p in blk]
        pop = max((p.get("probabilityOfPrecipitation") or {}).get("value") or 0 for p in blk)
        rh = [(p.get("relativeHumidity") or {}).get("value") for p in blk]; rh = [x for x in rh if x is not None]
        winds = [int(s) for p in blk for s in p["windSpeed"].replace("mph","").split(" to ") if s.strip().isdigit()]
        wdir = Counter(p["windDirection"] for p in blk).most_common(1)[0][0]
        sky = Counter(p["shortForecast"] for p in blk).most_common(1)[0][0]
        unit = blk[0]["temperatureUnit"]
        label = f"{start:%a %-I %p} to {end:%-I %p}"
        wind = f"{min(winds)}-{max(winds)} mph {wdir}" if winds and min(winds)!=max(winds) else f"{winds[0] if winds else '?'} mph {wdir}"
        if not winds or max(winds) == 0: wind = "calm"
        t = f"{min(temps)}-{max(temps)}" if min(temps) != max(temps) else f"{min(temps)}"
        print(f"{label}: {sky}. {t}°{unit}, rain chance up to {pop}%, "
              f"humidity ~{round(sum(rh)/len(rh)) if rh else '?'}%, wind {wind}.")

def main_zip(zipcode):
    try:
        z = get(f"https://api.zippopotam.us/us/{zipcode}")["places"][0]
    except Exception:
        z = territory_zip(zipcode)   # Puerto Rico, USVI, Guam, ... (NWS covers them too)
        if not z: sys.exit(f"Couldn't find US zip code {zipcode}. Check it and try again.")
    lat, lon = float(z["latitude"]), float(z["longitude"])
    pts = get(f"https://api.weather.gov/points/{lat:.4f},{lon:.4f}")["properties"]
    hourly = get(pts["forecastHourly"])["properties"]["periods"][:48]
    print(f"48-hour forecast for {zipcode} ({z['place name']}, {z['state abbreviation']})\n")
    print_nws(hourly)

# ---- worldwide ---------------------------------------------------------------------------------------------
COMPASS = "N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW".split()
WMO = {0: "Clear", 1: "Mostly Clear", 2: "Partly Cloudy", 3: "Cloudy", 45: "Fog", 48: "Freezing Fog",
       51: "Light Drizzle", 53: "Drizzle", 55: "Heavy Drizzle", 56: "Light Freezing Drizzle", 57: "Freezing Drizzle",
       61: "Light Rain", 63: "Rain", 65: "Heavy Rain", 66: "Light Freezing Rain", 67: "Freezing Rain",
       71: "Light Snow", 73: "Snow", 75: "Heavy Snow", 77: "Snow Grains", 80: "Light Rain Showers", 81: "Rain Showers",
       82: "Heavy Rain Showers", 85: "Snow Showers", 86: "Heavy Snow Showers", 95: "Thunderstorms",
       96: "Thunderstorms With Hail", 99: "Thunderstorms With Hail"}
DAYSKY = {"Clear": "Sunny", "Mostly Clear": "Mostly Sunny"}
MET = {"clearsky": "Clear", "fair": "Mostly Clear", "partlycloudy": "Partly Cloudy", "cloudy": "Cloudy", "fog": "Fog",
       "lightrain": "Light Rain", "rain": "Rain", "heavyrain": "Heavy Rain", "lightrainshowers": "Light Rain Showers",
       "rainshowers": "Rain Showers", "heavyrainshowers": "Heavy Rain Showers", "lightsleet": "Light Sleet",
       "sleet": "Sleet", "heavysleet": "Heavy Sleet", "lightsleetshowers": "Light Sleet Showers",
       "sleetshowers": "Sleet Showers", "heavysleetshowers": "Heavy Sleet Showers", "lightsnow": "Light Snow",
       "snow": "Snow", "heavysnow": "Heavy Snow", "lightsnowshowers": "Light Snow Showers", "snowshowers": "Snow Showers",
       "heavysnowshowers": "Heavy Snow Showers"}

WET = ("Rain", "Drizzle", "Snow", "Sleet", "Shower", "Thunder", "Freezing", "Grains")

def compass(deg): return COMPASS[round(deg / 22.5) % 16] if deg is not None else "?"

def met_sky(code):
    base, _, part = (code or "").partition("_")
    thunder = base.endswith("andthunder"); base = base.replace("andthunder", "")
    s = MET.get(base, base.title() or "?")
    if part == "day": s = DAYSKY.get(s, s)
    return s + " And Thunder" if thunder else s

def print_blocks(hours, metric):
    """hours: list of dicts with local datetime t, temp, rh, pop (None = n/a), mm, wind, wdir (compass), sky."""
    tu, wu = ("C", "km/h") if metric else ("F", "mph")
    for i in range(0, len(hours), 4):
        blk = hours[i:i+4]
        start, end = blk[0]["t"], blk[-1]["t"] + timedelta(hours=1)
        temps = [round(h["temp"]) for h in blk if h["temp"] is not None]
        pops = [h["pop"] for h in blk if h["pop"] is not None]
        rh = [h["rh"] for h in blk if h["rh"] is not None]
        winds = [round(h["wind"]) for h in blk if h["wind"] is not None]
        wdir = Counter(h["wdir"] for h in blk).most_common(1)[0][0]
        mm = sum(h["mm"] or 0 for h in blk)
        wet = [h for h in blk if any(w in h["sky"] for w in WET)]
        sky = Counter(h["sky"] for h in blk).most_common(1)[0][0]
        if wet and (len(wet) >= 2 or mm >= (1.0 if metric else 0.04)):
            # a block with real precipitation is named after its wettest condition, not "Cloudy"
            score = Counter()
            for h in wet: score[h["sky"]] += (h["mm"] or 0) + 0.01
            sky = score.most_common(1)[0][0]
        label = f"{start:%a %-I %p} to {end:%-I %p}"
        wind = f"{min(winds)}-{max(winds)} {wu} {wdir}" if winds and min(winds) != max(winds) else f"{winds[0] if winds else '?'} {wu} {wdir}"
        if not winds or max(winds) == 0: wind = "calm"
        t = (f"{min(temps)}-{max(temps)}" if min(temps) != max(temps) else f"{min(temps)}") if temps else "?"
        rain = f"rain chance up to {max(pops)}%" if pops else "rain chance n/a"
        if metric and mm >= 0.1: rain += f" ({mm:.1f} mm)"
        elif not metric and mm >= 0.01: rain += f" ({mm:.2f} in)"
        print(f"{label}: {sky}. {t}°{tu}, {rain}, humidity ~{round(sum(rh)/len(rh)) if rh else '?'}%, wind {wind}.")

def open_meteo(lat, lon, metric=True):
    q = {"latitude": f"{lat:.4f}", "longitude": f"{lon:.4f}", "timezone": "auto", "forecast_hours": 48,
         "hourly": "temperature_2m,relative_humidity_2m,precipitation_probability,precipitation,weather_code,"
                   "wind_speed_10m,wind_direction_10m,is_day"}
    if not metric: q.update(temperature_unit="fahrenheit", wind_speed_unit="mph", precipitation_unit="inch")
    return get("https://api.open-meteo.com/v1/forecast?" + urllib.parse.urlencode(q))

def om_hours(d):
    h = d["hourly"]; out = []
    for i, ts in enumerate(h["time"][:48]):
        sky = WMO.get(h["weather_code"][i], "?")
        if h["is_day"][i]: sky = DAYSKY.get(sky, sky)
        out.append({"t": datetime.fromisoformat(ts), "temp": h["temperature_2m"][i], "rh": h["relative_humidity_2m"][i],
                    "pop": h["precipitation_probability"][i], "mm": h["precipitation"][i], "wind": h["wind_speed_10m"][i],
                    "wdir": compass(h["wind_direction_10m"][i]), "sky": sky})
    return out

def met_norway(lat, lon, tz, metric=True):
    """Backup: MET Norway Locationforecast (free, keyless, CC BY 4.0; needs an identifying User-Agent)."""
    d = get(f"https://api.met.no/weatherapi/locationforecast/2.0/complete?lat={lat:.4f}&lon={lon:.4f}")
    now = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0); out = []
    for e in d["properties"]["timeseries"]:
        t = datetime.fromisoformat(e["time"].replace("Z", "+00:00"))
        n1 = e["data"].get("next_1_hours")
        if t < now or not n1: continue
        x = e["data"]["instant"]["details"]
        ws = x.get("wind_speed"); temp = x.get("air_temperature"); mm = n1["details"].get("precipitation_amount")
        if ws is not None: ws = ws * 3.6 if metric else ws * 2.23694
        if temp is not None and not metric: temp = temp * 9 / 5 + 32
        if mm is not None and not metric: mm /= 25.4
        pop = n1["details"].get("probability_of_precipitation")
        out.append({"t": t.astimezone(tz).replace(tzinfo=None), "temp": temp, "rh": x.get("relative_humidity"),
                    "pop": round(pop) if pop is not None else None, "mm": mm, "wind": ws,
                    "wdir": compass(x.get("wind_from_direction")), "sky": met_sky(n1["summary"]["symbol_code"])})
        if len(out) == 48: break
    return out

def forecast_world(loc, metric):
    """Open-Meteo, falling back to MET Norway. Returns (hours, source line)."""
    try: return om_hours(open_meteo(loc["lat"], loc["lon"], metric)), "Forecast data: Open-Meteo.com (CC BY 4.0)"
    except Exception as e:
        why = "daily request limit reached" if isinstance(e, urllib.error.HTTPError) and e.code == 429 else f"{e}"
        print(f"note: Open-Meteo unavailable ({why}); using MET Norway instead", file=sys.stderr)
    tz = ZoneInfo(loc["tz"]) if loc.get("tz") else timezone(timedelta(hours=round(loc["lon"] / 15)))
    return met_norway(loc["lat"], loc["lon"], tz, metric), "Forecast data: MET Norway (api.met.no, CC BY 4.0)"

def main(query):
    query = " ".join(query.split())
    if is_us_zip(query): return main_zip(query)
    try: loc = resolve(query)
    except LookupError_ as e: sys.exit(f"Couldn't look up \"{query}\" right now ({e}). Try again in a minute.")
    if not loc: sys.exit(f"Couldn't find a place called \"{query}\". Try a city name, \"city, country\", or a postal code with its country.")
    where = f"{loc['postal']} ({loc['label']})" if loc["postal"] else f"{loc['label']}"
    head = f"48-hour forecast for {where}"
    if loc["us"]:   # US place by name: same NWS forecast as the zip path, by coordinates
        try:
            pts = get(f"https://api.weather.gov/points/{loc['lat']:.4f},{loc['lon']:.4f}")["properties"]
            hourly = get(pts["forecastHourly"])["properties"]["periods"][:48]
            print(f"{head}\n"); print_nws(hourly); print("\nForecast data: US National Weather Service"); return
        except Exception as e: print(f"note: NWS unavailable here ({e}); using Open-Meteo", file=sys.stderr)
    try: hours, src = forecast_world(loc, metric=not loc["us"])
    except Exception as e: sys.exit(f"The forecast service is temporarily unavailable ({e}). Try again in a few minutes.")
    print(f"{head}\n"); print_blocks(hours, metric=not loc["us"]); print(f"\n{src}")

if __name__ == "__main__":
    main(" ".join(sys.argv[1:]) if len(sys.argv) > 1 else input("Zip code, city, or postal code: ").strip())
```

## zipradar.py
```python
#!/usr/bin/env python3
"""Animated precipitation GIF (+ MP4) for any location, 1280x720, zoom 9, centered on it.
US zip codes (and US places inside the NEXRAD composite): NEXRAD radar every 5 min for the past hour, then NOAA HRRR
forecast every 15 min out to +8 h. Everywhere else: RainViewer past radar every 10 min for the past hour, ending on
"Now" (RainViewer has no free forecast frames); skipped with a message where there is no radar coverage.
Free, no keys: Zippopotam / Open-Meteo geocoding, NWS (time zone), IEM tiles (radar/HRRR), RainViewer tiles
(personal use, credit RainViewer), OpenStreetMap basemap."""
import argparse, io, math, os, shutil, subprocess, sys, threading, time, requests
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from PIL import Image, ImageDraw, ImageChops, ImageEnhance, ImageFilter, ImageFont
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from wxlocate import is_us_zip, resolve, territory_zip, LookupError_

Z = 9                           # zoom 9: ~295 km across a 1280 px frame at 41N (native tiles, no resampling)
IEM = "https://mesonet.agron.iastate.edu"
TILE = IEM + "/cache/tile.py/1.0.0/{layer}/{{z}}/{{x}}/{{y}}.png"
OSM = "https://tile.openstreetmap.org/{z}/{x}/{y}.png"  # policy: identifying UA, light use, caching, attribution
CACHE = "/workspace/zipweather/cache"
S = requests.Session()
S.headers["User-Agent"] = "zipradar/3.0 (personal weather GIF script; tiles cached locally)"
S.mount("https://", requests.adapters.HTTPAdapter(pool_connections=4, pool_maxsize=16))
POOL = ThreadPoolExecutor(8)    # all tile fetches share this: at most 8 requests in flight (IEM), OSM limited to 2
OSM_SEM = threading.Semaphore(2)
LEGEND = [(94,173,207),(75,214,144),(15,183,20),(11,136,15),(9,94,9),(234,210,4),(255,177,0),(255,0,0),(177,0,0),(252,107,253)]
UTC = timezone.utc
HDR, FC, NOW, DOT = (20, 30, 50), (255, 225, 90), (130, 215, 255), (220, 20, 60)
TL_OBS, TL_FC, TL_BG = (40, 120, 200), (225, 150, 0), (215, 215, 215)   # timeline ticks on the white strip
FIXED = LEGEND + [HDR, FC, NOW, DOT, TL_OBS, TL_FC, TL_BG, (255, 255, 255), (0, 0, 0), (20, 20, 20), (60, 60, 60)]
MIN_IDX = 88                    # N0Q palette index for 12 dBZ (dBZ = idx/2 - 32); weaker echoes hidden

ALPHA_LUT = [0] * MIN_IDX + [204] * (256 - MIN_IDX)   # 80 % opacity for >= 12 dBZ
BAND_LUT = None  # filled from the N0Q palette: every 0.5-dBZ shade snapped to its 5-dBZ band colour (matches legend)
BANDS = [12] + list(range(15, 80, 5))                 # band lower edges, dBZ
BAND_FIXED = []
UNDER = (110, 190, 235)                              # basemap grey levels under precipitation
IEM_ATTR = "© OpenStreetMap contributors | Radar: NOAA NEXRAD/HRRR via IEM"

# ---- RainViewer (outside the NEXRAD composite): free public Weather Maps API, personal/educational use, credit
# RainViewer with a link. Since 2026: past 2 h every 10 min, max zoom 7, one colour scheme (Universal Blue),
# ~100 requests/IP/minute. 512-px zoom-7 tiles carry zoom-8 detail; frames are upscaled 2x to zoom 9.
RV_API = "https://api.rainviewer.com/public/weather-maps.json"
RV_ATTR = "© OpenStreetMap contributors | Radar: RainViewer (rainviewer.com)"
RV_Z = 7
RV_SEM = threading.Semaphore(3)
# Universal Blue rain colours (scheme 2, options 0_0) for dBZ 5..74 (below that is hidden anyway, 75+ is green)
RV_UB = ("928871 9e9375 aa9e79 b6a97e c2b482 cec087 d2c48b d6c88f dacc93 ded097 88ddee 6cd1eb 51c5e8 36bae5 1baee2 "
         "00a3e0 009ad5 0091ca 0088bf 007fb4 0077aa 0070a3 00699c 006295 005b8e 005588 005180 004e78 004a70 004768 "
         "ffee00 ffe000 ffd200 ffc500 ffb700 ffaa00 ff9f00 ff9500 ff8b00 ff8100 ff4400 f23600 e62800 d91b00 cd0d00 "
         "c10000 a80000 8f0000 760000 5d0000 ffaaff ff9fff ff95ff ff8bff ff81ff ff77ff ff6cff ff62ff ff58ff ff4eff "
         + "ffffff " * 10).split()
# NEXRAD N0Q colour at each band's lower edge (same as the US frames and legend)
N0Q_BAND = {12: (77, 125, 178), 15: (94, 173, 207), 20: (75, 214, 144), 25: (15, 183, 20), 30: (11, 136, 15),
            35: (9, 94, 9), 40: (234, 210, 4), 45: (255, 177, 0), 50: (255, 0, 0), 55: (177, 0, 0),
            60: (255, 245, 255), 65: (252, 107, 253), 70: (172, 0, 252), 75: (5, 235, 240)}

def set_bands(palbytes):
    global BAND_LUT
    cols = [tuple(palbytes[i * 3:i * 3 + 3]) for i in range(256)]
    lut = []
    for i in range(256):
        dbz = i / 2 - 32
        edge = max([b for b in BANDS if b <= dbz], default=None)
        lut.append(cols[int((edge + 32) * 2)] if edge is not None else cols[i])
    BAND_LUT = [[c[k] for c in lut] for k in range(3)]
    # palette anchors: each band as it looks over the faded basemap, so no band merges into a neighbour in the GIF
    for b in BANDS:
        c = cols[int((b + 32) * 2)]
        for g in UNDER: BAND_FIXED.append(tuple(round((v * 204 + g * 51) / 255) for v in c))

def get(url, **kw):
    for i in range(3):  # retry network hiccups; HTTP errors (e.g. 503 = not processed yet) raise at once
        try: r = S.get(url, timeout=20, **kw); break
        except (requests.ConnectionError, requests.Timeout):
            if i == 2: raise
            time.sleep(2)
    r.raise_for_status(); return r

def font(sz, bold=False):
    try: return ImageFont.truetype(f"/usr/share/fonts/truetype/dejavu/DejaVuSans{'-Bold' if bold else ''}.ttf", sz)
    except OSError: return ImageFont.load_default(sz)

MEM = {}  # in-memory tile cache: every tile is fetched at most once per run
def tile_bytes(url, cache_path=None, max_age=None):
    if url in MEM: return MEM[url]
    if cache_path and os.path.exists(cache_path) and (max_age is None or time.time() - os.path.getmtime(cache_path) < max_age):
        with open(cache_path, "rb") as f: MEM[url] = f.read(); return MEM[url]
    if "openstreetmap" in url:
        with OSM_SEM: data = get(url).content
    else: data = get(url).content
    if cache_path:
        os.makedirs(os.path.dirname(cache_path), exist_ok=True)
        tmp = f"{cache_path}.{threading.get_ident()}.tmp"
        with open(tmp, "wb") as f: f.write(data)
        os.replace(tmp, cache_path)
    MEM[url] = data; return data

def purge_cache():
    """Drop IEM radar/HRRR tiles older than a day and OSM tiles older than 30 days."""
    for sub, age in (("iem", 86400), ("osm", 30 * 86400), ("rainviewer", 86400), ("rvcov", 30 * 86400)):
        root = os.path.join(CACHE, sub)
        for dp, _, fs in os.walk(root, topdown=False):
            for fn in fs:
                p = os.path.join(dp, fn)
                try:
                    if time.time() - os.path.getmtime(p) > age: os.remove(p)
                except OSError: pass
            if dp != root:
                try: os.rmdir(dp)
                except OSError: pass

class Grid:
    def __init__(self, cx, cy, w, h):
        self.x0, self.y0, self.w, self.h = int(cx - w / 2), int(cy - h / 2), w, h
        self.tiles = [(tx, ty) for tx in range(self.x0 // 256, (self.x0 + w - 1) // 256 + 1)
                      for ty in range(self.y0 // 256, (self.y0 + h - 1) // 256 + 1)]

def mosaic(grid, fmt, cache_dir=None, max_age=None, pal=None):
    """Stitch the grid's XYZ tiles in parallel (shared bounded pool). pal: hide echoes below 12 dBZ."""
    def fetch(t):
        url = fmt.format(z=Z, x=t[0] % 2 ** Z, y=t[1])   # x wraps at the antimeridian
        cp = os.path.join(cache_dir, str(Z), str(t[0] % 2 ** Z), f"{t[1]}.png") if cache_dir else None
        im = Image.open(io.BytesIO(tile_bytes(url, cp, max_age))).convert("RGBA")
        if pal is not None:  # per tile, in the worker thread: dBZ index -> 5-dBZ band colour, 80 % alpha, < 12 dBZ hidden
            a = im.getchannel("A")
            if a.getbbox():
                idx = Image.frombytes("L", im.size, im.convert("RGB").quantize(palette=pal, dither=Image.Dither.NONE).tobytes())
                a = ImageChops.multiply(a, idx.point(ALPHA_LUT))
                if BAND_LUT: im = Image.merge("RGBA", [idx.point(BAND_LUT[c]) for c in range(3)] + [a])
                else: im.putalpha(a)
        return im
    img = Image.new("RGBA", (grid.w, grid.h), (0, 0, 0, 0))
    for (tx, ty), im in zip(grid.tiles, POOL.map(fetch, grid.tiles)):
        img.paste(im, (tx * 256 - grid.x0, ty * 256 - grid.y0))
    return img

def ok(url):
    try: return S.get(url, timeout=20).status_code == 200
    except requests.RequestException: return False

def layer_dir(layer): return os.path.join(CACHE, "iem", layer.replace(":", "_"))

def render(m, lab, kind, i, kinds, name, place, zipcode, attr=IEM_ATTR, note=None):
    """Draw header, marker, legend, timeline and attribution on a copy of map frame m, scaled to its size."""
    W, H = m.size; s = W / 640
    im = m.copy(); d = ImageDraw.Draw(im)
    f1, f2, f3, fm = font(round(17 * s), True), font(round(13 * s), True), font(round(10 * s)), font(round(14 * s), True)
    hh, fh = round(28 * s), round(22 * s)
    d.rectangle((0, 0, W, hh), fill=HDR)
    d.text((round(8 * s), hh // 2), f"Precipitation · {name} {zipcode}".rstrip(), font=f2, fill="white", anchor="lm")
    if note:  # e.g. "Grey: no radar coverage", small tag under the header
        nb = d.textbbox((round(8 * s), hh + round(5 * s)), note, font=f3)
        d.rectangle((nb[0] - round(3 * s), nb[1] - round(2 * s), nb[2] + round(3 * s), nb[3] + round(2 * s)), fill="white")
        d.text((round(8 * s), hh + round(5 * s)), note, font=f3, fill=(60, 60, 60))
    d.text((W - round(8 * s), hh // 2), lab, font=f1, fill=FC if kind == "fc" else NOW, anchor="rm")
    ix, iy, r = W // 2, H // 2, round(6 * s)
    d.ellipse((ix - r, iy - r, ix + r, iy + r), fill=DOT, outline="white", width=max(2, round(2 * s)))
    d.text((ix + r + round(4 * s), iy), place, font=fm, fill=(20, 20, 20), stroke_width=max(3, round(3 * s)), stroke_fill="white", anchor="lm")
    d.rectangle((0, H - fh, W, H), fill="white")
    ty = H - fh // 2; sw, sh = round(14 * s), round(10 * s)
    x = round(6 * s); d.text((x, ty), "Light", font=f3, fill="black", anchor="lm")
    x += round(d.textlength("Light", font=f3)) + round(5 * s)
    for c in LEGEND: d.rectangle((x, ty - sh // 2, x + sw - 1, ty + sh // 2), fill=c); x += sw
    x += round(5 * s); d.text((x, ty), "Heavy", font=f3, fill="black", anchor="lm")
    x += round(d.textlength("Heavy", font=f3))
    d.text((W - round(6 * s), ty), attr, font=f3, fill=(60, 60, 60), anchor="rm")
    # timeline: full-width strip above the legend, one segment per frame (radar blue, forecast orange, current black)
    th, gap, step = round(4 * s), max(1, round(s)), W / len(kinds)
    for k, kd in enumerate(kinds):
        a, b = round(k * step), round((k + 1) * step) - gap - 1
        col = "black" if k == i else (TL_OBS if kd == "obs" else TL_FC) if k < i else TL_BG
        d.rectangle((a, H - fh - th - (th // 2 if k == i else 0), max(a, b), H - fh - 1), fill=col)
    return im.convert("RGB")

def save_gif(frames, durations, out, ncol=255):
    """Shared 255-colour palette (index 255 left free for Pillow's transparent frame deltas)."""
    W, H = frames[0].size
    sample = frames[::max(1, len(frames) // 12)]
    sheet = Image.new("RGB", (W // 2, H // 2 * len(sample)))
    for i, im in enumerate(sample): sheet.paste(im.resize((W // 2, H // 2), Image.Resampling.NEAREST), (0, H // 2 * i))
    fixed = FIXED + [c for c in BAND_FIXED if c not in FIXED]
    n = min(ncol, 255) - len(fixed)
    q = sheet.quantize(n, method=Image.Quantize.MEDIANCUT)
    gpal = Image.new("P", (1, 1)); gpal.putpalette(q.getpalette()[:3 * n] + [v for c in fixed for v in c])
    pf = list(POOL.map(lambda im: im.quantize(palette=gpal, dither=Image.Dither.NONE), frames))
    pf[0].save(out, save_all=True, append_images=pf[1:], duration=durations, loop=0, optimize=True, disposal=1)
    return os.path.getsize(out)

def find_ffmpeg():
    exe = shutil.which("ffmpeg")
    if exe: return exe
    try:
        import imageio_ffmpeg; return imageio_ffmpeg.get_ffmpeg_exe()
    except Exception: return None

def save_mp4(frames, durations, out, fps=20):
    exe = find_ffmpeg()
    if not exe: print("note: ffmpeg not found; skipped MP4 (pip install imageio-ffmpeg to enable)", file=sys.stderr); return None
    W, H = frames[0].size
    cmd = [exe, "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{W}x{H}", "-r", str(fps), "-i", "-",
           "-c:v", "libx264", "-preset", "slow", "-crf", "23", "-tune", "animation", "-pix_fmt", "yuv420p",
           "-profile:v", "high", "-movflags", "+faststart", out]
    p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
    try:
        for im, ms in zip(frames, durations):
            b = im.tobytes()
            for _ in range(max(1, round(ms * fps / 1000))): p.stdin.write(b)
        p.stdin.close()
    except BrokenPipeError: pass
    if p.wait() != 0: print("warning: ffmpeg failed; no MP4", file

…(truncated)
