invenio-pidbox 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ """InvenioRDM PIDBox integration for people and organizations profile templates."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ __all__ = ("__version__", "InvenioPidbox")
6
+
7
+
8
+ def __getattr__(name):
9
+ """Lazily import heavy extension dependencies on demand."""
10
+ if name == "InvenioPidbox":
11
+ from .ext import InvenioPidbox
12
+
13
+ return InvenioPidbox
14
+ raise AttributeError(name)
@@ -0,0 +1,16 @@
1
+ """Default configuration for the profile templates package."""
2
+
3
+ CROSSREF_USERNAME = None
4
+ """Crossref account username (with role) used for the cited-by service."""
5
+
6
+ CROSSREF_PASSWORD = None
7
+ """Crossref account password used for the cited-by service."""
8
+
9
+ CROSSREF_PREFIX = None
10
+ """DOI prefix whose forward links are fetched from Crossref cited-by."""
11
+
12
+ CROSSREF_ADDITIONAL_PREFIXES = []
13
+ """List of additional DOI prefixes whose forward links are fetched from Crossref cited-by."""
14
+
15
+ CROSSREF_START_DATE = "2000-01-01"
16
+ """Earliest date for Crossref cited-by forward-link queries (ISO 8601)."""
invenio_pidbox/ext.py ADDED
@@ -0,0 +1,143 @@
1
+ """Flask extension for invenio-pidbox."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from urllib.parse import quote
6
+
7
+ from babel import Locale
8
+ from babel.core import UnknownLocaleError
9
+ from flask import Blueprint, current_app, redirect, render_template, request
10
+ from flask_babel import get_locale
11
+ from typing import Any
12
+
13
+ from .profile import ProfileDataProvider
14
+
15
+
16
+ def _country_name(code: str | None) -> str:
17
+ """Return the localized display name for an ISO country code."""
18
+ if not code:
19
+ return ""
20
+ try:
21
+ locale = Locale.parse(str(get_locale() or "en"))
22
+ return locale.territories.get(str(code).upper()) or str(code)
23
+ except UnknownLocaleError, ValueError:
24
+ return str(code)
25
+
26
+
27
+ def _build_search_config(app, query: str, filters: list[list[str]]) -> dict[str, Any]:
28
+ """Build a search configuration for the profile page search widget."""
29
+ fallback = {
30
+ "appId": "InvenioAppRdm.Search",
31
+ "apiConfig": {
32
+ "url": "/api/records",
33
+ "headers": {"Accept": "application/vnd.inveniordm.v1+json"},
34
+ },
35
+ "initialQueryState": {
36
+ "hiddenParams": [["q", query]],
37
+ "filters": filters,
38
+ "sortBy": "newest",
39
+ },
40
+ }
41
+
42
+ try:
43
+ from invenio_search_ui.searchconfig import search_app_config
44
+ except ImportError:
45
+ return fallback
46
+
47
+ try:
48
+ search_config = search_app_config(
49
+ "RDM_SEARCH",
50
+ app.config.get("RDM_FACETS", []),
51
+ app.config.get("RDM_SORT_OPTIONS", {}),
52
+ "/api/records",
53
+ {"Accept": "application/vnd.inveniordm.v1+json"},
54
+ pagination_options=(10, 20),
55
+ hidden_params=[["q", query]],
56
+ app_id="InvenioAppRdm.Search",
57
+ )
58
+ except KeyError:
59
+ return fallback
60
+
61
+ search_config.setdefault("initialQueryState", {})["sortBy"] = "newest"
62
+ search_config["initialQueryState"]["filters"] = filters
63
+ return search_config
64
+
65
+
66
+ def _profile_context(app, profile_type: str, profile_id: str) -> dict[str, Any]:
67
+ """Build the template context for a person or organization profile."""
68
+ provider = ProfileDataProvider(app.config["PIDBOX_SQLITE_PATH"])
69
+ context = provider.get_profile_context(profile_type, profile_id)
70
+ if profile_type == "person":
71
+ context["search_config"] = _build_search_config(
72
+ app,
73
+ f"orcid:{profile_id}",
74
+ [["author_identifiers", "orcid"]],
75
+ )
76
+ else:
77
+ context["search_config"] = _build_search_config(
78
+ app,
79
+ f"ror:{profile_id}",
80
+ [["affiliations", profile_id]],
81
+ )
82
+ return context
83
+
84
+
85
+ def create_blueprint() -> Blueprint:
86
+ """Create profile routes for people and organizations."""
87
+ blueprint = Blueprint("invenio_pidbox", __name__)
88
+
89
+ @blueprint.route("/people/<path:orcid>")
90
+ def person_profile(orcid: str):
91
+ context = _profile_context(current_app, "person", orcid)
92
+ if not context.get("person"):
93
+ return redirect(f"/search?q={quote(f'orcid:{orcid}')}&l=list&sort=newest")
94
+ return render_template("invenio_app_rdm/people/profile.html", **context)
95
+
96
+ @blueprint.route("/organizations/<path:ror>")
97
+ def organization_profile(ror: str):
98
+ context = _profile_context(current_app, "organization", ror)
99
+ if not context.get("organization"):
100
+ return redirect(f"/search?q={quote(f'ror:{ror}')}&l=list&sort=newest")
101
+ return render_template("invenio_app_rdm/organizations/profile.html", **context)
102
+
103
+ return blueprint
104
+
105
+
106
+ class InvenioPidbox:
107
+ """Load profile templates and expose SQLite-backed profile context."""
108
+
109
+ def __init__(self, app=None) -> None:
110
+ """Initialize the extension."""
111
+ self.app = None
112
+ if app is not None:
113
+ self.init_app(app)
114
+
115
+ def init_app(self, app) -> None:
116
+ """Initialize the application."""
117
+ self.app = app
118
+ app.extensions["invenio-pidbox"] = self
119
+
120
+ app.config.setdefault("PIDBOX_SQLITE_PATH", "profiles.sqlite3")
121
+ app.add_template_filter(_country_name, "country_name")
122
+ app.register_blueprint(create_blueprint())
123
+
124
+ @app.context_processor
125
+ def inject_profile_context() -> dict[str, Any]:
126
+ """Expose profile data from SQLite to templates when a profile route is active."""
127
+ path = app.config.get("PIDBOX_SQLITE_PATH")
128
+ if not path or not request.path:
129
+ return {}
130
+
131
+ provider = ProfileDataProvider(path)
132
+ parts = [part for part in request.path.split("/") if part]
133
+ if len(parts) < 2:
134
+ return {}
135
+
136
+ profile_type = parts[0]
137
+ if profile_type not in {"people", "organizations"}:
138
+ return {}
139
+
140
+ profile_id = parts[1]
141
+ if profile_type == "people":
142
+ return _profile_context(app, "person", profile_id)
143
+ return _profile_context(app, "organization", profile_id)
@@ -0,0 +1,5 @@
1
+ """Models for the profile templates package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __all__ = []
@@ -0,0 +1,213 @@
1
+ """Helpers for loading profile data from SQLite."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ _ROR_PREFIX = "https://ror.org/"
12
+ _ORG_IDENTIFIER_LINKS = {
13
+ "ISNI": (
14
+ "ISNI",
15
+ lambda value: (
16
+ f"https://isni.org/isni/{value.replace(' ', '').replace('-', '')}"
17
+ ),
18
+ ),
19
+ "Wikidata": (
20
+ "Wikidata",
21
+ lambda value: f"https://www.wikidata.org/wiki/{value}",
22
+ ),
23
+ "FundRef": (
24
+ "Crossref Funder ID",
25
+ lambda value: f"https://api.crossref.org/funders/{value}",
26
+ ),
27
+ }
28
+ _ORG_RELATION_LABELS = {
29
+ "IsPartOf": "Parent",
30
+ "HasPart": "Children",
31
+ "IsRelatedTo": "Related",
32
+ }
33
+
34
+
35
+ @dataclass(slots=True)
36
+ class ProfileDataProvider:
37
+ """Load profile rows from the commonmeta SQLite store."""
38
+
39
+ sqlite_path: str | Path
40
+
41
+ def __post_init__(self) -> None:
42
+ self.sqlite_path = str(self.sqlite_path)
43
+
44
+ def _format_partial_date(self, value: str | None) -> str:
45
+ """Preserve partial ORCID affiliation dates for template display."""
46
+ parts = (value or "").split("-")
47
+ if not parts or not parts[0]:
48
+ return ""
49
+ if len(parts) == 1:
50
+ return parts[0]
51
+ if len(parts) == 2:
52
+ return f"{parts[0]}-{parts[1]}"
53
+ return f"{parts[0]}-{parts[1]}-{parts[2]}"
54
+
55
+ def _employment_entries(
56
+ self, affiliations: list[dict[str, Any]] | None
57
+ ) -> list[dict[str, Any]]:
58
+ """Shape commonmeta affiliations into what the profile template expects."""
59
+ entries = []
60
+ for affiliation in affiliations or []:
61
+ identifier = affiliation.get("identifier") or ""
62
+ is_ror = affiliation.get("identifier_type") == "ROR" and identifier
63
+ start_date = affiliation.get("start_date") or ""
64
+ end_date = affiliation.get("end_date") or ""
65
+ entries.append(
66
+ {
67
+ "id": identifier.removeprefix(_ROR_PREFIX) if is_ror else None,
68
+ "name": affiliation.get("name"),
69
+ "role": affiliation.get("role"),
70
+ "start_date": start_date,
71
+ "start_date_display": self._format_partial_date(start_date),
72
+ "end_date": end_date,
73
+ "end_date_display": self._format_partial_date(end_date),
74
+ }
75
+ )
76
+ entries.sort(key=lambda entry: entry["start_date"], reverse=True)
77
+ return entries
78
+
79
+ def _organization_identifiers(
80
+ self, identifiers: list[dict[str, Any]] | None
81
+ ) -> list[dict[str, str | None]]:
82
+ """Shape commonmeta identifiers into display rows."""
83
+ by_type = {
84
+ identifier.get("identifier_type"): identifier.get("identifier")
85
+ for identifier in identifiers or []
86
+ if identifier.get("identifier")
87
+ }
88
+ rows = []
89
+ for scheme, (label, url_for) in _ORG_IDENTIFIER_LINKS.items():
90
+ value = by_type.get(scheme)
91
+ if value:
92
+ rows.append(
93
+ {
94
+ "label": label,
95
+ "value": value,
96
+ "url": url_for(value) if url_for else None,
97
+ }
98
+ )
99
+ return rows
100
+
101
+ def _organization_relations(
102
+ self, relations: list[dict[str, Any]] | None
103
+ ) -> list[dict[str, Any]]:
104
+ """Group related organizations by relationship type."""
105
+ grouped: dict[str | None, list[dict[str, str]]] = {}
106
+ for relation in relations or []:
107
+ identifier = relation.get("id") or ""
108
+ if not identifier:
109
+ continue
110
+ grouped.setdefault(relation.get("type"), []).append(
111
+ {
112
+ "id": identifier.removeprefix(_ROR_PREFIX),
113
+ "name": relation.get("name") or identifier,
114
+ }
115
+ )
116
+ return [
117
+ {"label": label, "members": grouped[type_]}
118
+ for type_, label in _ORG_RELATION_LABELS.items()
119
+ if grouped.get(type_)
120
+ ]
121
+
122
+ def _read_commonmeta_record(
123
+ self, profile_type: str, profile_id: str
124
+ ) -> dict[str, Any] | None:
125
+ """Read a person or organization from pid_annotations via commonmeta-rs."""
126
+ from commonmeta.backend import require_backend, resolve_db_path
127
+
128
+ backend = require_backend()
129
+ db_path = resolve_db_path(self.sqlite_path)
130
+ if profile_type == "person":
131
+ raw = backend.read_person_commonmeta_sqlite(profile_id, db_path)
132
+ elif profile_type == "organization":
133
+ raw = backend.read_org_commonmeta_sqlite(profile_id, db_path)
134
+ else:
135
+ raise ValueError(f"Unsupported profile type: {profile_type}")
136
+
137
+ if raw is None:
138
+ return None
139
+
140
+ records = json.loads(raw)
141
+ if not isinstance(records, list) or not records:
142
+ return None
143
+ record = records[0]
144
+ return record if isinstance(record, dict) else None
145
+
146
+ def _empty_context(self, profile_type: str, profile_id: str) -> dict[str, Any]:
147
+ """Return an empty template context for a missing profile."""
148
+ if profile_type == "person":
149
+ return {
150
+ "person": {},
151
+ "employment": [],
152
+ "orcid": None,
153
+ "search_config": {"filters": [f"person_id:{profile_id}"]},
154
+ }
155
+ if profile_type == "organization":
156
+ return {
157
+ "organization": {},
158
+ "urls": [],
159
+ "identifiers": [],
160
+ "relations": [],
161
+ "location": None,
162
+ "ror": None,
163
+ "search_config": {"filters": [f"organization_id:{profile_id}"]},
164
+ }
165
+ raise ValueError(f"Unsupported profile type: {profile_type}")
166
+
167
+ def get_profile_context(self, profile_type: str, profile_id: str) -> dict[str, Any]:
168
+ """Return a context dictionary for the named profile type and identifier."""
169
+ record = self._read_commonmeta_record(profile_type, profile_id)
170
+ if record is None:
171
+ return self._empty_context(profile_type, profile_id)
172
+
173
+ if profile_type == "person":
174
+ return {
175
+ "person": {
176
+ "id": profile_id,
177
+ "name": record.get("name"),
178
+ "given_name": record.get("given_name"),
179
+ "family_name": record.get("family_name"),
180
+ "description": record.get("description"),
181
+ "country": record.get("country"),
182
+ "additional_names": record.get("additional_names") or [],
183
+ },
184
+ "employment": self._employment_entries(record.get("affiliations")),
185
+ "orcid": profile_id,
186
+ "search_config": {"filters": [f"person_id:{profile_id}"]},
187
+ }
188
+
189
+ if profile_type == "organization":
190
+ locations = record.get("geo_locations") or []
191
+ return {
192
+ "organization": {
193
+ "id": profile_id,
194
+ "name": record.get("name"),
195
+ "acronym": record.get("acronym"),
196
+ "types": record.get("types") or [],
197
+ "additional_names": record.get("additional_names") or [],
198
+ },
199
+ "urls": [
200
+ url
201
+ for url in record.get("urls") or []
202
+ if url.get("url") and url.get("name") != "wikipedia"
203
+ ],
204
+ "identifiers": self._organization_identifiers(
205
+ record.get("identifiers")
206
+ ),
207
+ "relations": self._organization_relations(record.get("relations")),
208
+ "location": locations[0] if locations else None,
209
+ "ror": profile_id,
210
+ "search_config": {"filters": [f"organization_id:{profile_id}"]},
211
+ }
212
+
213
+ raise ValueError(f"Unsupported profile type: {profile_type}")
@@ -0,0 +1 @@
1
+ """invenio_pidbox.resources package."""
@@ -0,0 +1 @@
1
+ """Resource configuration module for invenio-pidbox."""
@@ -0,0 +1 @@
1
+ """Resource module for invenio-pidbox."""
@@ -0,0 +1 @@
1
+ """Services package for invenio-pidbox."""
@@ -0,0 +1 @@
1
+ """Service configuration module for invenio-pidbox."""
@@ -0,0 +1 @@
1
+ """Service module for invenio-pidbox."""
@@ -0,0 +1,125 @@
1
+ {#
2
+ Copyright (C) 2026 Front Matter.
3
+
4
+ Invenio App RDM is free software; you can redistribute it and/or modify it
5
+ under the terms of the MIT License; see LICENSE file for more details.
6
+ #}
7
+ {%- set title = organization.name %}
8
+ {%- extends config.BASE_TEMPLATE %}
9
+
10
+ {%- block javascript %}
11
+ {{ super() }}
12
+ {{ webpack['invenio-app-rdm-search.js'] }}
13
+ {%- endblock %}
14
+
15
+ {%- block page_body %}
16
+ <div class="ui stackable grid container rel-mt-2">
17
+
18
+ {# Profile header — full row #}
19
+ <div class="sixteen wide column row">
20
+ <div class="sixteen wide column">
21
+ <h2 class="ui header">
22
+ {{ organization.name }}
23
+ {%- if organization.acronym %} <span class="text-muted">({{ organization.acronym }})</span>{% endif %}
24
+ <a href="https://ror.org/{{ ror }}" target="_blank" rel="noopener noreferrer" style="margin-left: 0.1em;">
25
+ <img src="/static/images/ror.svg" alt="ROR" style="height: 0.8em; vertical-align: middle;">
26
+ </a>
27
+ </h2>
28
+ </div>
29
+ </div>
30
+
31
+ {# Alternate names — full width, above the two columns #}
32
+ {% if organization.additional_names %}
33
+ <div class="sixteen wide column row">
34
+ <div class="sixteen wide column">
35
+ <div><strong>{{ _("Also known as") }}</strong></div>
36
+ <div>{{ organization.additional_names | join(", ") }}</div>
37
+ </div>
38
+ </div>
39
+ {% endif %}
40
+
41
+ {# Type, location, website and identifiers (left) + relations (right) #}
42
+ <div class="row">
43
+
44
+ {# Left column: type, location, website, ISNI/Wikidata/Funder ID #}
45
+ <div class="eight wide computer sixteen wide tablet column">
46
+ {% if organization.types %}
47
+ <div class="rel-mt-0"><strong>{{ _("Type") }}</strong></div>
48
+ <div>{{ organization.types | map("capitalize") | join(", ") }}</div>
49
+ {% endif %}
50
+
51
+ {% if location %}
52
+ <div class="rel-mt-1"><strong>{{ _("Location") }}</strong></div>
53
+ <div>
54
+ {%- if location.id -%}
55
+ <a href="{{ location.id }}" target="_blank" rel="noopener noreferrer">{{ location.place }}</a>
56
+ {%- else -%}
57
+ {{ location.place }}
58
+ {%- endif -%}
59
+ </div>
60
+ {% endif %}
61
+
62
+ {% if urls %}
63
+ <div class="rel-mt-1"><strong>{{ _("Website") }}</strong></div>
64
+ {% for url in urls %}
65
+ {# Long URLs would otherwise overflow the narrow column. #}
66
+ <div><a href="{{ url.url }}" target="_blank" rel="noopener noreferrer" style="overflow-wrap: anywhere;">{{ url.url }}</a></div>
67
+ {% endfor %}
68
+ {% endif %}
69
+
70
+ {% for identifier in identifiers %}
71
+ <div class="rel-mt-1"><strong>{{ identifier.label }}</strong></div>
72
+ <div style="overflow-wrap: anywhere;">
73
+ {%- if identifier.url -%}
74
+ <a href="{{ identifier.url }}" target="_blank" rel="noopener noreferrer">{{ identifier.value }}</a>
75
+ {%- else -%}
76
+ {{ identifier.value }}
77
+ {%- endif -%}
78
+ </div>
79
+ {% endfor %}
80
+ </div>
81
+
82
+ {# Right column: related organizations #}
83
+ <div class="eight wide computer sixteen wide tablet column">
84
+ {% if relations %}
85
+ {# First in the column on desktop; on tablet/mobile the columns stack
86
+ below the identity block, so it keeps its top margin there. #}
87
+ <h3 class="ui header rel-mt-0 computer only">{{ _("Related organizations") }}</h3>
88
+ <h3 class="ui header rel-mt-2 tablet mobile only">{{ _("Related organizations") }}</h3>
89
+ {% for group in relations %}
90
+ <div class="rel-mt-1"><strong>{{ group.label }}</strong></div>
91
+ <div class="ui list organization-relations">
92
+ {%- if not group.members %}
93
+ <div class="item">{{ _("None") }}</div>
94
+ {% endif %}
95
+ {%- for member in group.members %}
96
+ <div class="item">
97
+ <div class="content">
98
+ <a href="/organizations/{{ member.id }}">{{ member.name }}</a>
99
+ <a href="https://ror.org/{{ member.id }}" target="_blank" rel="noopener noreferrer" style="margin-left: 0.3em;">
100
+ <img src="/static/images/ror.svg" alt="ROR" style="height: 0.8em; vertical-align: middle;">
101
+ </a>
102
+ </div>
103
+ </div>
104
+ {% endfor %}
105
+ </div>
106
+ {% endfor %}
107
+ {% endif %}
108
+ </div>
109
+
110
+ </div>
111
+
112
+ {# Metrics — full width below the profile #}
113
+ <div class="sixteen wide column row">
114
+ <div class="sixteen wide column">
115
+ {%- include "invenio_app_rdm/organizations/profile_metrics.html" %}
116
+ </div>
117
+ </div>
118
+
119
+ </div>
120
+
121
+ {# Search results — full search app pre-filtered to this organization's ROR #}
122
+ <div class="ui container rel-mt-2">
123
+ <div data-invenio-search-config='{{ search_config | tojson }}'></div>
124
+ </div>
125
+ {%- endblock page_body %}