collecte : import de l'historique Infoclimat (hdd3, lecture seule) et option --tout-vercors pour l'open data Météo-France

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cette révision appartient à :
Théo GastineletClaude Opus 5.5 a révisé 2026-11-04 15:12:19 +01:00
1 Parent 6ec2910d76
révision c671a363c7
2 fichiers modifiés
+97 -4

Aucun fichier ne correspond à votre recherche

+79
Voir le fichier
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Importe l'historique Infoclimat des stations du Vercors depuis la collecte GWS (lecture seule) dans l'archive.
Source : /mnt/hdd3/gws-meteo/infoclimat/<id Infoclimat>/*.json.gz (clé "hourly" : {id: [relevés]}, valeurs en texte).
Cible : base SQLite de l'archive (table obs, pas de 10 min), via archiver_historique.ingerer :
une valeur vide n'écrase jamais une valeur connue, ré-import sans doublon.
Usage : python3 importer_infoclimat_hdd3.py --db ~/meteo-vercors/archive/vercors.db [--source /mnt/hdd3/gws-meteo/infoclimat]
"""
import argparse
import gzip
import json
import os
import sys
import time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import archiver_historique as arch # noqa: E402
from extraire_infoclimat import STATIONS # noqa: E402
def nombre(v):
try:
return float(v)
except (TypeError, ValueError):
return None
def releves(fichier, id_ic):
with gzip.open(fichier, "rt", encoding="utf-8") as f:
d = json.load(f)
lignes = (d.get("hourly") or {}).get(id_ic) or []
out = []
for r in lignes:
if not isinstance(r, dict) or not isinstance(r.get("dh_utc"), str):
continue
out.append({k: (v if k == "dh_utc" else nombre(v)) for k, v in r.items()})
return out
def main(argv=None):
ap = argparse.ArgumentParser()
ap.add_argument("--db", required=True)
ap.add_argument("--source", default="/mnt/hdd3/gws-meteo/infoclimat")
a = ap.parse_args(argv)
db = arch.ouvrir(a.db)
db.execute("PRAGMA busy_timeout = 60000") # le minuteur écrit aussi dans la base toutes les 6 min
total = 0
for site, id_ic in STATIONS.items():
dossier = os.path.join(a.source, id_ic)
if not os.path.isdir(dossier):
print("%-13s %-11s aucun dossier" % (site, id_ic))
continue
n_site, premier = 0, None
for nom in sorted(os.listdir(dossier)):
if not nom.endswith(".json.gz"):
continue
try:
rs = releves(os.path.join(dossier, nom), id_ic)
except (OSError, ValueError, EOFError) as e:
print(" illisible :", id_ic, nom, type(e).__name__)
continue
if rs and premier is None:
premier = rs[0]["dh_utc"][:10]
for essai in range(5):
try:
n_site += arch.ingerer(db, {"stations": {site: {"releves": rs}}})
break
except Exception as e: # base occupée par le minuteur : on réessaie
if "locked" not in str(e) or essai == 4:
raise
time.sleep(5)
total += n_site
print("%-13s %-11s %8d relevés, depuis %s" % (site, id_ic, n_site, premier or "—"), flush=True)
print("total :", total)
return 0
if __name__ == "__main__":
sys.exit(main())
+18 -4
Voir le fichier
@@ -24,6 +24,10 @@ POSTES = {"38021001": "autrans", "38548001": "villard", "26074001": "chapelle",
# colonne de la base <- colonne Météo-France # colonne de la base <- colonne Météo-France
CHAMPS = (("t", "T"), ("tn", "TN"), ("tx", "TX"), ("td", "TD"), ("u", "U"), ("ff", "FF"), ("fxi", "FXI"), CHAMPS = (("t", "T"), ("tn", "TN"), ("tx", "TX"), ("td", "TD"), ("u", "U"), ("ff", "FF"), ("fxi", "FXI"),
("dd", "DD"), ("rr1", "RR1"), ("pmer", "PMER"), ("neige", "NEIGETOT")) ("dd", "DD"), ("rr1", "RR1"), ("pmer", "PMER"), ("neige", "NEIGETOT"))
# --tout-vercors : tous les postes Météo-France situés dans le Parc (cadre ouest, nord, est, sud), id « mf-<NUM_POSTE> »
CADRE_VERCORS = (5.06, 45.305, 5.835, 44.635)
SCHEMA_POSTES = """CREATE TABLE IF NOT EXISTS postes_mf (
id TEXT PRIMARY KEY, num TEXT, nom TEXT, lat REAL, lon REAL, alti REAL)"""
SCHEMA = """CREATE TABLE IF NOT EXISTS horaire ( SCHEMA = """CREATE TABLE IF NOT EXISTS horaire (
id TEXT NOT NULL, ts INTEGER NOT NULL, id TEXT NOT NULL, ts INTEGER NOT NULL,
t REAL, tn REAL, tx REAL, td REAL, u REAL, ff REAL, fxi REAL, dd REAL, rr1 REAL, pmer REAL, neige REAL, t REAL, tn REAL, tx REAL, td REAL, u REAL, ff REAL, fxi REAL, dd REAL, rr1 REAL, pmer REAL, neige REAL,
@@ -42,13 +46,21 @@ def epoch(aaaammjjhh):
return int(d.timestamp()) return int(d.timestamp())
def importer_fichier(db, chemin): def importer_fichier(db, chemin, tout_vercors=False):
cols = [c for c, _ in CHAMPS] cols = [c for c, _ in CHAMPS]
sql = ("INSERT OR REPLACE INTO horaire (id, ts, %s) VALUES (?, ?, %s)" % (", ".join(cols), ", ".join("?" * len(cols)))) sql = ("INSERT OR REPLACE INTO horaire (id, ts, %s) VALUES (?, ?, %s)" % (", ".join(cols), ", ".join("?" * len(cols))))
n = 0 n = 0
with gzip.open(chemin, "rt", encoding="utf-8") as f: with gzip.open(chemin, "rt", encoding="utf-8") as f:
for row in csv.DictReader(f, delimiter=";"): for row in csv.DictReader(f, delimiter=";"):
site = POSTES.get(row.get("NUM_POSTE")) num = row.get("NUM_POSTE")
site = POSTES.get(num)
if not site and tout_vercors:
lat, lon = nombre(row.get("LAT")), nombre(row.get("LON"))
o, nord, e, sud = CADRE_VERCORS
if lat is not None and lon is not None and o <= lon <= e and sud <= lat <= nord:
site = "mf-" + num
db.execute("INSERT OR IGNORE INTO postes_mf VALUES (?, ?, ?, ?, ?, ?)",
(site, num, row.get("NOM_USUEL"), lat, lon, nombre(row.get("ALTI"))))
if not site or not row.get("AAAAMMJJHH"): if not site or not row.get("AAAAMMJJHH"):
continue continue
db.execute(sql, [site, epoch(row["AAAAMMJJHH"])] + [nombre(row.get(src)) for _, src in CHAMPS]) db.execute(sql, [site, epoch(row["AAAAMMJJHH"])] + [nombre(row.get(src)) for _, src in CHAMPS])
@@ -61,12 +73,14 @@ def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--db", required=True) ap.add_argument("--db", required=True)
ap.add_argument("--dossier", required=True) ap.add_argument("--dossier", required=True)
ap.add_argument("--tout-vercors", action="store_true", help="tous les postes du Parc, pas seulement les 6 de la carte")
a = ap.parse_args(argv) a = ap.parse_args(argv)
db = sqlite3.connect(os.path.expanduser(a.db)) db = sqlite3.connect(os.path.expanduser(a.db), timeout=120)
db.execute(SCHEMA) db.execute(SCHEMA)
db.execute(SCHEMA_POSTES)
total = 0 total = 0
for chemin in sorted(glob.glob(os.path.join(os.path.expanduser(a.dossier), "H_*.csv.gz"))): for chemin in sorted(glob.glob(os.path.join(os.path.expanduser(a.dossier), "H_*.csv.gz"))):
n = importer_fichier(db, chemin) n = importer_fichier(db, chemin, a.tout_vercors)
total += n total += n
print("%s : %d heures" % (os.path.basename(chemin), n)) print("%s : %d heures" % (os.path.basename(chemin), n))
for site, mini, maxi, nb in db.execute("SELECT id, MIN(ts), MAX(ts), COUNT(*) FROM horaire GROUP BY id"): for site, mini, maxi, nb in db.execute("SELECT id, MIN(ts), MAX(ts), COUNT(*) FROM horaire GROUP BY id"):