|
|
|
@@ -0,0 +1,917 @@
|
|
|
|
|
"""Upload UDE OrgMiner staff that were verified by the collaboration graph.
|
|
|
|
|
|
|
|
|
|
What this script does
|
|
|
|
|
---------------------
|
|
|
|
|
For every organization in the UDE organization-content index (one at a time):
|
|
|
|
|
|
|
|
|
|
1. READ the organization and its staff list from Elasticsearch (INSE)
|
|
|
|
|
2. VERIFY each staff member against the collaboration graph (OpenAlex)
|
|
|
|
|
3. BUILD one document per (organization, OpenAlex person)
|
|
|
|
|
4. UPLOAD the documents to ``orgminer_verified_persons_ude`` (bulk upsert)
|
|
|
|
|
5. CHECKPOINT the organization as done in a small JSON progress file
|
|
|
|
|
|
|
|
|
|
Everything runs sequentially: one organization at a time, one graph query at a
|
|
|
|
|
time.
|
|
|
|
|
|
|
|
|
|
Resumability
|
|
|
|
|
------------
|
|
|
|
|
Document IDs are deterministic, so re-running is always safe (documents are
|
|
|
|
|
overwritten, never duplicated). The progress file stores only:
|
|
|
|
|
|
|
|
|
|
* ``processed_org_doc_ids``: organizations that were fully uploaded.
|
|
|
|
|
* ``last_source_uri``: a cursor; every organization sorted before it is done.
|
|
|
|
|
|
|
|
|
|
The cursor stops advancing at the first failed organization, so failures are
|
|
|
|
|
retried on the next run.
|
|
|
|
|
|
|
|
|
|
Usage (from any directory):
|
|
|
|
|
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py
|
|
|
|
|
|
|
|
|
|
Requires the INSE and NES Elasticsearch credentials in the service's ``.env``
|
|
|
|
|
file or the environment. ``--dry-run`` verifies and counts without creating the
|
|
|
|
|
index, uploading, or touching the progress file.
|
|
|
|
|
"""
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import argparse
|
|
|
|
|
import asyncio
|
|
|
|
|
import hashlib
|
|
|
|
|
import json
|
|
|
|
|
import logging
|
|
|
|
|
import os
|
|
|
|
|
import sys
|
|
|
|
|
import time
|
|
|
|
|
from collections.abc import AsyncIterator, Awaitable, Callable, Iterable
|
|
|
|
|
from contextlib import aclosing
|
|
|
|
|
from dataclasses import dataclass, field
|
|
|
|
|
from datetime import UTC, datetime
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
from typing import Any, TypeVar
|
|
|
|
|
|
|
|
|
|
import httpx
|
|
|
|
|
|
|
|
|
|
SERVICE_DIR = Path(__file__).resolve().parents[2]
|
|
|
|
|
sys.path.insert(0, str(SERVICE_DIR / "src" / "main"))
|
|
|
|
|
|
|
|
|
|
from inse import config # noqa: E402
|
|
|
|
|
from inse.model import ESIndex # noqa: E402
|
|
|
|
|
from inse.orgminer import logic # noqa: E402
|
|
|
|
|
from inse.orgminer.institutions_helper import DEFAULT_INSTITUTION_ID # noqa: E402
|
|
|
|
|
|
|
|
|
|
T = TypeVar("T")
|
|
|
|
|
Hit = dict[str, Any] # one Elasticsearch search hit
|
|
|
|
|
HierarchyLookup = dict[str, tuple[str, list[str]]] # uri -> (name, path from root)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# =============================================================================
|
|
|
|
|
# Configuration
|
|
|
|
|
# =============================================================================
|
|
|
|
|
|
|
|
|
|
SOURCE_INDEX = ESIndex.UDE_ORGANIZATION_CONTENT.value
|
|
|
|
|
OUTPUT_INDEX = "orgminer_verified_persons_ude"
|
|
|
|
|
INSTITUTION_URL = f"https://openalex.org/{DEFAULT_INSTITUTION_ID}"
|
|
|
|
|
DEFAULT_PROGRESS_FILE = (
|
|
|
|
|
Path(__file__).resolve().parent / "orgminer_verified_persons_ude_progress.json"
|
|
|
|
|
)
|
|
|
|
|
PROGRESS_VERSION = 2
|
|
|
|
|
|
|
|
|
|
# Scanning the source index (point-in-time search, paged).
|
|
|
|
|
SCAN_PAGE_SIZE = 100
|
|
|
|
|
PIT_KEEP_ALIVE = "10m"
|
|
|
|
|
MAX_PIT_RESTARTS = 5
|
|
|
|
|
|
|
|
|
|
# Bulk uploads.
|
|
|
|
|
BULK_MAX_DOCS = 250
|
|
|
|
|
BULK_MAX_BYTES = 5 * 1024 * 1024
|
|
|
|
|
MAX_ATTEMPTS = 4
|
|
|
|
|
RETRYABLE_STATUS = {429, 502, 503, 504}
|
|
|
|
|
|
|
|
|
|
# Collab-graph queries per organization. Kept at 1: fully sequential.
|
|
|
|
|
GRAPH_QUERIES_AT_A_TIME = 1
|
|
|
|
|
|
|
|
|
|
PROGRESS_SAVE_INTERVAL_S = 5.0
|
|
|
|
|
PROGRESS_LOG_INTERVAL_S = 30.0
|
|
|
|
|
|
|
|
|
|
INDEX_MAPPING = {
|
|
|
|
|
"dynamic": "strict",
|
|
|
|
|
"properties": {
|
|
|
|
|
"name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
|
|
|
|
|
"org_name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
|
|
|
|
|
"org_uri": {"type": "keyword"},
|
|
|
|
|
"org_hierarchy_path": {"type": "keyword"},
|
|
|
|
|
"openalex_id": {"type": "keyword"},
|
|
|
|
|
# Kept verbatim in _source; staff dicts vary, so don't index them.
|
|
|
|
|
"staff": {"type": "object", "dynamic": False},
|
|
|
|
|
"staff_entries": {"type": "object", "dynamic": False},
|
|
|
|
|
"source_index": {"type": "keyword"},
|
|
|
|
|
"source_org_doc_id": {"type": "keyword"},
|
|
|
|
|
"verification_method": {"type": "keyword"},
|
|
|
|
|
"verification_evidence": {
|
|
|
|
|
"type": "nested",
|
|
|
|
|
"properties": {
|
|
|
|
|
"openalex_id": {"type": "keyword"},
|
|
|
|
|
"collaborator_openalex_id": {"type": "keyword"},
|
|
|
|
|
"shared_work_weight": {"type": "float"},
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
"verified_at": {"type": "date"},
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logging.basicConfig(
|
|
|
|
|
level=logging.INFO,
|
|
|
|
|
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
|
|
|
|
)
|
|
|
|
|
logger = logging.getLogger("upload_orgminer_verified_persons_ude")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# =============================================================================
|
|
|
|
|
# Generic helpers
|
|
|
|
|
# =============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def backoff_delay(attempt: int) -> float:
|
|
|
|
|
return min(2.0**attempt, 30.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def retry_async(
|
|
|
|
|
operation: Callable[[], Awaitable[T]],
|
|
|
|
|
*,
|
|
|
|
|
description: str,
|
|
|
|
|
attempts: int = MAX_ATTEMPTS,
|
|
|
|
|
) -> T:
|
|
|
|
|
"""Run ``operation``; on any exception wait (exponential backoff) and retry."""
|
|
|
|
|
for attempt in range(1, attempts + 1):
|
|
|
|
|
try:
|
|
|
|
|
return await operation()
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
if attempt == attempts:
|
|
|
|
|
raise
|
|
|
|
|
logger.warning(
|
|
|
|
|
"%s failed (attempt %d/%d): %s. Retrying.",
|
|
|
|
|
description,
|
|
|
|
|
attempt,
|
|
|
|
|
attempts,
|
|
|
|
|
exc,
|
|
|
|
|
)
|
|
|
|
|
await asyncio.sleep(backoff_delay(attempt))
|
|
|
|
|
raise AssertionError("unreachable")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def require_es_credentials() -> tuple[str, str]:
|
|
|
|
|
"""Check both clusters are configured; return the INSE (url, api_key)."""
|
|
|
|
|
if (
|
|
|
|
|
not config.settings.elasticsearch_url
|
|
|
|
|
or not config.settings.elasticsearch_api_key
|
|
|
|
|
):
|
|
|
|
|
raise SystemExit(
|
|
|
|
|
"NES Elasticsearch credentials are missing. Collab-graph verification "
|
|
|
|
|
"needs ELASTICSEARCH_URL and ELASTICSEARCH_API_KEY."
|
|
|
|
|
)
|
|
|
|
|
url = config.settings.elasticsearch_inse_url
|
|
|
|
|
api_key = config.settings.elasticsearch_inse_api_key
|
|
|
|
|
if not url or not api_key:
|
|
|
|
|
raise SystemExit(
|
|
|
|
|
"INSE Elasticsearch credentials are missing. Set "
|
|
|
|
|
"ELASTICSEARCH_INSE_URL and ELASTICSEARCH_INSE_API_KEY in the "
|
|
|
|
|
"environment or service/src/main/inse/.env."
|
|
|
|
|
)
|
|
|
|
|
return url.rstrip("/"), api_key
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def make_headers(api_key: str, content_type: str = "application/json") -> dict[str, str]:
|
|
|
|
|
return {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def checkpoint_dir_is_mounted(path: Path) -> bool | None:
|
|
|
|
|
"""Whether the checkpoint directory is a mount point (relevant in containers).
|
|
|
|
|
|
|
|
|
|
Returns ``None`` when the platform doesn't expose mount info (e.g. macOS).
|
|
|
|
|
"""
|
|
|
|
|
mountinfo = Path("/proc/self/mountinfo")
|
|
|
|
|
if not mountinfo.exists():
|
|
|
|
|
return None
|
|
|
|
|
try:
|
|
|
|
|
directory = str(path.parent.resolve())
|
|
|
|
|
lines = mountinfo.read_text(encoding="utf-8").splitlines()
|
|
|
|
|
except OSError:
|
|
|
|
|
return None
|
|
|
|
|
return any(
|
|
|
|
|
len(fields) > 4 and fields[4] == directory
|
|
|
|
|
for fields in (line.split() for line in lines)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# =============================================================================
|
|
|
|
|
# Run statistics and progress checkpoint
|
|
|
|
|
# =============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class Stats:
|
|
|
|
|
scanned: int = 0
|
|
|
|
|
orgs_done: int = 0
|
|
|
|
|
orgs_failed: int = 0
|
|
|
|
|
person_docs: int = 0
|
|
|
|
|
uploaded: int = 0
|
|
|
|
|
doc_errors: int = 0
|
|
|
|
|
started: float = field(default_factory=time.monotonic)
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def has_errors(self) -> bool:
|
|
|
|
|
return bool(self.orgs_failed or self.doc_errors)
|
|
|
|
|
|
|
|
|
|
def summary(self) -> str:
|
|
|
|
|
return (
|
|
|
|
|
f"scanned={self.scanned} orgs_done={self.orgs_done} "
|
|
|
|
|
f"orgs_failed={self.orgs_failed} person_docs={self.person_docs} "
|
|
|
|
|
f"uploaded={self.uploaded} doc_errors={self.doc_errors} "
|
|
|
|
|
f"elapsed={time.monotonic() - self.started:.0f}s"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class Progress:
|
|
|
|
|
"""Checkpoint saved to a JSON file (at most every few seconds, and on exit)."""
|
|
|
|
|
|
|
|
|
|
path: Path
|
|
|
|
|
persist: bool # False in --dry-run: never write the file
|
|
|
|
|
processed_org_ids: set[str] = field(default_factory=set)
|
|
|
|
|
last_source_uri: str | None = None
|
|
|
|
|
_dirty: bool = False
|
|
|
|
|
_last_save: float = 0.0
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def load(cls, path: Path, *, persist: bool) -> Progress:
|
|
|
|
|
progress = cls(path=path, persist=persist)
|
|
|
|
|
if not path.exists():
|
|
|
|
|
return progress
|
|
|
|
|
try:
|
|
|
|
|
state = json.loads(path.read_text(encoding="utf-8"))
|
|
|
|
|
except (OSError, json.JSONDecodeError) as exc:
|
|
|
|
|
raise SystemExit(f"Could not read progress file {path}: {exc}") from exc
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
state.get("source_index") != SOURCE_INDEX
|
|
|
|
|
or state.get("output_index") != OUTPUT_INDEX
|
|
|
|
|
):
|
|
|
|
|
raise SystemExit(
|
|
|
|
|
f"Progress file {path} belongs to a different source/output index. "
|
|
|
|
|
"Choose another --progress-file or move the old file."
|
|
|
|
|
)
|
|
|
|
|
progress.processed_org_ids = set(state.get("processed_org_doc_ids", []))
|
|
|
|
|
progress.last_source_uri = state.get("last_source_uri")
|
|
|
|
|
return progress
|
|
|
|
|
|
|
|
|
|
def reset(self) -> None:
|
|
|
|
|
self.processed_org_ids.clear()
|
|
|
|
|
self.last_source_uri = None
|
|
|
|
|
|
|
|
|
|
def mark_org_done(self, org_doc_id: str) -> None:
|
|
|
|
|
self.processed_org_ids.add(org_doc_id)
|
|
|
|
|
self._dirty = True
|
|
|
|
|
|
|
|
|
|
def advance_cursor(self, uri: str | None) -> None:
|
|
|
|
|
if uri and uri != self.last_source_uri:
|
|
|
|
|
self.last_source_uri = uri
|
|
|
|
|
self._dirty = True
|
|
|
|
|
|
|
|
|
|
def save(self, *, force: bool = False) -> None:
|
|
|
|
|
if not self.persist or not self._dirty:
|
|
|
|
|
return
|
|
|
|
|
now = time.monotonic()
|
|
|
|
|
if not force and now - self._last_save < PROGRESS_SAVE_INTERVAL_S:
|
|
|
|
|
return
|
|
|
|
|
state = {
|
|
|
|
|
"version": PROGRESS_VERSION,
|
|
|
|
|
"source_index": SOURCE_INDEX,
|
|
|
|
|
"output_index": OUTPUT_INDEX,
|
|
|
|
|
"processed_org_doc_ids": sorted(self.processed_org_ids),
|
|
|
|
|
"last_source_uri": self.last_source_uri,
|
|
|
|
|
"updated_at": datetime.now(UTC).isoformat(),
|
|
|
|
|
}
|
|
|
|
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
tmp = self.path.with_suffix(self.path.suffix + ".tmp")
|
|
|
|
|
tmp.write_text(
|
|
|
|
|
json.dumps(state, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
|
|
|
|
|
encoding="utf-8",
|
|
|
|
|
)
|
|
|
|
|
os.replace(tmp, self.path) # atomic: never leaves a half-written file
|
|
|
|
|
self._dirty = False
|
|
|
|
|
self._last_save = now
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# =============================================================================
|
|
|
|
|
# Step 1: READ organizations from the source index
|
|
|
|
|
# =============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class PitExpired(Exception):
|
|
|
|
|
"""The point-in-time search context is gone and must be reopened."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _scan_query(start_uri: str | None) -> dict[str, Any]:
|
|
|
|
|
if not start_uri:
|
|
|
|
|
return {"match_all": {}}
|
|
|
|
|
# Organizations without a URI sort first and can never satisfy a range
|
|
|
|
|
# filter, so include them explicitly; already-processed IDs are skipped later.
|
|
|
|
|
return {
|
|
|
|
|
"bool": {
|
|
|
|
|
"should": [
|
|
|
|
|
{"range": {"uri.keyword": {"gte": start_uri}}},
|
|
|
|
|
{"bool": {"must_not": {"exists": {"field": "uri.keyword"}}}},
|
|
|
|
|
],
|
|
|
|
|
"minimum_should_match": 1,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def _scan_pages(
|
|
|
|
|
client: httpx.AsyncClient,
|
|
|
|
|
url: str,
|
|
|
|
|
headers: dict[str, str],
|
|
|
|
|
start_uri: str | None,
|
|
|
|
|
) -> AsyncIterator[list[Hit]]:
|
|
|
|
|
"""Open a point-in-time and yield pages of hits, sorted by URI."""
|
|
|
|
|
response = await client.post(
|
|
|
|
|
f"{url}/{SOURCE_INDEX}/_pit",
|
|
|
|
|
params={"keep_alive": PIT_KEEP_ALIVE},
|
|
|
|
|
headers=headers,
|
|
|
|
|
)
|
|
|
|
|
response.raise_for_status()
|
|
|
|
|
pit_id = response.json()["id"]
|
|
|
|
|
search_after: list[Any] | None = None
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
while True:
|
|
|
|
|
payload: dict[str, Any] = {
|
|
|
|
|
"size": SCAN_PAGE_SIZE,
|
|
|
|
|
"query": _scan_query(start_uri),
|
|
|
|
|
"pit": {"id": pit_id, "keep_alive": PIT_KEEP_ALIVE},
|
|
|
|
|
"sort": [
|
|
|
|
|
{"uri.keyword": {"order": "asc", "missing": "_first"}},
|
|
|
|
|
{"_shard_doc": "asc"},
|
|
|
|
|
],
|
|
|
|
|
"track_total_hits": False,
|
|
|
|
|
"_source": ["uri", "staff", "name", "org_name", "organization_name"],
|
|
|
|
|
}
|
|
|
|
|
if search_after is not None:
|
|
|
|
|
payload["search_after"] = search_after
|
|
|
|
|
|
|
|
|
|
response = await client.post(f"{url}/_search", json=payload, headers=headers)
|
|
|
|
|
if response.status_code == 404 and "search_context_missing" in response.text:
|
|
|
|
|
raise PitExpired
|
|
|
|
|
response.raise_for_status()
|
|
|
|
|
|
|
|
|
|
result = response.json()
|
|
|
|
|
hits = result.get("hits", {}).get("hits", [])
|
|
|
|
|
if not hits:
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
pit_id = result.get("pit_id", pit_id)
|
|
|
|
|
search_after = hits[-1].get("sort")
|
|
|
|
|
yield hits
|
|
|
|
|
if search_after is None or len(hits) < SCAN_PAGE_SIZE:
|
|
|
|
|
return
|
|
|
|
|
finally:
|
|
|
|
|
try:
|
|
|
|
|
await client.request(
|
|
|
|
|
"DELETE", f"{url}/_pit", json={"id": pit_id}, headers=headers
|
|
|
|
|
)
|
|
|
|
|
except Exception:
|
|
|
|
|
logger.warning("Could not close the point-in-time.", exc_info=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def scan_organizations(
|
|
|
|
|
client: httpx.AsyncClient,
|
|
|
|
|
url: str,
|
|
|
|
|
headers: dict[str, str],
|
|
|
|
|
start_after_uri: str | None,
|
|
|
|
|
) -> AsyncIterator[Hit]:
|
|
|
|
|
"""Yield organizations one by one, in URI order.
|
|
|
|
|
|
|
|
|
|
If the point-in-time expires, reopen it and continue from the last URI seen.
|
|
|
|
|
Organizations that were already finished are skipped by the caller.
|
|
|
|
|
"""
|
|
|
|
|
resume_uri = start_after_uri
|
|
|
|
|
restarts = 0
|
|
|
|
|
|
|
|
|
|
while True:
|
|
|
|
|
try:
|
|
|
|
|
async with aclosing(_scan_pages(client, url, headers, resume_uri)) as pages:
|
|
|
|
|
async for page in pages:
|
|
|
|
|
restarts = 0
|
|
|
|
|
resume_uri = page[-1].get("_source", {}).get("uri") or resume_uri
|
|
|
|
|
for hit in page:
|
|
|
|
|
yield hit
|
|
|
|
|
return
|
|
|
|
|
except PitExpired:
|
|
|
|
|
restarts += 1
|
|
|
|
|
if restarts > MAX_PIT_RESTARTS:
|
|
|
|
|
raise RuntimeError("Point-in-time kept expiring; giving up.") from None
|
|
|
|
|
logger.warning(
|
|
|
|
|
"Point-in-time expired; reopening from uri=%r (restart %d/%d).",
|
|
|
|
|
resume_uri,
|
|
|
|
|
restarts,
|
|
|
|
|
MAX_PIT_RESTARTS,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# =============================================================================
|
|
|
|
|
# Step 3: BUILD one document per (organization, OpenAlex person)
|
|
|
|
|
# =============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def normalize_org_uri(uri: str | None) -> str | None:
|
|
|
|
|
if not uri:
|
|
|
|
|
return None
|
|
|
|
|
normalized = uri.strip().rstrip("/")
|
|
|
|
|
if normalized.endswith("/index"):
|
|
|
|
|
normalized = normalized[: -len("/index")].rstrip("/")
|
|
|
|
|
return normalized or None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def build_hierarchy_lookup(hierarchy: Iterable[Any]) -> HierarchyLookup:
|
|
|
|
|
"""Map normalized organization links to (display name, path from the root)."""
|
|
|
|
|
lookup: HierarchyLookup = {}
|
|
|
|
|
|
|
|
|
|
def visit(node: Any, ancestors: list[str]) -> None:
|
|
|
|
|
name = getattr(node, "name_de", None) or getattr(node, "name_en", None)
|
|
|
|
|
path = [*ancestors, name] if name else ancestors
|
|
|
|
|
if name:
|
|
|
|
|
for link in (getattr(node, "link_de", None), getattr(node, "link_en", None)):
|
|
|
|
|
if normalized := normalize_org_uri(link):
|
|
|
|
|
lookup[normalized] = (name, path)
|
|
|
|
|
for child in getattr(node, "children", None) or []:
|
|
|
|
|
visit(child, path)
|
|
|
|
|
|
|
|
|
|
for root in hierarchy:
|
|
|
|
|
visit(root, [])
|
|
|
|
|
return lookup
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def organization_details(
|
|
|
|
|
source: dict[str, Any], hierarchy_lookup: HierarchyLookup
|
|
|
|
|
) -> tuple[str, list[str], str | None]:
|
|
|
|
|
"""Return (org name, hierarchy path, org URI), with fallbacks for the name."""
|
|
|
|
|
org_uri = source.get("uri")
|
|
|
|
|
hierarchy_name, hierarchy_path = hierarchy_lookup.get(
|
|
|
|
|
normalize_org_uri(org_uri) or "", ("", [])
|
|
|
|
|
)
|
|
|
|
|
org_name = (
|
|
|
|
|
source.get("org_name")
|
|
|
|
|
or source.get("organization_name")
|
|
|
|
|
or source.get("name")
|
|
|
|
|
or hierarchy_name
|
|
|
|
|
or org_uri
|
|
|
|
|
or "Unknown organization"
|
|
|
|
|
)
|
|
|
|
|
return str(org_name), hierarchy_path, org_uri
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def stable_document_id(org_uri: str | None, org_doc_id: str, openalex_id: str) -> str:
|
|
|
|
|
"""Deterministic ID so re-uploads overwrite instead of duplicating."""
|
|
|
|
|
org_identity = normalize_org_uri(org_uri) or org_doc_id
|
|
|
|
|
return hashlib.sha256(f"{org_identity}\0{openalex_id}".encode()).hexdigest()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _canonical(value: Any) -> str:
|
|
|
|
|
return json.dumps(value, sort_keys=True, ensure_ascii=False, default=str)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def make_person_documents(
|
|
|
|
|
source: dict[str, Any],
|
|
|
|
|
source_doc_id: str,
|
|
|
|
|
verified_entries: list[dict[str, Any]],
|
|
|
|
|
hierarchy_lookup: HierarchyLookup,
|
|
|
|
|
verified_at: str,
|
|
|
|
|
) -> list[tuple[str, Hit]]:
|
|
|
|
|
"""Turn verified staff entries into [(doc_id, document)], one per OpenAlex person.
|
|
|
|
|
|
|
|
|
|
A person may be matched by several staff entries and several collaborators,
|
|
|
|
|
so entries and evidence are de-duplicated per person first.
|
|
|
|
|
"""
|
|
|
|
|
org_name, hierarchy_path, org_uri = organization_details(source, hierarchy_lookup)
|
|
|
|
|
|
|
|
|
|
# openalex_id -> {canonical staff json -> staff dict}
|
|
|
|
|
staff_by_person: dict[str, dict[str, dict[str, Any]]] = {}
|
|
|
|
|
# openalex_id -> {(openalex_id, collaborator_id) -> evidence dict}
|
|
|
|
|
evidence_by_person: dict[str, dict[tuple[Any, Any], dict[str, Any]]] = {}
|
|
|
|
|
|
|
|
|
|
for entry in verified_entries:
|
|
|
|
|
staff = entry["staff"]
|
|
|
|
|
staff_key = _canonical(staff)
|
|
|
|
|
for openalex_id in entry["openalex_ids"]:
|
|
|
|
|
staff_by_person.setdefault(openalex_id, {}).setdefault(staff_key, staff)
|
|
|
|
|
seen = evidence_by_person.setdefault(openalex_id, {})
|
|
|
|
|
for evidence in entry["collaboration_evidence"]:
|
|
|
|
|
if evidence["openalex_id"] == openalex_id:
|
|
|
|
|
key = (evidence["openalex_id"], evidence.get("collaborator_openalex_id"))
|
|
|
|
|
seen.setdefault(key, evidence)
|
|
|
|
|
|
|
|
|
|
documents: list[tuple[str, Hit]] = []
|
|
|
|
|
for openalex_id, staff_map in staff_by_person.items():
|
|
|
|
|
staff_entries = list(staff_map.values())
|
|
|
|
|
primary_staff = staff_entries[0]
|
|
|
|
|
document = {
|
|
|
|
|
"name": primary_staff.get("name"),
|
|
|
|
|
"org_name": org_name,
|
|
|
|
|
"org_uri": org_uri,
|
|
|
|
|
"org_hierarchy_path": hierarchy_path,
|
|
|
|
|
"openalex_id": openalex_id,
|
|
|
|
|
"staff": primary_staff,
|
|
|
|
|
"staff_entries": staff_entries,
|
|
|
|
|
"source_index": SOURCE_INDEX,
|
|
|
|
|
"source_org_doc_id": source_doc_id,
|
|
|
|
|
"verification_method": "collab_graph",
|
|
|
|
|
"verification_evidence": list(evidence_by_person[openalex_id].values()),
|
|
|
|
|
"verified_at": verified_at,
|
|
|
|
|
}
|
|
|
|
|
doc_id = stable_document_id(org_uri, source_doc_id, openalex_id)
|
|
|
|
|
documents.append((doc_id, document))
|
|
|
|
|
return documents
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# =============================================================================
|
|
|
|
|
# Step 4: UPLOAD documents to the output index
|
|
|
|
|
# =============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def ensure_output_index(
|
|
|
|
|
client: httpx.AsyncClient, url: str, headers: dict[str, str]
|
|
|
|
|
) -> None:
|
|
|
|
|
"""Create the output index with its mapping if it doesn't exist yet."""
|
|
|
|
|
head = await client.head(f"{url}/{OUTPUT_INDEX}", headers=headers)
|
|
|
|
|
if head.status_code == 200:
|
|
|
|
|
logger.info("Output index %r already exists.", OUTPUT_INDEX)
|
|
|
|
|
return
|
|
|
|
|
if head.status_code != 404:
|
|
|
|
|
head.raise_for_status()
|
|
|
|
|
|
|
|
|
|
response = await client.put(
|
|
|
|
|
f"{url}/{OUTPUT_INDEX}", json={"mappings": INDEX_MAPPING}, headers=headers
|
|
|
|
|
)
|
|
|
|
|
if response.status_code == 400 and "resource_already_exists" in response.text:
|
|
|
|
|
logger.info("Output index %r was created concurrently.", OUTPUT_INDEX)
|
|
|
|
|
return
|
|
|
|
|
response.raise_for_status()
|
|
|
|
|
logger.info("Created output index %r.", OUTPUT_INDEX)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _bulk_chunk(doc_id: str, document: Hit) -> str:
|
|
|
|
|
action = json.dumps({"index": {"_index": OUTPUT_INDEX, "_id": doc_id}})
|
|
|
|
|
return f"{action}\n{json.dumps(document, ensure_ascii=False)}\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _split_batches(items: list[tuple[str, str]]) -> Iterable[list[tuple[str, str]]]:
|
|
|
|
|
"""Group (doc_id, ndjson) items by document count and payload size."""
|
|
|
|
|
batch: list[tuple[str, str]] = []
|
|
|
|
|
size = 0
|
|
|
|
|
for item in items:
|
|
|
|
|
item_size = len(item[1].encode("utf-8"))
|
|
|
|
|
if batch and (len(batch) >= BULK_MAX_DOCS or size + item_size > BULK_MAX_BYTES):
|
|
|
|
|
yield batch
|
|
|
|
|
batch, size = [], 0
|
|
|
|
|
batch.append(item)
|
|
|
|
|
size += item_size
|
|
|
|
|
if batch:
|
|
|
|
|
yield batch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def _post_bulk(
|
|
|
|
|
client: httpx.AsyncClient,
|
|
|
|
|
url: str,
|
|
|
|
|
api_key: str,
|
|
|
|
|
batch: list[tuple[str, str]],
|
|
|
|
|
) -> dict[str, Any]:
|
|
|
|
|
"""Send one bulk request, retrying on network errors and retryable statuses."""
|
|
|
|
|
body = "".join(chunk for _, chunk in batch).encode("utf-8")
|
|
|
|
|
headers = make_headers(api_key, "application/x-ndjson")
|
|
|
|
|
|
|
|
|
|
async def send() -> dict[str, Any]:
|
|
|
|
|
response = await client.post(f"{url}/_bulk", content=body, headers=headers)
|
|
|
|
|
response.raise_for_status()
|
|
|
|
|
return response.json()
|
|
|
|
|
|
|
|
|
|
return await retry_async(send, description="Bulk request")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def bulk_index(
|
|
|
|
|
client: httpx.AsyncClient,
|
|
|
|
|
url: str,
|
|
|
|
|
api_key: str,
|
|
|
|
|
documents: list[tuple[str, Hit]],
|
|
|
|
|
) -> tuple[int, list[tuple[str, str]]]:
|
|
|
|
|
"""Upsert documents. Return (success count, [(doc_id, error), ...]).
|
|
|
|
|
|
|
|
|
|
Items rejected with a retryable status (typically 429 under load) are sent
|
|
|
|
|
again with backoff. Everything else that fails is reported as a failure.
|
|
|
|
|
"""
|
|
|
|
|
pending = [(doc_id, _bulk_chunk(doc_id, doc)) for doc_id, doc in documents]
|
|
|
|
|
succeeded = 0
|
|
|
|
|
failures: dict[str, str] = {}
|
|
|
|
|
|
|
|
|
|
for attempt in range(1, MAX_ATTEMPTS + 1):
|
|
|
|
|
retry: list[tuple[str, str]] = []
|
|
|
|
|
|
|
|
|
|
for batch in _split_batches(pending):
|
|
|
|
|
result = await _post_bulk(client, url, api_key, batch)
|
|
|
|
|
items = result.get("items", [])
|
|
|
|
|
if len(items) != len(batch):
|
|
|
|
|
raise RuntimeError(
|
|
|
|
|
"Elasticsearch bulk response item count did not match the request."
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
for (doc_id, chunk), item in zip(batch, items):
|
|
|
|
|
outcome = item.get("index", {})
|
|
|
|
|
status = outcome.get("status", 0)
|
|
|
|
|
error = json.dumps(outcome.get("error", outcome), ensure_ascii=False)
|
|
|
|
|
if 200 <= status < 300:
|
|
|
|
|
succeeded += 1
|
|
|
|
|
failures.pop(doc_id, None)
|
|
|
|
|
elif status in RETRYABLE_STATUS:
|
|
|
|
|
retry.append((doc_id, chunk))
|
|
|
|
|
failures[doc_id] = error
|
|
|
|
|
else:
|
|
|
|
|
failures[doc_id] = error
|
|
|
|
|
|
|
|
|
|
if not retry:
|
|
|
|
|
break
|
|
|
|
|
pending = retry
|
|
|
|
|
if attempt < MAX_ATTEMPTS:
|
|
|
|
|
logger.warning(
|
|
|
|
|
"%d bulk items were rejected; retrying (attempt %d/%d).",
|
|
|
|
|
len(retry),
|
|
|
|
|
attempt,
|
|
|
|
|
MAX_ATTEMPTS,
|
|
|
|
|
)
|
|
|
|
|
await asyncio.sleep(backoff_delay(attempt))
|
|
|
|
|
|
|
|
|
|
return succeeded, sorted(failures.items())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# =============================================================================
|
|
|
|
|
# Processing a single organization (steps 2-4)
|
|
|
|
|
# =============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class Context:
|
|
|
|
|
"""Everything `process_organization` needs, bundled in one place."""
|
|
|
|
|
|
|
|
|
|
client: httpx.AsyncClient
|
|
|
|
|
url: str
|
|
|
|
|
api_key: str
|
|
|
|
|
hierarchy_lookup: HierarchyLookup
|
|
|
|
|
stats: Stats
|
|
|
|
|
dry_run: bool
|
|
|
|
|
fail_fast: bool
|
|
|
|
|
verified_at: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def staff_of(source: dict[str, Any]) -> list[dict[str, Any]]:
|
|
|
|
|
raw = source.get("staff")
|
|
|
|
|
if not isinstance(raw, list):
|
|
|
|
|
return []
|
|
|
|
|
return [staff for staff in raw if isinstance(staff, dict)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def process_organization(hit: Hit, ctx: Context) -> bool:
|
|
|
|
|
"""Verify one organization's staff and upload the result.
|
|
|
|
|
|
|
|
|
|
Returns True if the organization is completely done (nothing to retry).
|
|
|
|
|
"""
|
|
|
|
|
doc_id = str(hit.get("_id") or "")
|
|
|
|
|
source = hit.get("_source", {})
|
|
|
|
|
label = source.get("uri") or doc_id
|
|
|
|
|
|
|
|
|
|
staff_list = staff_of(source)
|
|
|
|
|
if not staff_list:
|
|
|
|
|
return True # nothing to verify
|
|
|
|
|
|
|
|
|
|
logger.info("Processing organization %s (%d staff entries).", label, len(staff_list))
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
# Step 2: verify staff against the collaboration graph.
|
|
|
|
|
verified_entries = await retry_async(
|
|
|
|
|
lambda: logic.get_verified_staff_with_collab_graph(
|
|
|
|
|
staff_list,
|
|
|
|
|
INSTITUTION_URL,
|
|
|
|
|
max_concurrent_queries=GRAPH_QUERIES_AT_A_TIME,
|
|
|
|
|
),
|
|
|
|
|
description=f"Collab-graph verification for {label}",
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# Step 3: build one document per OpenAlex person.
|
|
|
|
|
documents = make_person_documents(
|
|
|
|
|
source, doc_id, verified_entries, ctx.hierarchy_lookup, ctx.verified_at
|
|
|
|
|
)
|
|
|
|
|
ctx.stats.person_docs += len(documents)
|
|
|
|
|
|
|
|
|
|
if ctx.dry_run:
|
|
|
|
|
logger.info(
|
|
|
|
|
"DRY RUN org=%s verified_staff=%d person_org_docs=%d",
|
|
|
|
|
label,
|
|
|
|
|
len(verified_entries),
|
|
|
|
|
len(documents),
|
|
|
|
|
)
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
# Step 4: upload.
|
|
|
|
|
uploaded, failures = await bulk_index(ctx.client, ctx.url, ctx.api_key, documents)
|
|
|
|
|
ctx.stats.uploaded += uploaded
|
|
|
|
|
for failed_id, error in failures:
|
|
|
|
|
ctx.stats.doc_errors += 1
|
|
|
|
|
logger.error("Failed to index document %s (org %s): %s", failed_id, label, error)
|
|
|
|
|
return not failures
|
|
|
|
|
|
|
|
|
|
except Exception:
|
|
|
|
|
logger.exception("Failed processing organization %s (_id=%s).", label, doc_id)
|
|
|
|
|
if ctx.fail_fast:
|
|
|
|
|
raise
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# =============================================================================
|
|
|
|
|
# Main flow
|
|
|
|
|
# =============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def reset_checkpoint_files(progress_file: Path) -> None:
|
|
|
|
|
"""Implements --fresh: delete the progress file (and a leftover .tmp file)."""
|
|
|
|
|
tmp_file = progress_file.with_suffix(progress_file.suffix + ".tmp")
|
|
|
|
|
existed = progress_file.exists()
|
|
|
|
|
removed = []
|
|
|
|
|
for path in (progress_file, tmp_file):
|
|
|
|
|
try:
|
|
|
|
|
path.unlink()
|
|
|
|
|
removed.append(str(path))
|
|
|
|
|
except FileNotFoundError:
|
|
|
|
|
pass
|
|
|
|
|
logger.info(
|
|
|
|
|
"--fresh: removed %s. Output index %r is kept and will be updated by upserts.",
|
|
|
|
|
removed,
|
|
|
|
|
OUTPUT_INDEX,
|
|
|
|
|
)
|
|
|
|
|
if existed:
|
|
|
|
|
logger.warning(
|
|
|
|
|
"--fresh discarded the existing checkpoint. If a saved job command "
|
|
|
|
|
"contains --fresh, it restarts from the first organization on every "
|
|
|
|
|
"run; remove the flag to resume instead."
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def prepare_progress(args: argparse.Namespace) -> Progress:
|
|
|
|
|
"""Load (or reset) the checkpoint according to the CLI flags."""
|
|
|
|
|
if args.fresh:
|
|
|
|
|
reset_checkpoint_files(args.progress_file)
|
|
|
|
|
|
|
|
|
|
progress = Progress.load(args.progress_file, persist=not args.dry_run)
|
|
|
|
|
if args.ignore_progress:
|
|
|
|
|
progress.reset()
|
|
|
|
|
|
|
|
|
|
logger.info(
|
|
|
|
|
"Checkpoint %s: %d finished organizations, resume cursor=%r.",
|
|
|
|
|
args.progress_file,
|
|
|
|
|
len(progress.processed_org_ids),
|
|
|
|
|
progress.last_source_uri,
|
|
|
|
|
)
|
|
|
|
|
if not args.dry_run and checkpoint_dir_is_mounted(args.progress_file) is False:
|
|
|
|
|
logger.warning(
|
|
|
|
|
"Checkpoint directory %s is not a mounted volume, so progress is lost "
|
|
|
|
|
"as soon as the container is removed. Set the job's persistent directory "
|
|
|
|
|
"to %s.",
|
|
|
|
|
args.progress_file.parent,
|
|
|
|
|
args.progress_file.parent,
|
|
|
|
|
)
|
|
|
|
|
return progress
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def run(args: argparse.Namespace) -> int:
|
|
|
|
|
# Setup ---------------------------------------------------------------
|
|
|
|
|
url, api_key = require_es_credentials() # fail fast, before slow work
|
|
|
|
|
headers = make_headers(api_key)
|
|
|
|
|
progress = prepare_progress(args)
|
|
|
|
|
|
|
|
|
|
hierarchy = await logic.get_hierarchy(INSTITUTION_URL)
|
|
|
|
|
hierarchy_lookup = build_hierarchy_lookup(hierarchy)
|
|
|
|
|
logger.info("Loaded %d hierarchy URL mappings for UDE.", len(hierarchy_lookup))
|
|
|
|
|
|
|
|
|
|
stats = Stats()
|
|
|
|
|
organizations_handled = 0 # for --limit
|
|
|
|
|
cursor_blocked = False # set after the first failure; cursor stops moving
|
|
|
|
|
last_log = time.monotonic()
|
|
|
|
|
|
|
|
|
|
async with httpx.AsyncClient(timeout=httpx.Timeout(90.0)) as client:
|
|
|
|
|
if not args.dry_run:
|
|
|
|
|
await ensure_output_index(client, url, headers)
|
|
|
|
|
|
|
|
|
|
ctx = Context(
|
|
|
|
|
client=client,
|
|
|
|
|
url=url,
|
|
|
|
|
api_key=api_key,
|
|
|
|
|
hierarchy_lookup=hierarchy_lookup,
|
|
|
|
|
stats=stats,
|
|
|
|
|
dry_run=args.dry_run,
|
|
|
|
|
fail_fast=args.fail_fast,
|
|
|
|
|
verified_at=datetime.now(UTC).isoformat(),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# Main loop: one organization at a time -----------------------------
|
|
|
|
|
try:
|
|
|
|
|
async with aclosing(
|
|
|
|
|
scan_organizations(client, url, headers, progress.last_source_uri)
|
|
|
|
|
) as organizations:
|
|
|
|
|
async for hit in organizations:
|
|
|
|
|
stats.scanned += 1
|
|
|
|
|
org_doc_id = str(hit.get("_id") or "")
|
|
|
|
|
org_uri = hit.get("_source", {}).get("uri")
|
|
|
|
|
|
|
|
|
|
# Already uploaded in an earlier run.
|
|
|
|
|
if org_doc_id in progress.processed_org_ids:
|
|
|
|
|
if not cursor_blocked:
|
|
|
|
|
progress.advance_cursor(org_uri)
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
if args.limit is not None and organizations_handled >= args.limit:
|
|
|
|
|
logger.info("Reached --limit=%d.", args.limit)
|
|
|
|
|
break
|
|
|
|
|
|
|
|
|
|
organizations_handled += 1
|
|
|
|
|
if await process_organization(hit, ctx):
|
|
|
|
|
stats.orgs_done += 1
|
|
|
|
|
if not args.dry_run:
|
|
|
|
|
progress.mark_org_done(org_doc_id)
|
|
|
|
|
if not cursor_blocked:
|
|
|
|
|
progress.advance_cursor(org_uri)
|
|
|
|
|
else:
|
|
|
|
|
stats.orgs_failed += 1
|
|
|
|
|
cursor_blocked = True # retry this one on the next run
|
|
|
|
|
|
|
|
|
|
progress.save()
|
|
|
|
|
if time.monotonic() - last_log >= PROGRESS_LOG_INTERVAL_S:
|
|
|
|
|
logger.info("Progress: %s", stats.summary())
|
|
|
|
|
last_log = time.monotonic()
|
|
|
|
|
finally:
|
|
|
|
|
progress.save(force=True)
|
|
|
|
|
|
|
|
|
|
logger.info("Finished: %s progress_file=%s", stats.summary(), args.progress_file)
|
|
|
|
|
return 1 if stats.has_errors else 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# =============================================================================
|
|
|
|
|
# Command line
|
|
|
|
|
# =============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def parse_args() -> argparse.Namespace:
|
|
|
|
|
parser = argparse.ArgumentParser(
|
|
|
|
|
description="Upload UDE OrgMiner persons verified by the collaboration graph."
|
|
|
|
|
)
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
"--progress-file",
|
|
|
|
|
type=Path,
|
|
|
|
|
default=DEFAULT_PROGRESS_FILE,
|
|
|
|
|
help=f"JSON checkpoint file (default: {DEFAULT_PROGRESS_FILE})",
|
|
|
|
|
)
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
"--limit",
|
|
|
|
|
type=int,
|
|
|
|
|
default=None,
|
|
|
|
|
help="Process at most this many not-yet-completed organizations.",
|
|
|
|
|
)
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
"--dry-run",
|
|
|
|
|
action="store_true",
|
|
|
|
|
help=(
|
|
|
|
|
"Verify and count results without creating the index, uploading, "
|
|
|
|
|
"or writing progress. Still reads existing progress unless "
|
|
|
|
|
"--ignore-progress is given."
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
"--ignore-progress",
|
|
|
|
|
action="store_true",
|
|
|
|
|
help="Start from scratch, ignoring any existing progress file contents.",
|
|
|
|
|
)
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
"--fresh",
|
|
|
|
|
action="store_true",
|
|
|
|
|
help=(
|
|
|
|
|
"Delete the selected JSON progress checkpoint and start from the "
|
|
|
|
|
"first source organization. Existing output-index documents are kept."
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
"--fail-fast",
|
|
|
|
|
action="store_true",
|
|
|
|
|
help="Stop at the first organization-level error instead of continuing.",
|
|
|
|
|
)
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
if args.limit is not None and args.limit < 1:
|
|
|
|
|
parser.error("--limit must be at least 1.")
|
|
|
|
|
return args
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
raise SystemExit(asyncio.run(run(parse_args())))
|