LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
637 lines
30 KiB
Python
637 lines
30 KiB
Python
"""
|
|
load_graph.py — Minimal FalkorDB example for the INSE backend.
|
|
|
|
Builds a small knowledge graph around a couple of researchers from the predefined
|
|
("default") organizations in src/data/predefined_accounts.json, using only the
|
|
backend's existing data-source logic (everything reads the INSE Elasticsearch mirrors):
|
|
|
|
OpenAlex authors, works, topics, institutions -> inse.authors.v2 / inse.works.v2 / inse.institutions.v2
|
|
EPO + USPTO patents -> inse.patents.authors.logic
|
|
CORDIS (EU) + DFG projects, via publication DOIs -> inse.works.logic + inse.projects.*
|
|
Funders of the author's funded publications -> inse.funders.logic
|
|
News mentions (UDE "aktuell" + CC-News) -> inse.news.logic
|
|
Handelsregister company officer matches -> inse.company_connections.logic
|
|
|
|
The collected nodes/edges are written to FalkorDB with batched UNWIND ... MERGE
|
|
queries, and CO_AUTHOR edges are then derived inside the graph with one Cypher query.
|
|
|
|
Usage (see run.sh for running inside the service image):
|
|
python scripts/falkordb/load_graph.py # 2 researchers per default org
|
|
python scripts/falkordb/load_graph.py --organization "Duisburg" --per-org 3
|
|
python scripts/falkordb/load_graph.py --author-id A5040796987 --author-id A5119657791
|
|
python scripts/falkordb/load_graph.py --reset --dump /tmp/graph.json --skip news --skip companies
|
|
|
|
FalkorDB connection: --falkordb-host/--falkordb-port/--falkordb-password or the
|
|
FALKORDB_HOST / FALKORDB_PORT / FALKORDB_PASSWORD environment variables.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
import os
|
|
import re
|
|
import sys
|
|
import time
|
|
from collections import Counter, defaultdict
|
|
from dataclasses import dataclass, field
|
|
from datetime import date, datetime
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
# --- locate the backend package (works from the repo checkout and inside the service image) ---
|
|
_current_dir = Path(__file__).resolve().parent
|
|
_service_dir = _current_dir.parent.parent
|
|
_src_main = _service_dir / "src" / "main"
|
|
if not (_src_main / "inse").is_dir():
|
|
_src_main = Path(os.environ.get("INSE_SRC_DIR", "/home"))
|
|
sys.path.insert(0, str(_src_main))
|
|
|
|
from dotenv import load_dotenv # noqa: E402
|
|
|
|
_env_file = _src_main / "inse" / ".env"
|
|
if _env_file.exists():
|
|
load_dotenv(dotenv_path=_env_file)
|
|
|
|
# inse.config reads the .env at import time, so these imports must come after load_dotenv.
|
|
from inse.authors.institution_membership_query import ( # noqa: E402
|
|
build_institution_membership_query,
|
|
current_affiliation_year_cutoff,
|
|
)
|
|
from inse.authors.v2.service import get_author_by_id_strict_or_raise, search_authors # noqa: E402
|
|
from inse.company_connections.logic import get_company_connections_by_author_id # noqa: E402
|
|
from inse.funders.logic import get_funders_by_author_id # noqa: E402
|
|
from inse.institutions.v2.service import get_institution_by_id # noqa: E402
|
|
from inse.models.openalex.author import Author # noqa: E402
|
|
from inse.news.logic import get_news_by_author # noqa: E402
|
|
from inse.patents.authors.logic import get_patents_by_author_id # noqa: E402
|
|
from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id # noqa: E402
|
|
from inse.projects.projects_search_client import ( # noqa: E402
|
|
get_cordis_eu_project_ids_by_dois,
|
|
get_dfg_project_by_id,
|
|
get_dfg_project_ids_by_dois,
|
|
)
|
|
from inse.works.logic import get_publication_dois_of_author # noqa: E402
|
|
from inse.works.v2.service import get_author_works # noqa: E402
|
|
|
|
logger = logging.getLogger("falkordb.load_graph")
|
|
|
|
OPENALEX_PREFIX = "https://openalex.org/"
|
|
PREDEFINED_ACCOUNTS = _src_main.parent / "data" / "predefined_accounts.json"
|
|
SOURCES = ("works", "projects", "patents", "funders", "news", "companies")
|
|
_IDENT = re.compile(r"^[A-Z][A-Za-z_]*$")
|
|
|
|
|
|
# --------------------------------------------------------------------------- helpers
|
|
def short_id(raw: str | None) -> str | None:
|
|
"""'https://openalex.org/A123' -> 'A123' (OpenAlex ids are stored as URLs in ES)."""
|
|
if not raw:
|
|
return None
|
|
return raw.strip().removeprefix(OPENALEX_PREFIX)
|
|
|
|
|
|
def raw_doi(doi: str) -> str:
|
|
for prefix in ("https://doi.org/", "http://doi.org/", "http://dx.doi.org/"):
|
|
if doi.startswith(prefix):
|
|
return doi[len(prefix):]
|
|
return doi
|
|
|
|
|
|
def _scalar(value: Any) -> Any:
|
|
if isinstance(value, (date, datetime)):
|
|
return value.isoformat()
|
|
if isinstance(value, str):
|
|
return value[:2000]
|
|
if isinstance(value, (bool, int, float)):
|
|
return value
|
|
return str(value)
|
|
|
|
|
|
def clean_props(props: dict[str, Any]) -> dict[str, Any]:
|
|
"""FalkorDB properties must be scalars or lists of scalars; drop None/dicts."""
|
|
cleaned: dict[str, Any] = {}
|
|
for key, value in props.items():
|
|
if value is None or isinstance(value, dict):
|
|
continue
|
|
if isinstance(value, (list, tuple, set)):
|
|
cleaned[key] = [_scalar(v) for v in value if v is not None and not isinstance(v, dict)]
|
|
else:
|
|
cleaned[key] = _scalar(value)
|
|
return cleaned
|
|
|
|
|
|
@dataclass
|
|
class GraphBatch:
|
|
"""In-memory node/edge accumulator. First writer of a property wins, so seed
|
|
authors (hydrated first) keep their full profile when they reappear as co-authors."""
|
|
|
|
nodes: dict[tuple[str, str], dict[str, Any]] = field(default_factory=dict)
|
|
edges: dict[tuple[str, str, str, str, str], dict[str, Any]] = field(default_factory=dict)
|
|
|
|
def node(self, label: str, node_id: str | None, **props: Any) -> None:
|
|
if not node_id:
|
|
return
|
|
props = clean_props(props)
|
|
existing = self.nodes.setdefault((label, node_id), {})
|
|
for key, value in props.items():
|
|
existing.setdefault(key, value)
|
|
|
|
def edge(self, src_label: str, src: str | None, rel: str, dst_label: str, dst: str | None, **props: Any) -> None:
|
|
if not src or not dst:
|
|
return
|
|
props = clean_props(props)
|
|
existing = self.edges.setdefault((src_label, src, rel, dst_label, dst), {})
|
|
for key, value in props.items():
|
|
existing.setdefault(key, value)
|
|
|
|
def has_node(self, label: str, node_id: str | None) -> bool:
|
|
return bool(node_id) and (label, node_id) in self.nodes
|
|
|
|
def summary(self) -> tuple[Counter, Counter]:
|
|
return (
|
|
Counter(label for label, _ in self.nodes),
|
|
Counter(rel for _, _, rel, _, _ in self.edges),
|
|
)
|
|
|
|
def to_json(self) -> dict[str, Any]:
|
|
return {
|
|
"nodes": [{"label": l, "id": i, "props": p} for (l, i), p in self.nodes.items()],
|
|
"edges": [
|
|
{"src_label": sl, "src": s, "rel": r, "dst_label": dl, "dst": d, "props": p}
|
|
for (sl, s, r, dl, d), p in self.edges.items()
|
|
],
|
|
}
|
|
|
|
|
|
def add_topic(batch: GraphBatch, topic: Any) -> str | None:
|
|
"""Topic node from an OpenAlex WorkTopic-like object (works, authors, patents, news)."""
|
|
tid = short_id(getattr(topic, "id", None))
|
|
if not tid:
|
|
return None
|
|
subfield = getattr(topic, "subfield", None)
|
|
field_ = getattr(topic, "var_field", None) or getattr(topic, "field", None)
|
|
domain = getattr(topic, "domain", None)
|
|
batch.node(
|
|
"Topic",
|
|
tid,
|
|
name=getattr(topic, "display_name", None),
|
|
subfield=getattr(subfield, "display_name", None),
|
|
field=getattr(field_, "display_name", None),
|
|
domain=getattr(domain, "display_name", None),
|
|
)
|
|
return tid
|
|
|
|
|
|
# --------------------------------------------------------------------------- organizations
|
|
def load_default_organizations() -> list[dict[str, str]]:
|
|
"""The predefined organizations seeded at startup (auth.service.create_predefined_accounts)."""
|
|
with open(PREDEFINED_ACCOUNTS, encoding="utf-8") as fh:
|
|
data = json.load(fh)
|
|
return [
|
|
{"name": org["name"], "institution_id": org["openalex_institution_id"]}
|
|
for org in data.get("organizations", [])
|
|
if org.get("openalex_institution_id")
|
|
]
|
|
|
|
|
|
def select_organizations(orgs: list[dict[str, str]], wanted: list[str]) -> list[dict[str, str]]:
|
|
if not wanted:
|
|
return orgs
|
|
selected = []
|
|
for term in wanted:
|
|
term_l = term.lower()
|
|
matches = [o for o in orgs if term_l in o["name"].lower() or term_l == o["institution_id"].lower()]
|
|
if not matches:
|
|
raise SystemExit(f"No default organization matches {term!r}. Known: {[o['name'] for o in orgs]}")
|
|
selected.extend(m for m in matches if m not in selected)
|
|
return selected
|
|
|
|
|
|
async def ensure_organization_nodes(batch: GraphBatch, org: dict[str, str]) -> None:
|
|
"""Organization (from predefined_accounts.json) + its OpenAlex institution."""
|
|
if batch.has_node("Organization", org["name"]):
|
|
return
|
|
institution = await get_institution_by_id(org["institution_id"])
|
|
batch.node("Organization", org["name"], name=org["name"], openalex_institution_id=org["institution_id"])
|
|
batch.node(
|
|
"Institution", org["institution_id"],
|
|
name=getattr(institution, "display_name", None) or org["name"],
|
|
ror=getattr(institution, "ror", None),
|
|
country_code=getattr(institution, "country_code", None),
|
|
type=str(institution.type) if getattr(institution, "type", None) else None,
|
|
)
|
|
batch.edge("Organization", org["name"], "REPRESENTS", "Institution", org["institution_id"])
|
|
|
|
|
|
def organization_of(author: Author, orgs: list[dict[str, str]]) -> dict[str, str] | None:
|
|
"""Default organization whose institution is among the author's last known institutions."""
|
|
last_known = {short_id(i.id) for i in (author.last_known_institutions or []) if i.id}
|
|
return next((org for org in orgs if org["institution_id"] in last_known), None)
|
|
|
|
|
|
async def pick_seed_authors(
|
|
institution_id: str, per_org: int, min_works: int, max_works: int, require_orcid: bool
|
|
) -> list[Author]:
|
|
"""Seed researchers of an institution.
|
|
|
|
Reuses the backend's active-cohort membership query (last known institution plus an
|
|
affiliation since the current year minus two, the same rule the app uses for
|
|
"currently belongs to institution"), then narrows the candidates so the example graph
|
|
stays small and well disambiguated:
|
|
* works_count within [min_works, max_works] -> skips hyper-authorship profiles
|
|
* an ORCID (optional) -> better-disambiguated OpenAlex profiles
|
|
* every last-known institution inside the institution's OpenAlex lineage
|
|
-> drops merged profiles that also "currently" belong to unrelated institutions
|
|
"""
|
|
institution_url = f"{OPENALEX_PREFIX}{institution_id}"
|
|
filters: list[dict[str, Any]] = [
|
|
build_institution_membership_query(institution_id, year_mode="from", year=current_affiliation_year_cutoff()),
|
|
{"range": {"works_count": {"gte": min_works, "lte": max_works}}},
|
|
]
|
|
if require_orcid:
|
|
filters.append({"exists": {"field": "orcid"}})
|
|
page = await search_authors(
|
|
page=0,
|
|
size=max(20, per_org * 20),
|
|
query={"bool": {"filter": filters}},
|
|
sort=[{"works_count": {"order": "desc"}}, {"cited_by_count": {"order": "desc"}}],
|
|
)
|
|
|
|
def within_lineage(author: Author) -> bool:
|
|
return all(
|
|
inst.id == institution_url or institution_url in (inst.lineage or [])
|
|
for inst in (author.last_known_institutions or [])
|
|
)
|
|
|
|
return [author for author in page.elements if within_lineage(author)][:per_org]
|
|
|
|
|
|
# --------------------------------------------------------------------------- collectors
|
|
def collect_author_profile(batch: GraphBatch, author: Author, org_name: str | None) -> str:
|
|
aid = short_id(author.id)
|
|
stats = author.summary_stats
|
|
batch.node(
|
|
"Author",
|
|
aid,
|
|
name=author.display_name,
|
|
orcid=author.orcid,
|
|
works_count=author.works_count,
|
|
cited_by_count=author.cited_by_count,
|
|
h_index=getattr(stats, "h_index", None),
|
|
i10_index=getattr(stats, "i10_index", None),
|
|
seed=True,
|
|
)
|
|
if org_name:
|
|
batch.edge("Author", aid, "MEMBER_OF", "Organization", org_name)
|
|
|
|
last_known = {short_id(i.id) for i in (author.last_known_institutions or []) if i.id}
|
|
for affiliation in author.affiliations or []:
|
|
inst = affiliation.institution
|
|
iid = short_id(inst.id) if inst else None
|
|
if not iid:
|
|
continue
|
|
batch.node("Institution", iid, name=inst.display_name, country_code=inst.country_code, type=inst.type, ror=inst.ror)
|
|
batch.edge(
|
|
"Author", aid, "AFFILIATED_WITH", "Institution", iid,
|
|
years=sorted(affiliation.years or []),
|
|
last_known=iid in last_known,
|
|
)
|
|
for topic in author.topics or []:
|
|
tid = add_topic(batch, topic)
|
|
if tid:
|
|
batch.edge("Author", aid, "WORKS_ON", "Topic", tid, score=getattr(topic, "score", None))
|
|
return aid
|
|
|
|
|
|
async def collect_works(batch: GraphBatch, aid: str, max_works: int, max_authors_per_work: int) -> int:
|
|
page = await get_author_works(aid, page=0, size=max_works)
|
|
for work in page.elements:
|
|
wid = short_id(work.id)
|
|
if not wid:
|
|
continue
|
|
authorships = work.authorships or []
|
|
hyper = len(authorships) > max_authors_per_work
|
|
batch.node(
|
|
"Work", wid,
|
|
title=work.title or work.display_name,
|
|
year=work.publication_year,
|
|
type=work.type,
|
|
language=work.language,
|
|
cited_by_count=work.cited_by_count,
|
|
authors_count=len(authorships),
|
|
hyperauthorship=hyper,
|
|
)
|
|
for topic in work.topics or []:
|
|
tid = add_topic(batch, topic)
|
|
if tid:
|
|
batch.edge("Work", wid, "HAS_TOPIC", "Topic", tid, score=topic.score)
|
|
for authorship in authorships:
|
|
author = authorship.author
|
|
cid = short_id(author.id) if author else None
|
|
if not cid or (hyper and cid != aid):
|
|
continue # for hyper-authorship works only keep the seed author's own edge
|
|
batch.node("Author", cid, name=author.display_name, orcid=author.orcid, seed=False)
|
|
batch.edge(
|
|
"Author", cid, "AUTHORED", "Work", wid,
|
|
position=authorship.author_position,
|
|
corresponding=authorship.is_corresponding,
|
|
)
|
|
for inst in authorship.institutions or []:
|
|
iid = short_id(inst.id)
|
|
if iid:
|
|
batch.node("Institution", iid, name=inst.display_name, country_code=inst.country_code, type=inst.type)
|
|
batch.edge("Author", cid, "AFFILIATED_WITH", "Institution", iid)
|
|
return len(page.elements)
|
|
|
|
|
|
async def collect_projects(batch: GraphBatch, aid: str) -> int:
|
|
"""Author -> project bridge used elsewhere in the backend: the author's publication DOIs
|
|
are looked up in the CORDIS publication index and in the DFG projects' publication lists."""
|
|
dois = await get_publication_dois_of_author(aid)
|
|
if not dois:
|
|
return 0
|
|
doi_variants = sorted({v for d in dois for v in (d, raw_doi(d), raw_doi(d).lower())})
|
|
cordis_ids = await get_cordis_eu_project_ids_by_dois(dois)
|
|
dfg_ids = await get_dfg_project_ids_by_dois(doi_variants)
|
|
|
|
for pid in cordis_ids:
|
|
node_id = f"cordis:{pid}"
|
|
details = await get_enriched_cordis_project_by_id(str(pid))
|
|
batch.node(
|
|
"Project", node_id,
|
|
source="cordis", source_id=str(pid),
|
|
title=getattr(details, "title", None),
|
|
acronym=getattr(details, "acronym", None),
|
|
start=getattr(details, "start_date", None),
|
|
end=getattr(details, "end_date", None),
|
|
funding_scheme=getattr(details, "funding_scheme", None),
|
|
status=getattr(details, "status", None),
|
|
ec_max_contribution=getattr(details, "ec_max_contribution", None),
|
|
)
|
|
batch.edge("Author", aid, "CONTRIBUTED_TO", "Project", node_id, via="publication_doi")
|
|
for pid in dfg_ids:
|
|
node_id = f"dfg:{pid}"
|
|
details = await get_dfg_project_by_id(str(pid))
|
|
batch.node(
|
|
"Project", node_id,
|
|
source="dfg", source_id=str(pid),
|
|
title=getattr(details, "title_en", None) or getattr(details, "title_de", None),
|
|
start=getattr(details, "funding_start", None),
|
|
end=getattr(details, "funding_end", None),
|
|
funding_scheme=getattr(details, "funding_type_en", None) or getattr(details, "funding_type_de", None),
|
|
url=getattr(details, "page_url", None) or getattr(details, "link", None),
|
|
)
|
|
batch.edge("Author", aid, "CONTRIBUTED_TO", "Project", node_id, via="publication_doi")
|
|
return len(cordis_ids) + len(dfg_ids)
|
|
|
|
|
|
async def collect_patents(batch: GraphBatch, aid: str) -> int:
|
|
response = await get_patents_by_author_id(aid)
|
|
for patent in response.patents:
|
|
pid = f"{patent.source}:{patent.patent_id}"
|
|
year = int(patent.publication_year) if patent.publication_year and patent.publication_year.isdigit() else None
|
|
batch.node(
|
|
"Patent", pid,
|
|
patent_id=patent.patent_id, source=patent.source,
|
|
title=patent.title or patent.title_en or patent.title_de,
|
|
year=year, publication_date=patent.publication_date,
|
|
kind=patent.kind, status=patent.status, country=patent.country,
|
|
ipc=patent.ipc, assignees=patent.assignees, inventors=patent.inventors,
|
|
)
|
|
batch.edge("Author", aid, "INVENTOR_OF", "Patent", pid)
|
|
for tag in patent.openalex_topics:
|
|
tid = short_id(tag.topic_id)
|
|
if tid:
|
|
batch.node("Topic", tid, name=tag.topic_display_name, field=tag.field_name, domain=tag.domain_name)
|
|
batch.edge("Patent", pid, "HAS_TOPIC", "Topic", tid)
|
|
return response.patent_count
|
|
|
|
|
|
async def collect_funders(batch: GraphBatch, aid: str) -> int:
|
|
response = await get_funders_by_author_id(aid)
|
|
for funder in response.funders:
|
|
fid = short_id(funder.funder_id) or f"name:{funder.funder_name}"
|
|
batch.node("Funder", fid, name=funder.funder_name)
|
|
batch.edge("Author", aid, "FUNDED_BY", "Funder", fid, publications=funder.publication_count)
|
|
ids = funder.publication_ids
|
|
for wid_raw in ids.first + ids.middle + ids.last + ids.unknown:
|
|
wid = short_id(wid_raw)
|
|
if batch.has_node("Work", wid): # only link works we already loaded
|
|
batch.edge("Work", wid, "FUNDED_BY", "Funder", fid)
|
|
return response.funder_count
|
|
|
|
|
|
async def collect_news(batch: GraphBatch, aid: str, max_news: int) -> int:
|
|
page = await get_news_by_author(aid, page=1, page_size=max_news)
|
|
for article in page.results:
|
|
batch.node("NewsArticle", article.id, title=article.maintitle, date=article.date, url=article.url)
|
|
batch.edge("Author", aid, "MENTIONED_IN", "NewsArticle", article.id, matching="display_name")
|
|
for topic in article.topics or []:
|
|
tid = short_id(topic.id)
|
|
if tid:
|
|
batch.node("Topic", tid, name=topic.display_name, subfield=topic.subfield_name, field=topic.field_name, domain=topic.domain_name)
|
|
batch.edge("NewsArticle", article.id, "HAS_TOPIC", "Topic", tid)
|
|
return page.total
|
|
|
|
|
|
async def collect_companies(batch: GraphBatch, aid: str) -> int:
|
|
response = await get_company_connections_by_author_id(aid)
|
|
for company in response.connections:
|
|
cid = company.company_number or company.native_company_number or f"name:{company.company_name}"
|
|
batch.node(
|
|
"Company", cid,
|
|
name=company.company_name, status=company.company_status,
|
|
registered_office=company.registered_office,
|
|
register=" ".join(p for p in (company.register_art, company.register_nummer) if p) or None,
|
|
)
|
|
batch.edge(
|
|
"Author", aid, "OFFICER_OF", "Company", cid,
|
|
positions=[o.position for o in company.matched_officers if o.position],
|
|
matching_method=response.matching_method,
|
|
common_name_warning=response.common_name_warning,
|
|
)
|
|
return response.company_count
|
|
|
|
|
|
# --------------------------------------------------------------------------- FalkorDB sink
|
|
def _chunks(rows: list[dict[str, Any]], size: int):
|
|
for start in range(0, len(rows), size):
|
|
yield rows[start:start + size]
|
|
|
|
|
|
def write_to_falkordb(batch: GraphBatch, args: argparse.Namespace) -> None:
|
|
from falkordb import FalkorDB
|
|
from redis.exceptions import ResponseError
|
|
|
|
db = FalkorDB(host=args.falkordb_host, port=args.falkordb_port, password=args.falkordb_password)
|
|
if args.reset and args.graph in db.list_graphs():
|
|
db.select_graph(args.graph).delete()
|
|
logger.info("Deleted existing graph %r", args.graph)
|
|
graph = db.select_graph(args.graph)
|
|
|
|
labels = sorted({label for label, _ in batch.nodes})
|
|
for label in labels:
|
|
try:
|
|
graph.create_node_range_index(label, "id")
|
|
except ResponseError as exc:
|
|
if "already indexed" not in str(exc):
|
|
raise
|
|
|
|
nodes_by_label: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
|
for (label, node_id), props in batch.nodes.items():
|
|
nodes_by_label[label].append({"id": node_id, "props": props})
|
|
for label, rows in nodes_by_label.items():
|
|
assert _IDENT.match(label), label
|
|
for chunk in _chunks(rows, args.batch_size):
|
|
graph.query(f"UNWIND $rows AS r MERGE (n:{label} {{id: r.id}}) SET n += r.props", {"rows": chunk})
|
|
|
|
edges_by_type: dict[tuple[str, str, str], list[dict[str, Any]]] = defaultdict(list)
|
|
for (src_label, src, rel, dst_label, dst), props in batch.edges.items():
|
|
edges_by_type[(src_label, rel, dst_label)].append({"src": src, "dst": dst, "props": props})
|
|
for (src_label, rel, dst_label), rows in edges_by_type.items():
|
|
assert _IDENT.match(src_label) and _IDENT.match(rel) and _IDENT.match(dst_label)
|
|
for chunk in _chunks(rows, args.batch_size):
|
|
graph.query(
|
|
f"UNWIND $rows AS r "
|
|
f"MATCH (a:{src_label} {{id: r.src}}), (b:{dst_label} {{id: r.dst}}) "
|
|
f"MERGE (a)-[e:{rel}]->(b) SET e += r.props",
|
|
{"rows": chunk},
|
|
)
|
|
|
|
if not args.no_coauthor_edges:
|
|
# Derive co-authorship inside the graph instead of in Python (this is the part the
|
|
# in-service CollaborationGraph API currently leaves to the client).
|
|
result = graph.query(
|
|
"MATCH (a:Author)-[:AUTHORED]->(w:Work)<-[:AUTHORED]-(b:Author) "
|
|
"WHERE a.id < b.id "
|
|
"WITH a, b, count(DISTINCT w) AS n, min(w.year) AS first_year, max(w.year) AS last_year "
|
|
"MERGE (a)-[c:CO_AUTHOR]->(b) "
|
|
"SET c.weight = n, c.first_year = first_year, c.last_year = last_year"
|
|
)
|
|
logger.info("CO_AUTHOR edges created: %d", int(result.relationships_created or 0))
|
|
|
|
stats = graph.ro_query(
|
|
"MATCH (n) WITH count(n) AS nodes MATCH ()-[r]->() RETURN nodes, count(r)"
|
|
).result_set
|
|
logger.info("Graph %r now holds %s nodes and %s relationships", args.graph, *stats[0])
|
|
|
|
seeds = graph.ro_query(
|
|
"MATCH (s:Author {seed: true}) "
|
|
"OPTIONAL MATCH (s)-[c:CO_AUTHOR]-(o:Author) "
|
|
"WITH s, o, c ORDER BY c.weight DESC "
|
|
"WITH s, collect(o.name + ' (' + toString(c.weight) + ')')[0..3] AS top "
|
|
"RETURN s.id, s.name, top ORDER BY s.name"
|
|
).result_set
|
|
for row in seeds:
|
|
logger.info(" %s %-32s strongest co-authors: %s", row[0], row[1], ", ".join(row[2]) or "-")
|
|
|
|
|
|
# --------------------------------------------------------------------------- main
|
|
async def run_source(name: str, coro, status: dict[str, str]) -> None:
|
|
started = time.perf_counter()
|
|
try:
|
|
count = await coro
|
|
status[name] = f"{count} ({(time.perf_counter() - started) * 1000:.0f}ms)"
|
|
except Exception as exc: # one failing source must not abort the whole load
|
|
logger.warning("source %-9s failed: %s: %s", name, type(exc).__name__, exc)
|
|
status[name] = "error"
|
|
|
|
|
|
async def main(args: argparse.Namespace) -> None:
|
|
batch = GraphBatch()
|
|
skipped = set(args.skip)
|
|
seeds: list[tuple[Author, str | None]] = []
|
|
default_orgs = load_default_organizations()
|
|
|
|
if args.author_id:
|
|
for raw in args.author_id:
|
|
author = await get_author_by_id_strict_or_raise(short_id(raw))
|
|
org = organization_of(author, default_orgs)
|
|
if org:
|
|
await ensure_organization_nodes(batch, org)
|
|
seeds.append((author, org["name"] if org else None))
|
|
else:
|
|
for org in select_organizations(default_orgs, args.organization):
|
|
await ensure_organization_nodes(batch, org)
|
|
authors = await pick_seed_authors(
|
|
org["institution_id"], args.per_org, args.min_works, args.max_works, args.require_orcid
|
|
)
|
|
logger.info("%s (%s): %s", org["name"], org["institution_id"], ", ".join(f"{a.display_name} [{short_id(a.id)}]" for a in authors) or "no authors found")
|
|
seeds.extend((author, org["name"]) for author in authors)
|
|
|
|
if not seeds:
|
|
raise SystemExit("No seed researchers selected.")
|
|
|
|
seed_ids = [collect_author_profile(batch, author, org_name) for author, org_name in seeds]
|
|
|
|
for (author, _), aid in zip(seeds, seed_ids):
|
|
logger.info("Collecting sources for %s [%s] ...", author.display_name, aid)
|
|
status: dict[str, str] = {}
|
|
if "works" not in skipped:
|
|
await run_source("works", collect_works(batch, aid, args.works, args.max_authors_per_work), status)
|
|
if "projects" not in skipped:
|
|
await run_source("projects", collect_projects(batch, aid), status)
|
|
if "patents" not in skipped:
|
|
await run_source("patents", collect_patents(batch, aid), status)
|
|
if "funders" not in skipped:
|
|
await run_source("funders", collect_funders(batch, aid), status)
|
|
if "news" not in skipped:
|
|
await run_source("news", collect_news(batch, aid, args.news), status)
|
|
if "companies" not in skipped:
|
|
await run_source("companies", collect_companies(batch, aid), status)
|
|
logger.info(" %s", " ".join(f"{k}={v}" for k, v in status.items()))
|
|
|
|
node_counts, edge_counts = batch.summary()
|
|
logger.info("Collected nodes: %s", dict(node_counts))
|
|
logger.info("Collected edges: %s", dict(edge_counts))
|
|
|
|
if args.dump:
|
|
Path(args.dump).write_text(json.dumps(batch.to_json(), ensure_ascii=False, indent=1), encoding="utf-8")
|
|
logger.info("Wrote %s", args.dump)
|
|
|
|
if args.no_write:
|
|
return
|
|
write_to_falkordb(batch, args)
|
|
|
|
|
|
def parse_args() -> argparse.Namespace:
|
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
sel = parser.add_argument_group("researcher selection")
|
|
sel.add_argument("--organization", action="append", default=[], metavar="NAME_OR_ID",
|
|
help="restrict to default organization(s) by name substring or OpenAlex institution id (repeatable)")
|
|
sel.add_argument("--per-org", type=int, default=2, help="seed researchers per organization (default 2)")
|
|
sel.add_argument("--min-works", type=int, default=20, help="minimum works_count for seed selection")
|
|
sel.add_argument("--max-works", type=int, default=300, help="maximum works_count for seed selection (skips hyper-authorship profiles)")
|
|
sel.add_argument("--require-orcid", action=argparse.BooleanOptionalAction, default=True,
|
|
help="only seed researchers with an ORCID (default on)")
|
|
sel.add_argument("--author-id", action="append", default=[], metavar="OPENALEX_ID",
|
|
help="explicit seed researcher(s), e.g. A5040796987 (repeatable; overrides organization selection)")
|
|
src = parser.add_argument_group("sources")
|
|
src.add_argument("--works", type=int, default=40, help="max works per researcher (default 40)")
|
|
src.add_argument("--max-authors-per-work", type=int, default=30, help="skip co-author edges for works with more authors")
|
|
src.add_argument("--news", type=int, default=20, help="max news articles per researcher")
|
|
src.add_argument("--skip", action="append", default=[], choices=SOURCES, help="skip a source (repeatable)")
|
|
out = parser.add_argument_group("output")
|
|
out.add_argument("--falkordb-host", default=os.environ.get("FALKORDB_HOST", "localhost"))
|
|
out.add_argument("--falkordb-port", type=int, default=int(os.environ.get("FALKORDB_PORT", "6379")))
|
|
out.add_argument("--falkordb-password", default=os.environ.get("FALKORDB_PASSWORD") or None)
|
|
out.add_argument("--graph", default=os.environ.get("FALKORDB_GRAPH", "inse"), help="graph name (default inse)")
|
|
out.add_argument("--reset", action="store_true", help="delete the graph before loading")
|
|
out.add_argument("--no-coauthor-edges", action="store_true", help="do not derive CO_AUTHOR edges")
|
|
out.add_argument("--batch-size", type=int, default=500)
|
|
out.add_argument("--dump", metavar="PATH", help="also write the collected nodes/edges as JSON")
|
|
out.add_argument("--no-write", action="store_true", help="collect only (useful with --dump), do not touch FalkorDB")
|
|
parser.add_argument("-v", "--verbose", action="store_true", help="show backend/httpx logs")
|
|
return parser.parse_args()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
cli_args = parse_args()
|
|
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
|
if not cli_args.verbose:
|
|
# Some backend modules pin their own logger level, so filter at the handler instead.
|
|
for handler in logging.getLogger().handlers:
|
|
handler.addFilter(lambda record: record.levelno >= logging.WARNING or record.name.startswith("falkordb"))
|
|
asyncio.run(main(cli_args))
|