Fichiers
meteo-vercors/collecte/importer_opendata.py
T

94 lignes
4.3 KiB
Python

#!/usr/bin/env python3
"""Importe l'historique horaire Météo-France (open data data.gouv.fr, « Données climatologiques de base - horaires »)
des postes du Vercors dans la base d'archive de vercors.me (table `horaire`, un point par heure, jamais purgé).
Fichiers : H_<département>_<période>.csv.gz, séparateur « ; », déjà téléchargés dans un dossier.
https://object.files.data.gouv.fr/meteofrance/data/synchro_ftp/BASE/HOR/H_38_latest-2025-2026.csv.gz (idem 26, et les décennies)
Ce script ne télécharge rien. Licence Ouverte Etalab 2.0, source Météo-France.
Usage : python importer_opendata.py --db archive/vercors.db --dossier od/
Les fichiers « latest » s'arrêtent plusieurs mois avant aujourd'hui : l'API temps réel (6 min) couvre les 5 derniers jours ;
le trou entre les deux est à combler avec l'API climatologique (DPClim) si Théo s'y abonne.
"""
import argparse
import csv
import datetime as dt
import glob
import gzip
import os
import sqlite3
import sys
POSTES = {"38021001": "autrans", "38548001": "villard", "26074001": "chapelle",
"26290002": "rousset", "38186001": "gresse", "26307001": "st-jean"}
# colonne de la base <- colonne Météo-France
CHAMPS = (("t", "T"), ("tn", "TN"), ("tx", "TX"), ("td", "TD"), ("u", "U"), ("ff", "FF"), ("fxi", "FXI"),
("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 (
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,
PRIMARY KEY (id, ts)) WITHOUT ROWID"""
def nombre(v):
try:
return float(v) if v not in ("", None) else None
except ValueError:
return None
def epoch(aaaammjjhh):
d = dt.datetime.strptime(aaaammjjhh, "%Y%m%d%H").replace(tzinfo=dt.timezone.utc)
return int(d.timestamp())
def importer_fichier(db, chemin, tout_vercors=False):
cols = [c for c, _ in CHAMPS]
sql = ("INSERT OR REPLACE INTO horaire (id, ts, %s) VALUES (?, ?, %s)" % (", ".join(cols), ", ".join("?" * len(cols))))
n = 0
with gzip.open(chemin, "rt", encoding="utf-8") as f:
for row in csv.DictReader(f, delimiter=";"):
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"):
continue
db.execute(sql, [site, epoch(row["AAAAMMJJHH"])] + [nombre(row.get(src)) for _, src in CHAMPS])
n += 1
db.commit()
return n
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--db", 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)
db = sqlite3.connect(os.path.expanduser(a.db), timeout=120)
db.execute(SCHEMA)
db.execute(SCHEMA_POSTES)
total = 0
for chemin in sorted(glob.glob(os.path.join(os.path.expanduser(a.dossier), "H_*.csv.gz"))):
n = importer_fichier(db, chemin, a.tout_vercors)
total += 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"):
f = lambda t: dt.datetime.fromtimestamp(t, dt.timezone.utc).strftime("%Y-%m-%d")
print(" %s : %d heures, du %s au %s" % (site, nb, f(mini), f(maxi)))
return 0
if __name__ == "__main__":
sys.exit(main())