Files
smartguide/llm_evaluations/basic_applied_experimental/prepare_classification_data.py
T
Roman d2dec7c6ee
LocationBasedServices/smartguide/pipeline/head This commit looks good
work-classifications
2026-07-14 00:12:31 +02:00

411 lines
12 KiB
Python

from __future__ import annotations
import json
import time
from pathlib import Path
from typing import Any
import requests
PROJECT_ROOT = Path(__file__).resolve().parent
ES_BASE_URL = "https://project.nes.uni-due.de/elastic".rstrip("/")
ES_API_KEY = "am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=="
HEADERS = {
"Authorization": f"ApiKey {ES_API_KEY}",
"Content-Type": "application/json",
"Accept": "application/json",
}
SELECTED_PERSONS_FILE = PROJECT_ROOT / "selected_persons.json"
CLASSIFICATION_DATA_DIR = PROJECT_ROOT / "classification_data"
CLASSIFICATION_REPORT_FILE = (
CLASSIFICATION_DATA_DIR / "selected_persons_classification_report.json"
)
WORKS_INDEX = "openalex-works*"
WORK_YEAR_GTE = 1950
PAGE_SIZE = 500
EXCLUDED_TYPES = {
"editorial",
"erratum",
"paratext",
"retraction",
}
def es_search(index: str, body: dict[str, Any]) -> dict[str, Any]:
url = f"{ES_BASE_URL}/{index}/_search"
response = requests.post(url, headers=HEADERS, json=body, timeout=120)
if not response.ok:
raise RuntimeError(
f"Elasticsearch error {response.status_code} for index {index}:\n"
f"{response.text}"
)
return response.json()
def read_json(path: Path) -> Any:
with path.open("r", encoding="utf-8") as file:
return json.load(file)
def write_json(path: Path, data: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temp_path = path.with_suffix(path.suffix + ".tmp")
temp_path.write_text(
json.dumps(data, ensure_ascii=False, indent=2),
encoding="utf-8",
)
temp_path.replace(path)
def text_present(value: Any) -> bool:
return isinstance(value, str) and bool(value.strip())
def person_filename(person_id: str) -> str:
return person_id.rstrip("/").rsplit("/", 1)[-1]
def unique_clean(values: list[Any], limit: int = 8) -> list[str]:
result: list[str] = []
seen: set[str] = set()
for value in values:
if not text_present(value):
continue
clean = value.strip()
normalized = clean.casefold()
if normalized in seen:
continue
seen.add(normalized)
result.append(clean)
if len(result) >= limit:
break
return result
def get_venue(work: dict[str, Any]) -> str | None:
primary_location = work.get("primary_location") or {}
primary_source = primary_location.get("source") or {}
if text_present(primary_source.get("display_name")):
return primary_source["display_name"]
for location in work.get("locations") or []:
if not isinstance(location, dict):
continue
source = location.get("source") or {}
if text_present(source.get("display_name")):
return source["display_name"]
return None
def get_topics(work: dict[str, Any]) -> list[str]:
values: list[Any] = []
for topic in work.get("topics") or []:
if not isinstance(topic, dict):
continue
values.append(topic.get("display_name"))
subfield = topic.get("subfield") or {}
field = topic.get("field") or {}
if isinstance(subfield, dict):
values.append(subfield.get("display_name"))
if isinstance(field, dict):
values.append(field.get("display_name"))
for concept in work.get("concepts") or []:
if isinstance(concept, dict):
values.append(concept.get("display_name"))
return unique_clean(values, limit=8)
def get_funders(work: dict[str, Any]) -> list[str]:
values: list[Any] = []
for funder in work.get("funders") or []:
if isinstance(funder, dict):
values.append(funder.get("display_name"))
for award in work.get("awards") or []:
if isinstance(award, dict):
values.append(award.get("funder_display_name"))
return unique_clean(values, limit=8)
def to_classification_record(
person: dict[str, Any],
work: dict[str, Any],
) -> dict[str, Any]:
work_type = work.get("type")
abstract = work.get("abstract")
return {
"person": {
"id": person.get("id"),
"display_name": person.get("display_name"),
},
"work_id": work.get("id"),
"doi": work.get("doi"),
"input": {
"title": work.get("title") or work.get("display_name"),
"abstract": abstract if text_present(abstract) else None,
"venue": get_venue(work),
"work_type": work_type,
"topics": get_topics(work),
"funders": get_funders(work),
"year": work.get("publication_year"),
"language": work.get("language"),
},
"debug": {
"publication_date": work.get("publication_date"),
"has_abstract": text_present(abstract),
"excluded_type": work_type in EXCLUDED_TYPES,
},
}
def works_by_author_query(
author_id: str,
search_after: list[Any] | None = None,
) -> dict[str, Any]:
body: dict[str, Any] = {
"size": PAGE_SIZE,
"track_total_hits": True,
"_source": [
"id",
"doi",
"title",
"display_name",
"abstract",
"publication_year",
"publication_date",
"type",
"language",
"primary_location.source.display_name",
"primary_location.source.type",
"locations.source.display_name",
"locations.source.type",
"topics.display_name",
"topics.subfield.display_name",
"topics.field.display_name",
"concepts.display_name",
"concepts.score",
"funders.display_name",
"awards.funder_display_name",
],
"query": {
"bool": {
"filter": [
{"range": {"publication_year": {"gte": WORK_YEAR_GTE}}},
{
"nested": {
"path": "authorships",
"query": {
"term": {
"authorships.author.id": author_id,
}
},
}
},
]
}
},
"sort": [
{"publication_year": {"order": "desc"}},
{"id": {"order": "asc"}},
],
}
if search_after is not None:
body["search_after"] = search_after
return body
def fetch_all_works_for_author(
author_id: str,
) -> tuple[list[dict[str, Any]], int, int]:
works_by_id: dict[str, dict[str, Any]] = {}
duplicate_hits_ignored = 0
search_after: list[Any] | None = None
total_hits = 0
hits_read = 0
while True:
result = es_search(
WORKS_INDEX,
works_by_author_query(author_id, search_after),
)
hits = result.get("hits", {}).get("hits", [])
if hits_read == 0:
total = result.get("hits", {}).get("total", 0)
total_hits = int(
total.get("value", 0) if isinstance(total, dict) else total
)
if not hits:
break
for hit in hits:
source = hit.get("_source") or {}
work_id = source.get("id")
if not isinstance(work_id, str) or not work_id:
raise ValueError("Encountered a work without an OpenAlex id")
existing = works_by_id.get(work_id)
if existing is None:
works_by_id[work_id] = source
elif existing == source:
duplicate_hits_ignored += 1
else:
raise ValueError(f"Conflicting records for work_id {work_id}")
hits_read += len(hits)
search_after = hits[-1].get("sort")
if not isinstance(search_after, list):
raise RuntimeError("Missing search_after values in Elasticsearch response")
print(
f" hits read: {hits_read} / {total_hits}; unique works: {len(works_by_id)}"
)
time.sleep(0.05)
return list(works_by_id.values()), total_hits, duplicate_hits_ignored
def validate_selected_persons(data: Any) -> list[dict[str, Any]]:
if not isinstance(data, list):
raise ValueError("selected_persons.json must contain a list")
persons: list[dict[str, Any]] = []
seen_ids: set[str] = set()
for item in data:
if not isinstance(item, dict):
raise ValueError("Each selected person must be an object")
person_id = item.get("id")
if not isinstance(person_id, str) or not person_id:
raise ValueError("Each selected person must have a non-empty id")
if person_id in seen_ids:
raise ValueError(f"Duplicate selected person id: {person_id}")
seen_ids.add(person_id)
persons.append(item)
return persons
def main() -> None:
if ES_API_KEY == "тут код" or not ES_API_KEY.strip():
raise RuntimeError("Set ES_API_KEY in prepare_classification_data.py")
if not SELECTED_PERSONS_FILE.exists():
raise FileNotFoundError(SELECTED_PERSONS_FILE)
CLASSIFICATION_DATA_DIR.mkdir(parents=True, exist_ok=True)
selected_persons = validate_selected_persons(read_json(SELECTED_PERSONS_FILE))
report: dict[str, Any] = {
"config": {
"selected_persons_file": SELECTED_PERSONS_FILE.name,
"classification_data_dir": CLASSIFICATION_DATA_DIR.name,
"works_index": WORKS_INDEX,
"work_year_gte": WORK_YEAR_GTE,
"excluded_types": sorted(EXCLUDED_TYPES),
},
"persons": [],
}
for index, person in enumerate(selected_persons, start=1):
person_id = person["id"]
person_name = person.get("display_name")
short_id = person_filename(person_id)
print(f"\n[{index}/{len(selected_persons)}] {person_name} - {person_id}")
raw_works, total_hits, duplicates_ignored = fetch_all_works_for_author(
person_id
)
classification_records = [
to_classification_record(person, work) for work in raw_works
]
output_path = CLASSIFICATION_DATA_DIR / f"{short_id}.json"
write_json(
output_path,
{
"person": person,
"works": classification_records,
},
)
works_with_abstract = sum(
record["debug"]["has_abstract"] is True for record in classification_records
)
works_excluded_type = sum(
record["debug"]["excluded_type"] is True
for record in classification_records
)
report["persons"].append(
{
"id": person_id,
"display_name": person_name,
"output_file": output_path.relative_to(PROJECT_ROOT).as_posix(),
"elasticsearch_hits_total": total_hits,
"duplicate_hits_ignored": duplicates_ignored,
"works_total": len(classification_records),
"works_with_abstract": works_with_abstract,
"works_without_abstract": (
len(classification_records) - works_with_abstract
),
"works_excluded_type": works_excluded_type,
}
)
print(f" written: {output_path.relative_to(PROJECT_ROOT).as_posix()}")
print(f" unique works: {len(classification_records)}")
print(f" duplicate hits ignored: {duplicates_ignored}")
print(f" with abstract: {works_with_abstract}")
print(f" excluded type: {works_excluded_type}")
write_json(CLASSIFICATION_REPORT_FILE, report)
print("\nDone.")
print(
"Report written: "
f"{CLASSIFICATION_REPORT_FILE.relative_to(PROJECT_ROOT).as_posix()}"
)
if __name__ == "__main__":
main()