#!/usr/bin/env python3 """Extrait les stations du Vercors du fichier Infoclimat déjà collecté sur le LAN (meteo-direct/www/direct.json) -> JSON public filtré (public/data/infoclimat.json), même format que meteo.json et meteofrance.json. Aucun appel réseau : la collecte Infoclimat tourne ailleurs (cron recuperer.sh, toutes les 5 min). On garde les 24 dernières heures, seulement les champs publics, sans valeur vide. Usage : python extraire_infoclimat.py --source ~/services/meteo-direct/www/direct.json --sortie CHEMIN Licences : celles d'Infoclimat, station par station (CC BY ou CC BY-NC) ; recopiées dans les métadonnées. """ import argparse import datetime as dt import json import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from collecter_weatherlink import CHAMPS_PUBLICS, charger_json, ecrire_atomique, maintenant, verifier_public # noqa: E402 RACINE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SORTIE_DEFAUT = os.path.join(RACINE, "public", "data", "infoclimat.json") HORS_LIGNE_MIN = 40 # Infoclimat publie toutes les 10 min, avec du retard # identifiant du site -> identifiant Infoclimat (ou VP2 : station Gastinel, passée par le même fichier) STATIONS = { "bruyeres": "000T0", "allieres": "000GS", "engins": "000HT", "meaudre": "000IA", "geve": "000IL", "lans": "VP2", "moucherolle": "STATIC0479", "darbounouse": "STATIC0213", "oscence": "000UF", "die": "000PD", "st-julien-q": "000OS", "archiane": "000ZK", # retirées le 04/11 (pas d'autorisation) : rochechinard STATIC0238, marignac STATIC0203, solaure STATIC0323 } def lire_date(s): return dt.datetime.strptime(s[:19], "%Y-%m-%d %H:%M:%S").replace(tzinfo=dt.timezone.utc) def extraire(source, fin, heures=24): stations, meta, journal = {}, {}, [] sts, metas = source.get("stations", {}), source.get("metadonnees", {}) debut = fin - dt.timedelta(hours=heures) for sid, ic in STATIONS.items(): st, m = sts.get(ic, {}), metas.get(ic, {}) rel = [] for r in st.get("releves", []) if isinstance(st.get("releves"), list) else []: if not isinstance(r, dict) or not isinstance(r.get("dh_utc"), str) or r.get("temperature") is None: continue if lire_date(r["dh_utc"]) <= debut: continue rel.append({k: r[k] for k in CHAMPS_PUBLICS if r.get(k) is not None and k not in ("temperature_min", "temperature_max")}) rel.sort(key=lambda r: r["dh_utc"]) if rel: ts = [r["temperature"] for r in rel] rel[-1]["temperature_min"], rel[-1]["temperature_max"] = min(ts), max(ts) hors_ligne = not rel or fin - lire_date(rel[-1]["dh_utc"]) > dt.timedelta(minutes=HORS_LIGNE_MIN) source_st = "Station Gastinel" if ic == "VP2" else "Infoclimat" stations[sid] = {"nom": st.get("nom", sid), "source": source_st, "hors_ligne": hors_ligne, "releves": rel} meta[sid] = {"licence": m.get("licence") or ("" if ic == "VP2" else "Infoclimat")} journal.append("%s: %s (%d relevés)" % (sid, "hors ligne" if hors_ligne else "ok", len(rel))) obj = {"source": "Infoclimat (licences CC BY ou CC BY-NC selon la station)", "mis_a_jour_utc": fin.strftime("%Y-%m-%dT%H:%M:%SZ"), "metadonnees": meta, "stations": stations} return obj, journal def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--source", required=True) ap.add_argument("--sortie", default=SORTIE_DEFAUT) ap.add_argument("--heures", type=float, default=24.0) a = ap.parse_args(argv) source = charger_json(os.path.expanduser(a.source)) if not source.get("stations"): print("source illisible ou vide : rien écrit") return 1 obj, journal = extraire(source, maintenant(), a.heures) verifier_public(obj) ecrire_atomique(os.path.expanduser(a.sortie), obj) print("écrit : %s (%d stations)" % (os.path.basename(a.sortie), len(obj["stations"]))) print("; ".join(journal)) return 0 if __name__ == "__main__": sys.exit(main())