Datasets:
Download src/common.py from skyleee/diversa-biomedical-v1: direct link, hf CLI and curl.
- Browser
- Download file 8.54 kB
-
https://huggingface.co/datasets/skyleee/diversa-biomedical-v1/resolve/main/src/common.py
- Command line
-
hf download hf://datasets/skyleee/diversa-biomedical-v1/src/common.py
-
curl -L -o common.py https://huggingface.co/datasets/skyleee/diversa-biomedical-v1/resolve/main/src/common.py
8.54 kB
| """Shared utilities: config, paths, logging, checkpoints, hashing, HTTP with backoff.""" | |
| from __future__ import annotations | |
| import gzip | |
| import hashlib | |
| import json | |
| import logging | |
| import os | |
| import random | |
| import sys | |
| import threading | |
| import time | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any, Iterable, Iterator | |
| import requests | |
| import yaml | |
| ROOT = Path(__file__).resolve().parent.parent | |
| CONFIG_PATH = ROOT / "config.yaml" | |
| PIPELINE_VERSION = "1.0.0" | |
| _log_lock = threading.Lock() | |
| _logger: logging.Logger | None = None | |
| def load_config(path: str | Path | None = None) -> dict: | |
| with open(path or CONFIG_PATH, "r", encoding="utf-8") as fh: | |
| cfg = yaml.safe_load(fh) | |
| cfg["_root"] = str(ROOT) | |
| return cfg | |
| def p(cfg: dict, key: str) -> Path: | |
| """Resolve a configured relative path against the project root.""" | |
| return ROOT / cfg["paths"][key] | |
| def ensure_dirs(cfg: dict) -> None: | |
| for key in ("staging", "parts", "raw", "data", "analytics", "metadata", "checkpoints", "logs"): | |
| p(cfg, key).mkdir(parents=True, exist_ok=True) | |
| def utc_now() -> str: | |
| return datetime.now(timezone.utc).replace(microsecond=0).isoformat() | |
| def brief_ts() -> str: | |
| return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") | |
| def get_logger(name: str = "diversa", logfile: Path | None = None) -> logging.Logger: | |
| global _logger | |
| with _log_lock: | |
| if _logger is not None: | |
| return _logger | |
| logger = logging.getLogger(name) | |
| logger.setLevel(logging.INFO) | |
| fmt = logging.Formatter("%(asctime)s | %(levelname)-7s | %(message)s", "%Y-%m-%d %H:%M:%S") | |
| sh = logging.StreamHandler(sys.stdout) | |
| sh.setFormatter(fmt) | |
| logger.addHandler(sh) | |
| if logfile is not None: | |
| logfile.parent.mkdir(parents=True, exist_ok=True) | |
| fh = logging.FileHandler(logfile, encoding="utf-8") | |
| fh.setFormatter(fmt) | |
| logger.addHandler(fh) | |
| _logger = logger | |
| return logger | |
| def write_json(path: str | Path, obj: Any) -> None: | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| tmp = path.with_suffix(path.suffix + ".tmp") | |
| with open(tmp, "w", encoding="utf-8") as fh: | |
| json.dump(obj, fh, indent=2, ensure_ascii=False, default=str) | |
| os.replace(tmp, path) | |
| def read_json(path: str | Path, default: Any = None) -> Any: | |
| path = Path(path) | |
| if not path.exists(): | |
| return default | |
| with open(path, "r", encoding="utf-8") as fh: | |
| return json.load(fh) | |
| def sha256_file(path: str | Path, chunk: int = 1 << 20) -> str: | |
| h = hashlib.sha256() | |
| with open(path, "rb") as fh: | |
| for block in iter(lambda: fh.read(chunk), b""): | |
| h.update(block) | |
| return h.hexdigest() | |
| def sha256_text(text: str) -> str: | |
| return hashlib.sha256(text.encode("utf-8")).hexdigest() | |
| def stable_key(*parts: Any) -> str: | |
| return sha256_text("||".join(str(x) for x in parts))[:16] | |
| class Checkpoint: | |
| """Small JSON-backed state store, safe for resume across runs.""" | |
| def __init__(self, path: str | Path): | |
| self.path = Path(path) | |
| self._data = read_json(self.path, default={}) or {} | |
| self._lock = threading.Lock() | |
| def data(self) -> dict: | |
| return self._data | |
| def get(self, key: str, default: Any = None) -> Any: | |
| return self._data.get(key, default) | |
| def set(self, key: str, value: Any) -> None: | |
| with self._lock: | |
| self._data[key] = value | |
| write_json(self.path, self._data) | |
| def update(self, **kw: Any) -> None: | |
| with self._lock: | |
| self._data.update(kw) | |
| write_json(self.path, self._data) | |
| class RateLimiter: | |
| def __init__(self, min_interval: float): | |
| self.min_interval = min_interval | |
| self._lock = threading.Lock() | |
| self._last = 0.0 | |
| def wait(self) -> None: | |
| with self._lock: | |
| delta = time.time() - self._last | |
| if delta < self.min_interval: | |
| time.sleep(self.min_interval - delta) | |
| self._last = time.time() | |
| class OpenAlexClient: | |
| """Polite, retrying OpenAlex client with exponential backoff + jitter.""" | |
| def __init__(self, cfg: dict): | |
| self.base = cfg["source"]["base_url"].rstrip("/") | |
| self.mailto = cfg["source"].get("mailto") | |
| self.timeout = cfg["source"].get("request_timeout", 120) | |
| self.max_retries = cfg["source"].get("max_retries", 6) | |
| self.backoff_base = cfg["source"].get("backoff_base", 1.6) | |
| self.backoff_max = cfg["source"].get("backoff_max", 90) | |
| self.limiter = RateLimiter(cfg["source"].get("min_request_interval", 0.0)) | |
| self.session = requests.Session() | |
| self.session.headers.update({ | |
| "User-Agent": f"diversa-biomedical/1.0 (mailto:{self.mailto})", | |
| "Accept": "application/json", | |
| }) | |
| api_key = cfg["source"].get("api_key") or os.environ.get("OPENALEX_API_KEY") | |
| if not api_key: | |
| key_file = Path.home() / ".openalex_api_key" | |
| if key_file.exists(): | |
| api_key = key_file.read_text(encoding="utf-8").strip() or None | |
| if api_key: | |
| self.session.params = {"api_key": api_key} | |
| def get_json(self, path: str, params: dict | None = None, logger: logging.Logger | None = None): | |
| params = dict(params or {}) | |
| if self.mailto and "mailto" not in params: | |
| params["mailto"] = self.mailto | |
| url = f"{self.base}{path}" | |
| last_exc: Exception | None = None | |
| for attempt in range(self.max_retries + 1): | |
| self.limiter.wait() | |
| try: | |
| resp = self.session.get(url, params=params, timeout=self.timeout) | |
| if resp.status_code in (429, 500, 502, 503, 504): | |
| raise requests.HTTPError(f"retryable status {resp.status_code}", response=resp) | |
| resp.raise_for_status() | |
| return resp.json() | |
| except Exception as exc: # noqa: BLE001 | |
| last_exc = exc | |
| if attempt >= self.max_retries: | |
| break | |
| retry_after = None | |
| if isinstance(exc, requests.HTTPError) and exc.response is not None: | |
| retry_after = exc.response.headers.get("Retry-After") | |
| if retry_after and str(retry_after).isdigit() and float(retry_after) > 600: | |
| # OpenAlex returns a very large Retry-After when the daily | |
| # budget is exhausted; sleeping would stall the pipeline for | |
| # hours, so surface it as a fatal condition instead. | |
| raise RuntimeError( | |
| f"OpenAlex rate/budget limit hit (Retry-After={retry_after}s). " | |
| f"Stopping stage; rerun later or add an API key with budget." | |
| ) | |
| if retry_after and str(retry_after).isdigit(): | |
| delay = min(float(retry_after), self.backoff_max) | |
| else: | |
| delay = min(self.backoff_max, self.backoff_base ** attempt) | |
| delay += random.uniform(0, delay * 0.25) | |
| if logger: | |
| logger.warning("request failed (%s); retry %d/%d in %.1fs", | |
| _short(exc), attempt + 1, self.max_retries, delay) | |
| time.sleep(delay) | |
| raise RuntimeError(f"request failed after {self.max_retries} retries: {_short(last_exc)}") | |
| def _short(exc: Exception | None) -> str: | |
| if exc is None: | |
| return "unknown" | |
| return f"{type(exc).__name__}: {str(exc)[:160]}" | |
| def iter_gzip_jsonl(path: str | Path) -> Iterator[dict]: | |
| with gzip.open(path, "rt", encoding="utf-8") as fh: | |
| for line in fh: | |
| line = line.strip() | |
| if line: | |
| yield json.loads(line) | |
| def write_gzip_jsonl(path: str | Path, rows: Iterable[dict]) -> int: | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| tmp = path.with_suffix(path.suffix + ".tmp") | |
| n = 0 | |
| with gzip.open(tmp, "wt", encoding="utf-8") as fh: | |
| for row in rows: | |
| fh.write(json.dumps(row, ensure_ascii=False)) | |
| fh.write("\n") | |
| n += 1 | |
| os.replace(tmp, path) | |
| return n | |
| def human_bytes(n: float) -> str: | |
| for unit in ("B", "KB", "MB", "GB", "TB"): | |
| if abs(n) < 1024.0: | |
| return f"{n:3.1f}{unit}" | |
| n /= 1024.0 | |
| return f"{n:.1f}PB" | |