Files
smartguide/service/scripts/projects/map_project_topics.py
T
arzani 54696df912
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
job for matching projects to openalex topics, can be used for bund, eu and eventually dfg
2026-07-13 22:11:41 +02:00

549 lines
19 KiB
Python

#!/usr/bin/env python3
"""
map_project_topics.py — Map project keywords to OpenAlex topics.
Streams all documents from a source index, reads a configurable text field
(the "project-specific keyword"), matches every unique keyword against
OpenAlex topics, and persists one document per (project, keyword) pair into
the output index using mapping.PROJECT_TOPICS_MAPPING:
{project_id, keyword, source_index, source_field, topic_matches[],
match_method, model_name, built_at}
The run is resumable: source documents whose id already exists in the output
index are skipped, so a crashed or interrupted run can simply be restarted.
Each unique keyword is searched only once and results are bulk-indexed
incrementally, chunk by chunk.
Usage (bund, keyword unique per project, project id is the document _id):
python map_project_topics.py \
--source-index projects_bund_v1 \
--text-field Leistungsplansystematik_fullname \
--output-index projects_bund_openalex_topics
Usage (EU EuroSciVoc, project id in the projectID source field):
python map_project_topics.py \
--source-index cordis_eu_fp7_euroscivoc \
--text-field title \
--project-id-field projectID \
--output-index projects_eu_openalex_topics
Requires ELASTICSEARCH_INSE_URL/ELASTICSEARCH_INSE_API_KEY (and for
--*-cluster nes: ELASTICSEARCH_URL/ELASTICSEARCH_API_KEY) in the environment
or in the service .env, plus a running backend serving
/api/topics/vector-search (e.g. ./gradlew serve).
"""
from __future__ import annotations
import argparse
import asyncio
import json
import logging
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, AsyncIterator
import httpx
from dotenv import load_dotenv
sys.path.insert(0, str(Path(__file__).resolve().parent))
from mapping import PROJECT_TOPICS_MAPPING
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
DEFAULT_ENV_FILE = Path(__file__).resolve().parents[2] / "src" / "main" / "inse" / ".env"
DEFAULT_API_BASE_URL = "http://localhost:8000" #backend TODO replace with env variable
VECTOR_SEARCH_PATH = "/api/topics/vector-search"
MATCH_METHOD = "sentence_transformer"
SEARCH_CONCURRENCY = 8
TEXT_BATCH_SIZE = 100
SCAN_PAGE_SIZE = 1000
BULK_BATCH_SIZE = 500
MAX_RETRIES = 3
RETRY_BACKOFF_SECONDS = 5
_http_client: httpx.AsyncClient | None = None
def get_http_client() -> httpx.AsyncClient:
global _http_client
if _http_client is None:
_http_client = httpx.AsyncClient(timeout=60.0)
return _http_client
def es_credentials(cluster: str) -> tuple[str, str]:
"""Returns (url, api_key) for a cluster from the environment."""
env_names = {
"inse": ("ELASTICSEARCH_INSE_URL", "ELASTICSEARCH_INSE_API_KEY"),
"nes": ("ELASTICSEARCH_URL", "ELASTICSEARCH_API_KEY"),
}
url_var, key_var = env_names[cluster]
url, api_key = os.getenv(url_var), os.getenv(key_var)
if not url or not api_key:
raise SystemExit(
f"{url_var} and {key_var} must be set (via environment or --env-file)."
)
return url.rstrip("/"), api_key
def es_headers(cluster: str, content_type: str = "application/json") -> tuple[str, dict]:
url, api_key = es_credentials(cluster)
return url, {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type}
async def with_retries(coro_factory, description: str):
"""Retries transient network failures with a linear backoff."""
for attempt in range(1, MAX_RETRIES):
try:
return await coro_factory()
except Exception:
logger.exception(
"%s failed (attempt %d/%d), retrying in %ds...",
description,
attempt,
MAX_RETRIES,
RETRY_BACKOFF_SECONDS * attempt,
)
await asyncio.sleep(RETRY_BACKOFF_SECONDS * attempt)
return await coro_factory()
async def scan(
index: str, cluster: str, query: dict, source: list[str]
) -> AsyncIterator[dict[str, Any]]:
"""Yields every hit matching query via point-in-time + search_after."""
url, headers = es_headers(cluster)
client = get_http_client()
response = await client.post(
f"{url}/{index}/_pit?keep_alive=1m", headers=headers
)
response.raise_for_status()
pit_id = response.json()["id"]
search_after: list | None = None
try:
while True:
payload: dict[str, Any] = {
"size": SCAN_PAGE_SIZE,
"query": query,
"pit": {"id": pit_id, "keep_alive": "1m"},
"sort": [{"_shard_doc": "asc"}],
"track_total_hits": False,
"_source": source,
}
if search_after is not None:
payload["search_after"] = search_after
response = await with_retries(
lambda: client.post(f"{url}/_search", json=payload, headers=headers),
f"Scanning '{index}'",
)
response.raise_for_status()
result = response.json()
hits = result.get("hits", {}).get("hits", [])
if not hits:
break
for hit in hits:
yield hit
pit_id = result.get("pit_id", pit_id)
search_after = hits[-1].get("sort")
if search_after is None or len(hits) < SCAN_PAGE_SIZE:
break
finally:
try:
await client.request(
"DELETE", f"{url}/_pit", json={"id": pit_id}, headers=headers
)
except Exception:
logger.exception("Failed to close Elasticsearch point-in-time.")
async def check_backend(api_base_url: str) -> None:
"""Fails fast with a clear message if the backend is not reachable."""
client = get_http_client()
try:
response = await client.get(
f"{api_base_url}{VECTOR_SEARCH_PATH}", params={"query": "test", "limit": 1}
)
response.raise_for_status()
except Exception as exc:
raise SystemExit(
f"Backend not reachable at {api_base_url}{VECTOR_SEARCH_PATH} ({exc}). "
"Start the service (e.g. ./gradlew serve) or pass --api-base-url."
) from exc
logger.info("Backend reachable at %s%s.", api_base_url, VECTOR_SEARCH_PATH)
async def ensure_index(index: str, cluster: str) -> None:
"""Creates the output index with the explicit mapping if it does not exist."""
url, headers = es_headers(cluster)
client = get_http_client()
response = await client.head(f"{url}/{index}", headers=headers)
if response.status_code == 200:
logger.info("Output index '%s' already exists.", index)
return
response = await client.put(
f"{url}/{index}", json={"mappings": PROJECT_TOPICS_MAPPING}, headers=headers
)
response.raise_for_status()
logger.info("Created output index '%s' with explicit mapping.", index)
async def fetch_source_entries(
index: str, cluster: str, text_field: str, id_field: str | None, max_docs: int | None
) -> dict[str, tuple[str, str]]:
"""Returns doc_id -> (project_id, keyword) for every source document."""
entries: dict[str, tuple[str, str]] = {}
total = 0
if id_field == "_id":
id_field = None
source_fields = [text_field] + ([id_field] if id_field else [])
async for hit in scan(
index=index,
cluster=cluster,
query={"exists": {"field": text_field}},
source=source_fields,
):
total += 1
doc_source = hit.get("_source", {})
text = str(doc_source.get(text_field) or "").strip()
project_id = str(doc_source.get(id_field) or "").strip() if id_field else hit["_id"]
if text and project_id:
entries[hit["_id"]] = (project_id, text)
if total % 50000 == 0:
logger.info("Scanned %d source documents...", total)
if max_docs and total >= max_docs:
logger.info("Stopping scan at --max-docs=%d.", max_docs)
break
logger.info(
"Scanned %d documents from '%s', %d with a non-empty '%s'.",
total,
index,
len(entries),
text_field,
)
return entries
async def fetch_covered_doc_ids(index: str, cluster: str) -> set[str]:
"""Returns the document ids that already exist in the output index."""
covered: set[str] = set()
try:
async for hit in scan(index=index, cluster=cluster, query={"match_all": {}}, source=[]):
covered.add(hit["_id"])
except Exception:
logger.info("Output index '%s' not readable yet — starting from scratch.", index)
return set()
return covered
def build_topic_matches(topics: list[dict]) -> list[dict]:
"""Maps /api/topics/vector-search results to ranked topic_matches entries.
The endpoint does not expose Elasticsearch scores, so match_score stays null;
rank preserves the search result order.
"""
matches = []
seen_ids = set()
for topic in topics:
topic_id = topic.get("id")
if not topic_id or topic_id in seen_ids:
continue
seen_ids.add(topic_id)
matches.append(
{
"rank": len(matches) + 1,
"topic_id": topic_id,
"topic_display_name": topic.get("display_name"),
"subfield": (topic.get("subfield") or {}).get("display_name"),
"field": (topic.get("field") or {}).get("display_name"),
"domain": (topic.get("domain") or {}).get("display_name"),
"match_score": None,
}
)
return matches
async def match_keywords(
keywords: list[str], api_base_url: str, top_k: int, search_type: str
) -> dict[str, list[dict]]:
"""Searches topics for a chunk of keywords via the backend API, concurrently.
Keywords whose search failed are missing from the result, so they are
retried on the next run instead of being persisted with empty matches.
"""
client = get_http_client()
semaphore = asyncio.Semaphore(SEARCH_CONCURRENCY)
async def search_one(keyword: str) -> tuple[str, list[dict] | None]:
async def request():
response = await client.get(
f"{api_base_url}{VECTOR_SEARCH_PATH}",
params={"query": keyword, "limit": top_k, "searchType": search_type},
)
response.raise_for_status()
return response.json()
async with semaphore:
try:
data = await with_retries(request, f"Topic search for '{keyword[:60]}'")
except Exception:
logger.exception("Topic-Matching fuer Keyword '%s' fehlgeschlagen.", keyword)
return keyword, None
return keyword, build_topic_matches(data.get("results") or [])
results = await asyncio.gather(*(search_one(keyword) for keyword in keywords))
return {keyword: matches for keyword, matches in results if matches is not None}
async def bulk_index(index: str, cluster: str, documents: list[tuple[str, dict]]) -> None:
"""Bulk-indexes (doc_id, document) pairs in batches."""
url, headers = es_headers(cluster, content_type="application/x-ndjson")
client = get_http_client()
for start in range(0, len(documents), BULK_BATCH_SIZE):
batch = documents[start : start + BULK_BATCH_SIZE]
lines = []
for doc_id, doc in batch:
lines.append(json.dumps({"index": {"_index": index, "_id": doc_id}}))
lines.append(json.dumps(doc, ensure_ascii=False))
payload = "\n".join(lines) + "\n"
async def send():
response = await client.post(f"{url}/_bulk", content=payload, headers=headers)
response.raise_for_status()
return response.json()
result = await with_retries(send, f"Bulk indexing {len(batch)} documents")
if result.get("errors"):
failed = [
item["index"].get("error")
for item in result.get("items", [])
if item.get("index", {}).get("error")
]
logger.error("Bulk batch had %d failures, first: %s", len(failed), failed[:1])
async def run(args: argparse.Namespace) -> None:
built_at = datetime.now(timezone.utc).isoformat()
model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME")
await check_backend(args.api_base_url)
if not args.dry_run:
await ensure_index(index=args.output_index, cluster=args.output_cluster)
entries = await fetch_source_entries(
index=args.source_index,
cluster=args.source_cluster,
text_field=args.text_field,
id_field=args.project_id_field,
max_docs=args.max_docs,
)
if not entries:
logger.warning("No usable documents in '%s' — nothing to do.", args.source_index)
return
covered = await fetch_covered_doc_ids(index=args.output_index, cluster=args.output_cluster)
pending = {doc_id: entry for doc_id, entry in entries.items() if doc_id not in covered}
logger.info(
"Coverage: %d/%d documents already in '%s', %d still to be processed.",
len(entries) - len(pending),
len(entries),
args.output_index,
len(pending),
)
if not pending:
logger.info("Nothing left to process.")
return
docs_by_keyword: dict[str, list[tuple[str, str]]] = {}
for doc_id, (project_id, keyword) in pending.items():
docs_by_keyword.setdefault(keyword, []).append((doc_id, project_id))
unique_keywords = sorted(docs_by_keyword)
logger.info(
"%d unique keywords cover the %d pending documents.",
len(unique_keywords),
len(pending),
)
backup_docs: list[dict] = []
docs_done = 0
keywords_done = 0
for start in range(0, len(unique_keywords), args.text_batch_size):
chunk = unique_keywords[start : start + args.text_batch_size]
matches_by_keyword = await match_keywords(
chunk,
api_base_url=args.api_base_url,
top_k=args.top_k,
search_type=args.search_type,
)
documents = []
for keyword in chunk:
if keyword not in matches_by_keyword:
continue # search failed — left for the next run
for doc_id, project_id in docs_by_keyword[keyword]:
documents.append(
(
doc_id,
{
"project_id": project_id,
"keyword": keyword,
"source_index": args.source_index,
"source_field": args.text_field,
"topic_matches": matches_by_keyword[keyword],
"match_method": MATCH_METHOD,
"model_name": model_name,
"built_at": built_at,
},
)
)
if documents and not args.dry_run:
await bulk_index(
index=args.output_index, cluster=args.output_cluster, documents=documents
)
if args.output:
backup_docs.extend(doc for _, doc in documents)
keywords_done += len(chunk)
docs_done += len(documents)
logger.info(
"Progress: %d/%d keywords, %d/%d pending documents indexed into '%s'.",
keywords_done,
len(unique_keywords),
docs_done,
len(pending),
args.output_index,
)
skipped = len(pending) - docs_done
if skipped:
logger.warning(
"%d documents were NOT indexed due to failed searches — rerun the script to retry.",
skipped,
)
if args.output:
output_path = Path(args.output)
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(
json.dumps(backup_docs, indent=2, ensure_ascii=False), encoding="utf-8"
)
logger.info("Wrote local JSON backup (%d documents) to %s", len(backup_docs), output_path)
logger.info(
"Done. %d documents indexed this run, %d covered in total.",
docs_done,
len(covered) + docs_done,
)
def main() -> None:
parser = argparse.ArgumentParser(
description="Map a project index's keyword field to OpenAlex topics.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=(
"Examples:\n"
" python map_project_topics.py --source-index projects_bund_v1 "
"--text-field Leistungsplansystematik_fullname --output-index projects_bund_openalex_topics\n"
" python map_project_topics.py --source-index cordis_eu_fp7_euroscivoc "
"--text-field title --project-id-field projectID --output-index projects_eu_openalex_topics"
),
)
parser.add_argument("--source-index", required=True, help="Index to read projects from")
parser.add_argument(
"--text-field",
required=True,
help="Source field holding the project-specific keyword to match",
)
parser.add_argument(
"--output-index", required=True, help="Index to persist the topic mappings into"
)
parser.add_argument(
"--project-id-field",
default="_id",
help=(
"Source field holding the project id, e.g. projectID for the EuroSciVoc "
"indices (default: _id, the Elasticsearch document id)"
),
)
parser.add_argument(
"--source-cluster",
default="inse",
choices=["inse", "nes"],
help="Cluster of the source index (default: inse)",
)
parser.add_argument(
"--output-cluster",
default="inse",
choices=["inse", "nes"],
help="Cluster of the output index (default: inse)",
)
parser.add_argument(
"--api-base-url",
default=DEFAULT_API_BASE_URL,
help=f"Base URL of the running backend (default: {DEFAULT_API_BASE_URL})",
)
parser.add_argument(
"--top-k", type=int, default=3, help="Number of topic matches per keyword (default: 3)"
)
parser.add_argument(
"--search-type",
default="hybrid",
choices=["hybrid", "semantic"],
help="Topic search type, mirrors vector_search_topics (default: hybrid)",
)
parser.add_argument(
"--text-batch-size",
type=int,
default=TEXT_BATCH_SIZE,
help=f"Unique keywords searched per chunk (default: {TEXT_BATCH_SIZE})",
)
parser.add_argument(
"--env-file",
default=str(DEFAULT_ENV_FILE),
help=f"Path to a .env with Elasticsearch credentials (default: {DEFAULT_ENV_FILE})",
)
parser.add_argument(
"--max-docs",
type=int,
default=None,
help="Stop scanning the source index after N documents (for test runs)",
)
parser.add_argument(
"--output",
default=None,
help="Optional path for a local JSON backup of the documents built this run",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Build the mapping without creating/writing the output index",
)
args = parser.parse_args()
if args.env_file and Path(args.env_file).exists():
load_dotenv(dotenv_path=args.env_file)
asyncio.run(run(args))
if __name__ == "__main__":
main()