SPB Git

Repository Public

common.py 13.8 KB 343 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : ORIX Cosmos10# File             : DataPipeline/catalogs/common.py11# Description      : Shared helpers of the catalogue pipeline: polite cached12#                    HTTP, resumable asynchronous TAP jobs, schema checks that13#                    fail loudly, SHA-256, retrieval records. Standard library14#                    only.15# Module           : DataPipeline16# Repository       : https://git.spboucher.ai/orix-cosmos17# Project Website  : https://www.orixlab.dev18# Created          : 2026-11-2419# Last Modified    : 2026-11-2420#21# =============================================================================22# AUTHOR & PROFESSIONAL AFFILIATION23# =============================================================================24#25# Author           : Simon-Pierre Boucher26# Position         : Professor of Finance27# Institution      : Université du Québec en Outaouais (UQO)28# Department       : Département des sciences administratives29# Organization     : SP Boucher30#31# Website          : https://spboucher.ai32# Git              : https://git.spboucher.ai33#34# =============================================================================35# OFFICIAL CONTACT DIRECTORY36# =============================================================================37#38# General          : info@spboucher.ai39# Professional     : contact@spboucher.ai40# Direct           : simon@spboucher.ai41# Research         : research@spboucher.ai42# Development      : dev@spboucher.ai43# Support          : support@spboucher.ai44# Security/Admin   : admin@spboucher.ai45# Notifications    : notifications@spboucher.ai46#47# Preferred Contact: support@spboucher.ai48#49# =============================================================================50# COPYRIGHT & INTELLECTUAL PROPERTY51# =============================================================================52#53# Copyright (c) 202654# Simon-Pierre Boucher55#56# All rights reserved where applicable.57#58# This file is governed by the applicable project license,59# copyright notices, institutional agreements and relevant law.60#61# Unless expressly authorized by the applicable license or62# rights holder, copying, redistribution, sublicensing,63# publication and commercial exploitation are not permitted.64#65# Existing third-party rights and notices remain unaffected.66#67# =============================================================================68# CONFIDENTIALITY & SECURITY69# =============================================================================70#71# Classification   : Public72# Distribution     : Public repository; use is governed by the project license73# Security Contact : admin@spboucher.ai74#75# Access to this source does not independently grant permission76# to redistribute or disclose confidential materials.77#78# Do not embed credentials, private keys, access tokens,79# certificates or confidential personal information.80#81# =============================================================================82# LICENSE & MAINTENANCE83# =============================================================================84#85# License          : None specified (no license file in this repository)86# Maintainer       : Simon-Pierre Boucher87# Technical Contact: dev@spboucher.ai88#89# =============================================================================90# END OF SP BOUCHER SOURCE HEADER91# =============================================================================9293"""Catalogue pipeline helpers.9495Every raw response is cached under DataPipeline/raw/catalogs/<source>/ (git-ignored) next to a96`<file>.meta.json` holding the URL or query, the retrieval date (UTC) and the SHA-256 of the bytes. A script that97is run again reuses the cache, so an interrupted batch resumes where it stopped and a build is reproducible from98the cached raw files. Requests carry a generic User-Agent and no personal data.99"""100import csv101import datetime102import hashlib103import io104import json105import os106import sys107import time108import urllib.error109import urllib.parse110import urllib.request111112USER_AGENT = "orix-cosmos-pipeline/1.0"113ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".."))114RAW = os.path.join(ROOT, "DataPipeline", "raw", "catalogs")115OUT = os.path.join(ROOT, "DataPipeline", "out", "catalogs")116PACKS = os.environ.get("COSMOS_PACKS_DIR", os.path.join(ROOT, "Resources", "Packs"))117118119class SchemaError(RuntimeError):120    """The source no longer has the columns/units this adapter was written for."""121122123def log(*a):124    print(time.strftime("%H:%M:%S"), *a, file=sys.stderr, flush=True)125126127def sha256_file(path):128    h = hashlib.sha256()129    with open(path, "rb") as f:130        for chunk in iter(lambda: f.read(1 << 20), b""):131            h.update(chunk)132    return h.hexdigest()133134135def raw_path(source, name):136    d = os.path.join(RAW, source)137    os.makedirs(d, exist_ok=True)138    return os.path.join(d, name)139140141def read_meta(path):142    with open(path + ".meta.json", encoding="utf-8") as f:143        return json.load(f)144145146def _write_meta(path, what):147    meta = dict(what)148    meta["retrieved_utc"] = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")149    meta["bytes"] = os.path.getsize(path)150    meta["sha256"] = sha256_file(path)151    with open(path + ".meta.json", "w", encoding="utf-8") as f:152        json.dump(meta, f, indent=1, sort_keys=True)153    return meta154155156def _open(url, data=None, timeout=300):157    req = urllib.request.Request(url, data=data, headers={"User-Agent": USER_AGENT})158    return urllib.request.urlopen(req, timeout=timeout)159160161def fetch(source, name, url, post=None, retries=3, stop_on=(301, 403, 404), timeout=600):162    """Downloads `url` once into the raw cache and returns the local path. An HTTP status in `stop_on`163    is never retried (CelesTrak's usage policy: such an answer does not change by repeating the request)."""164    path = raw_path(source, name)165    if os.path.exists(path) and os.path.exists(path + ".meta.json"):166        return path167    data = urllib.parse.urlencode(post).encode() if post else None168    err = None169    for attempt in range(retries):170        try:171            log("GET", url if not post else url + " [POST]")172            with _open(url, data, timeout) as resp, open(path + ".part", "wb") as out:173                while True:174                    chunk = resp.read(1 << 20)175                    if not chunk:176                        break177                    out.write(chunk)178            os.replace(path + ".part", path)179            _write_meta(path, {"url": url, "post": post})180            return path181        except urllib.error.HTTPError as exc:182            if exc.code in stop_on:183                raise RuntimeError("HTTP %d for %s: not retried, report to a human" % (exc.code, url)) from exc184            err = exc185        except Exception as exc:  # network trouble: back off and retry186            err = exc187        time.sleep(5 * (attempt + 1))188    raise RuntimeError("download failed for %s: %s" % (url, err))189190191def tap_sync(source, name, endpoint, adql, fmt="csv", maxrec=None, row_limit=None, expected=None, timeout=900):192    """Synchronous TAP query, cached. The answer is accepted only if its first line carries the `expected`193    column names (an error document or a time-out page is rejected) and it has fewer than `row_limit` rows."""194    path = raw_path(source, name)195    if os.path.exists(path) and os.path.exists(path + ".meta.json"):196        return path197    form = {"REQUEST": "doQuery", "LANG": "ADQL", "FORMAT": fmt, "QUERY": adql}198    if maxrec:199        form["MAXREC"] = str(maxrec)200    log("TAP sync", name)201    try:202        with _open(endpoint.rstrip("/") + "/sync", urllib.parse.urlencode(form).encode(), timeout) as resp, \203                open(path + ".part", "wb") as out:204            while True:205                chunk = resp.read(1 << 20)206                if not chunk:207                    break208                out.write(chunk)209    except Exception as exc:210        raise RuntimeError("TAP sync failed for %s: %s" % (name, exc)) from exc211    with open(path + ".part", "rb") as f:212        header = f.readline().decode("utf-8", "replace").strip().split(",")213        rows = sum(chunk.count(b"\n") for chunk in iter(lambda: f.read(1 << 20), b""))214    if expected and [c for c in expected if c not in header]:215        with open(path + ".part", "rb") as f:216            head = f.read(600).decode("utf-8", "replace")217        os.remove(path + ".part")218        raise RuntimeError("TAP sync %s: not the expected table (service error or time-out): %s" % (name, head))219    if row_limit and rows >= row_limit:220        os.remove(path + ".part")221        raise RowLimit("%s: %d rows reach the row limit %d (truncated answer discarded)" % (name, rows, row_limit))222    os.replace(path + ".part", path)223    _write_meta(path, {"url": endpoint, "adql": adql, "mode": "sync"})224    return path225226227class RowLimit(RuntimeError):228    """The answer has as many rows as the service allows: it is truncated and must not be used."""229230231def tap_async(source, name, endpoint, adql, fmt="csv", poll_s=10, max_wait_s=6 * 3600, maxrec=None, row_limit=None):232    """Runs an asynchronous TAP job (UWS). The job URL is written to `<file>.job` so that a re-run after an233    interruption polls the same job instead of submitting a new one. `maxrec` is sent as MAXREC; an answer with234    `row_limit` rows or more is treated as truncated: it is discarded and RowLimit is raised."""235    path = raw_path(source, name)236    if os.path.exists(path) and os.path.exists(path + ".meta.json"):237        return path238    jobfile = path + ".job"239    job = None240    if os.path.exists(jobfile):241        with open(jobfile) as f:242            saved = json.load(f)243        if saved.get("adql") == adql:244            job = saved["job"]245    if job is None:246        form = {"REQUEST": "doQuery", "LANG": "ADQL", "FORMAT": fmt, "PHASE": "RUN", "QUERY": adql}247        if maxrec:248            form["MAXREC"] = str(maxrec)249        data = urllib.parse.urlencode(form).encode()250        with _open(endpoint.rstrip("/") + "/async", data) as resp:251            job = resp.geturl()252        with open(jobfile, "w") as f:253            json.dump({"job": job, "adql": adql}, f)254        log("TAP job submitted", job)255    start = time.time()256    while True:257        try:258            with _open(job + "/phase", timeout=120) as resp:259                phase = resp.read().decode().strip()260        except urllib.error.HTTPError as exc:261            if exc.code == 404:  # job expired on the server: forget it and resubmit on the next run262                os.remove(jobfile)263                raise RuntimeError("TAP job vanished (%s); run again to resubmit" % job) from exc264            raise265        if phase == "COMPLETED":266            break267        if phase == "PENDING":  # some services (DaCHS) create the job without starting it268            with _open(job + "/phase", urllib.parse.urlencode({"PHASE": "RUN"}).encode(), timeout=120) as resp:269                resp.read()270            time.sleep(2)271            continue272        if phase in ("ERROR", "ABORTED"):273            detail = ""274            try:275                with _open(job + "/error", timeout=120) as resp:276                    detail = resp.read().decode("utf-8", "replace")[:2000]277            except Exception:278                pass279            os.remove(jobfile)280            raise RuntimeError("TAP job %s ended in phase %s: %s" % (job, phase, detail))281        if time.time() - start > max_wait_s:282            raise RuntimeError("TAP job %s still %s after %d s; run again to resume" % (job, phase, max_wait_s))283        time.sleep(poll_s)284    log("TAP job completed, downloading", name)285    with _open(job + "/results/result", timeout=3600) as resp, open(path + ".part", "wb") as out:286        while True:287            chunk = resp.read(1 << 20)288            if not chunk:289                break290            out.write(chunk)291    os.remove(jobfile)292    if row_limit:293        with open(path + ".part", "rb") as f:294            rows = sum(chunk.count(b"\n") for chunk in iter(lambda: f.read(1 << 20), b"")) - 1295        if rows >= row_limit:296            os.remove(path + ".part")297            raise RowLimit("%s: %d rows reach the row limit %d (truncated answer discarded)" % (name, rows, row_limit))298    os.replace(path + ".part", path)299    _write_meta(path, {"url": endpoint, "adql": adql, "job": job})300    return path301302303def read_csv(path, expected, delimiter=","):304    """Yields dict rows of a CSV file after checking that every expected column is present.305    Lines starting with '#' (IPAC/VizieR comments) are skipped."""306    with open(path, encoding="utf-8", newline="") as f:307        lines = (line for line in f if not line.startswith("#"))308        reader = csv.DictReader(lines, delimiter=delimiter)309        missing = [c for c in expected if c not in (reader.fieldnames or [])]310        if missing:311            raise SchemaError("%s: missing columns %s (got %s)" % (path, missing, reader.fieldnames))312        for row in reader:313            yield row314315316def fnum(text):317    """Float or None. Empty, 'null', 'nan' are None: an unknown value is never turned into 0."""318    if text is None:319        return None320    t = text.strip()321    if t == "" or t.lower() in ("null", "nan", "none", "--", "_"):322        return None323    v = float(t)324    if v != v:325        return None326    return v327328329def inum(text):330    v = fnum(text)331    return None if v is None else int(v)332333334def retrieved_date(path):335    return read_meta(path)["retrieved_utc"][:10]336337338def write_json(path, obj):339    os.makedirs(os.path.dirname(path), exist_ok=True)340    with open(path, "w", encoding="utf-8") as f:341        json.dump(obj, f, indent=1, ensure_ascii=False, sort_keys=False)342        f.write("\n")343
Files main
Menu

Theme