ab-plugin-clic 0.1.0a1__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.
ab_clic/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """Metadata read by Activity Browser before activation."""
2
+
3
+ PLUGINS_API_VERSION = "1"
4
+ PLUGIN_DISPLAY_NAME = "CLIC"
ab_clic/activate.py ADDED
@@ -0,0 +1,39 @@
1
+ """Register the CLIC page and menu action with the AB3 host."""
2
+
3
+ from importlib.resources import files
4
+
5
+ from activity_browser.plugins import ABAction, PluginContext, reveal_page
6
+ from qtpy import QtGui
7
+
8
+ from .page import ClicPage
9
+
10
+ PAGE_ID = "ab_clic.catalog"
11
+ OPEN_ACTION_ID = "ab_clic.open"
12
+
13
+
14
+ class OpenClicPage(ABAction):
15
+ text = "Browse and import"
16
+
17
+ @classmethod
18
+ def get_QAction(cls, *args, **kwargs):
19
+ action = super().get_QAction(*args, **kwargs)
20
+ action.setIconVisibleInMenu(True)
21
+ return action
22
+
23
+ @staticmethod
24
+ def run():
25
+ reveal_page(PAGE_ID)
26
+
27
+
28
+ def activate(ctx: PluginContext) -> None:
29
+ class CatalogPage(ClicPage):
30
+ def __init__(self, *args, **kwargs):
31
+ super().__init__(*args, host=ctx, **kwargs)
32
+
33
+ mark = files("ab_clic").joinpath("assets", "clic-mark.svg")
34
+ pixmap = QtGui.QPixmap()
35
+ pixmap.loadFromData(mark.read_bytes(), "SVG")
36
+ OpenClicPage.icon = QtGui.QIcon(pixmap)
37
+ ctx.register_page(PAGE_ID, CatalogPage, title="CLIC", show_by_default=False)
38
+ ctx.register_action(OPEN_ACTION_ID, OpenClicPage)
39
+ ctx.register_menu_item("Browse and import", OPEN_ACTION_ID)
@@ -0,0 +1,7 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48">
2
+ <path d="M13 14h22M13 34h22M14 13v22M34 13v22" fill="none" stroke="#00649f" stroke-width="2"/>
3
+ <rect x="5" y="5" width="16" height="16" fill="#082f3d" stroke="#ffffff" stroke-width="2"/>
4
+ <rect x="27" y="5" width="16" height="16" fill="#d7e100" stroke="#ffffff" stroke-width="2"/>
5
+ <rect x="5" y="27" width="16" height="16" fill="#082f3d" stroke="#ffffff" stroke-width="2"/>
6
+ <rect x="27" y="27" width="16" height="16" fill="#082f3d" stroke="#ffffff" stroke-width="2"/>
7
+ </svg>
ab_clic/background.py ADDED
@@ -0,0 +1,120 @@
1
+ """Find ecoinvent export targets supported by the active Brightway databases."""
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+
6
+ import bw2data as bd
7
+ from bw2data.backends import ActivityDataset
8
+ from bw2data.configuration import labels, typo_settings
9
+
10
+ ECOINVENT_NAME = re.compile(
11
+ r"ecoinvent[- ](?P<version>3\.\d+(?:\.\d+)?)[- ](?P<model>cut-?off|consequential|apos)",
12
+ re.IGNORECASE,
13
+ )
14
+ VERSION = re.compile(r"3\.\d+(?:\.\d+)?")
15
+ MODELS = {"cutoff", "consequential"}
16
+ CUTOFF_ALIASES = {"3.9": "3.9.1", "3.10": "3.10.1"}
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class EcoinventProfile:
21
+ version: str
22
+ model: str
23
+
24
+ @property
25
+ def label(self) -> str:
26
+ return f"ecoinvent {self.version} {self.model}"
27
+
28
+ @property
29
+ def target(self) -> dict[str, str]:
30
+ return {
31
+ "family": "ecoinvent",
32
+ "version": self.version,
33
+ "system_model": self.model,
34
+ }
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class BackgroundSuggestion:
39
+ technosphere: str
40
+ biosphere: str
41
+ profile: EcoinventProfile
42
+
43
+
44
+ def ecoinvent_profile(database: str) -> EcoinventProfile | None:
45
+ metadata = bd.databases.get(database, {})
46
+ version = str(metadata.get("ecoinvent_version") or "")
47
+ model = str(
48
+ metadata.get("ecoinvent_system_model") or metadata.get("system_model") or ""
49
+ )
50
+ if version and model and VERSION.fullmatch(version):
51
+ return EcoinventProfile(version, model.casefold().replace("-", ""))
52
+ match = ECOINVENT_NAME.fullmatch(database)
53
+ if match:
54
+ return EcoinventProfile(
55
+ version or match["version"],
56
+ (model or match["model"]).casefold().replace("-", ""),
57
+ )
58
+ return None
59
+
60
+
61
+ def linked_biospheres(technosphere: str) -> list[str]:
62
+ dependencies = bd.databases.get(technosphere, {}).get("depends", []) or []
63
+ flow_types = set(typo_settings.node_types) - set(labels.lci_node_types)
64
+ biospheres = []
65
+ for name in dependencies:
66
+ if name == technosphere or name not in bd.databases:
67
+ continue
68
+ types = {
69
+ row[0]
70
+ for row in ActivityDataset.select(ActivityDataset.type)
71
+ .where(ActivityDataset.database == name)
72
+ .distinct()
73
+ .tuples()
74
+ }
75
+ if types and types <= flow_types:
76
+ biospheres.append(name)
77
+ return sorted(set(biospheres))
78
+
79
+
80
+ def _export_profile_error(profile: EcoinventProfile) -> str:
81
+ if profile.model not in MODELS:
82
+ return f"CLIC does not offer {profile.model} as an ecoinvent export target."
83
+ if profile.model == "cutoff" and profile.version in CUTOFF_ALIASES:
84
+ resolved = CUTOFF_ALIASES[profile.version]
85
+ return f"CLIC exports ecoinvent {resolved} for {profile.version} cutoff. Use a matching local release."
86
+ return ""
87
+
88
+
89
+ def suggest_backgrounds() -> dict[str, BackgroundSuggestion]:
90
+ suggestions = {}
91
+ for name in bd.databases:
92
+ profile = ecoinvent_profile(name)
93
+ if profile is None or _export_profile_error(profile):
94
+ continue
95
+ biospheres = linked_biospheres(name)
96
+ if len(biospheres) == 1:
97
+ suggestions[name] = BackgroundSuggestion(name, biospheres[0], profile)
98
+ return suggestions
99
+
100
+
101
+ def choose_target(
102
+ technosphere: str, biosphere: str, version: str, model: str
103
+ ) -> dict[str, str]:
104
+ if not VERSION.fullmatch(version) or model not in MODELS:
105
+ raise ValueError("Enter the ecoinvent release and select its system model.")
106
+ requested = EcoinventProfile(version, model)
107
+ if error := _export_profile_error(requested):
108
+ raise ValueError(error)
109
+ local = ecoinvent_profile(technosphere)
110
+ if local is not None and local != requested:
111
+ raise ValueError(
112
+ f"The selected database identifies itself as {local.label}. Match the CLIC target or choose a different database."
113
+ )
114
+ if local is not None:
115
+ linked = linked_biospheres(technosphere)
116
+ if linked and biosphere not in linked:
117
+ raise ValueError(
118
+ f"Choose a biosphere database linked by {technosphere} ({', '.join(linked)})."
119
+ )
120
+ return requested.target
@@ -0,0 +1,33 @@
1
+ """Keep recently read public metadata available across catalog and import views."""
2
+
3
+ from collections import OrderedDict
4
+ from time import monotonic
5
+
6
+ MAX_RECORDS = 2048
7
+ MAX_AGE_SECONDS = 300
8
+
9
+
10
+ class CatalogCache:
11
+ def __init__(self):
12
+ self._records: OrderedDict[tuple[str, str], tuple[float, dict]] = OrderedDict()
13
+
14
+ def remember(self, record: dict, slug: str | None = None) -> None:
15
+ slug = slug or record.get("dataset_slug")
16
+ version = record.get("semantic_version")
17
+ if not slug or not version:
18
+ return
19
+ key = (slug, version)
20
+ self._records[key] = (monotonic(), record)
21
+ self._records.move_to_end(key)
22
+ if len(self._records) > MAX_RECORDS:
23
+ self._records.popitem(last=False)
24
+
25
+ def get(self, key: tuple[str, str]) -> dict | None:
26
+ if key not in self._records:
27
+ return None
28
+ saved_at, record = self._records[key]
29
+ if monotonic() - saved_at >= MAX_AGE_SECONDS:
30
+ del self._records[key]
31
+ return None
32
+ self._records.move_to_end(key)
33
+ return record
@@ -0,0 +1,131 @@
1
+ """Sortable and filterable columns for the CLIC catalog results."""
2
+
3
+ from qtpy import QtCore, QtWidgets
4
+
5
+ COLUMNS = (
6
+ ("", "Select", 65),
7
+ ("name", "Inventory", 320),
8
+ ("location", "Location", 100),
9
+ ("semantic_version", "Version", 85),
10
+ ("id", "CLIC ID", 85),
11
+ )
12
+
13
+
14
+ class CatalogCell(QtWidgets.QTableWidgetItem):
15
+ def __init__(self, field, value):
16
+ text = str(value)
17
+ super().__init__(text)
18
+ if field == "id":
19
+ self.sort_key = int(value)
20
+ elif field == "semantic_version":
21
+ parts = text.split(".")
22
+ self.sort_key = (
23
+ (0, tuple(map(int, parts)))
24
+ if all(part.isdecimal() for part in parts)
25
+ else (1, text.casefold())
26
+ )
27
+ else:
28
+ self.sort_key = text.casefold()
29
+
30
+ def __lt__(self, other):
31
+ return self.sort_key < other.sort_key
32
+
33
+
34
+ class CatalogTable(QtWidgets.QTableWidget):
35
+ column_filters_requested = QtCore.Signal(object)
36
+
37
+ def __init__(self, parent=None):
38
+ super().__init__(0, len(COLUMNS), parent)
39
+ self.column_filters = {}
40
+ self.sort_column = None
41
+ self.sort_order = QtCore.Qt.AscendingOrder
42
+ self.setHorizontalHeaderLabels([title for _, title, _ in COLUMNS])
43
+ header = self.horizontalHeader()
44
+ header.setSectionResizeMode(QtWidgets.QHeaderView.Interactive)
45
+ header.setSectionsClickable(True)
46
+ header.setSortIndicatorShown(False)
47
+ header.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
48
+ header.sectionClicked.connect(self._on_header_click)
49
+ header.customContextMenuRequested.connect(self._show_filter_menu)
50
+ for index, (_, _, width) in enumerate(COLUMNS):
51
+ self.setColumnWidth(index, width)
52
+ self.set_column_filters({})
53
+
54
+ def _on_header_click(self, column):
55
+ if column == 0:
56
+ return
57
+ descending = (
58
+ self.sort_column == column and self.sort_order == QtCore.Qt.AscendingOrder
59
+ )
60
+ self.sort_column = column
61
+ self.sort_order = (
62
+ QtCore.Qt.DescendingOrder if descending else QtCore.Qt.AscendingOrder
63
+ )
64
+ current = self.currentItem()
65
+ self.apply_sort()
66
+ if current is not None:
67
+ self.setCurrentItem(current)
68
+ self.scrollToItem(current)
69
+ header = self.horizontalHeader()
70
+ header.setSortIndicator(column, self.sort_order)
71
+ header.setSortIndicatorShown(True)
72
+
73
+ def apply_sort(self):
74
+ if self.sort_column is not None:
75
+ self.sortItems(self.sort_column, self.sort_order)
76
+
77
+ def set_column_filters(self, filters):
78
+ self.column_filters = filters
79
+ for column, (field, title, _) in enumerate(COLUMNS[1:], start=1):
80
+ item = self.horizontalHeaderItem(column)
81
+ hint = "Click to sort this page. Right-click to filter."
82
+ if field in filters:
83
+ term, exclude = filters[field]
84
+ item.setText(f"{title} •")
85
+ hint += f" Filter {'hides' if exclude else 'shows'} ‘{term}’."
86
+ else:
87
+ item.setText(title)
88
+ item.setToolTip(hint)
89
+
90
+ def _show_filter_menu(self, position):
91
+ header = self.horizontalHeader()
92
+ column = header.logicalIndexAt(position)
93
+ if column < 1:
94
+ return
95
+ field, title, _ = COLUMNS[column]
96
+ menu = QtWidgets.QMenu(header)
97
+ include = menu.addAction(
98
+ "Show names containing…" if field == "name" else "Show matching value…"
99
+ )
100
+ exclude = menu.addAction(
101
+ "Hide names containing…" if field == "name" else "Hide matching value…"
102
+ )
103
+ menu.addSeparator()
104
+ clear = menu.addAction(f"Clear {title} filter")
105
+ clear.setEnabled(field in self.column_filters)
106
+ clear_all = menu.addAction("Clear all column filters")
107
+ clear_all.setEnabled(bool(self.column_filters))
108
+ action = menu.exec(header.viewport().mapToGlobal(position))
109
+ filters = self.column_filters.copy()
110
+ if action in (include, exclude):
111
+ current, _ = filters.get(field, ("", False))
112
+ term, accepted = QtWidgets.QInputDialog.getText(
113
+ self,
114
+ f"Filter {title}",
115
+ "Text to match" if field == "name" else "Exact value",
116
+ text=current,
117
+ )
118
+ if not accepted:
119
+ return
120
+ if term := term.strip():
121
+ filters[field] = (term, action == exclude)
122
+ else:
123
+ filters.pop(field, None)
124
+ elif action == clear:
125
+ filters.pop(field)
126
+ elif action == clear_all:
127
+ filters.clear()
128
+ else:
129
+ return
130
+ if filters != self.column_filters:
131
+ self.column_filters_requested.emit(filters)
ab_clic/client.py ADDED
@@ -0,0 +1,350 @@
1
+ """Read published CLIC metadata and export selected versions together."""
2
+
3
+ import logging
4
+ import re
5
+ import time
6
+ from collections.abc import Callable, Iterable, Mapping
7
+ from concurrent.futures import ThreadPoolExecutor, as_completed
8
+ from contextlib import ExitStack, suppress
9
+ from threading import Event, Lock, local
10
+ from urllib.parse import quote, unquote, urljoin, urlsplit
11
+
12
+ import requests
13
+
14
+ from .catalog_cache import CatalogCache
15
+ from .metadata import inventory_comment
16
+ from .progress import PreparationStep, ProgressCallback, ignore_progress
17
+
18
+ CLIC_URL = "https://clic.psi.ch"
19
+ PAGE_SIZE = 25
20
+ MAX_EXPORT_VERSIONS = 100
21
+ METADATA_WORKERS = 6
22
+ YEAR_FIELDS = {"publication_year", "inventory_reference_year"}
23
+ DATASET_LINK = re.compile(
24
+ r"/(?:api/)?datasets/([a-zA-Z0-9_-]+)(?:/versions/(\d+(?:\.\d+\.\d+)?))?/?"
25
+ )
26
+ VERSION_API_LINK = re.compile(r"/api/versions/([1-9]\d*)/?")
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ class ClicError(RuntimeError):
31
+ """A CLIC operation could not be completed."""
32
+
33
+
34
+ class ExportDeferred(Exception):
35
+ """The user stopped waiting for a saved CLIC export job."""
36
+
37
+
38
+ class ExportRejected(ClicError):
39
+ """The server reported that this export job failed."""
40
+
41
+
42
+ def has_noncommercial_license(version: dict) -> bool:
43
+ return (version.get("selected_license") or "").startswith("CC-BY-NC-")
44
+
45
+
46
+ def _matches_columns(version: dict, filters: Mapping[str, tuple[str, bool]]) -> bool:
47
+ for field, (term, exclude) in filters.items():
48
+ value = str(version.get(field) or "").casefold()
49
+ matches = term in value if field == "name" else term == value
50
+ if matches == exclude:
51
+ return False
52
+ return True
53
+
54
+
55
+ class ClicClient:
56
+ def __init__(
57
+ self, session: requests.Session, catalog_cache: CatalogCache | None = None
58
+ ):
59
+ self.session = session
60
+ self.catalog_cache = (
61
+ catalog_cache if catalog_cache is not None else CatalogCache()
62
+ )
63
+
64
+ def dataset_from_link(self, link: str) -> dict:
65
+ try:
66
+ url = urlsplit(link.strip())
67
+ except ValueError:
68
+ raise ClicError("Paste a CLIC dataset or published-version link.") from None
69
+ if (url.scheme, url.netloc) != ("https", "clic.psi.ch"):
70
+ raise ClicError("Paste a link from https://clic.psi.ch.")
71
+ path = unquote(url.path)
72
+ if version_api := VERSION_API_LINK.fullmatch(path):
73
+ record = self._request("GET", f"/api/versions/{version_api[1]}/")
74
+ self.catalog_cache.remember(record)
75
+ return record
76
+ if not (dataset_link := DATASET_LINK.fullmatch(path)):
77
+ raise ClicError("Paste a CLIC dataset or published-version link.")
78
+ slug, revision = dataset_link.groups()
79
+ if revision and revision.isascii() and revision.isdecimal():
80
+ version = self._request("GET", f"/api/versions/{revision}/")
81
+ if version.get("dataset_slug") != slug:
82
+ raise ClicError("The CLIC version is not part of this dataset.")
83
+ self.catalog_cache.remember(version)
84
+ return version
85
+ dataset = self._request("GET", f"/api/datasets/{slug}/")
86
+ if not revision:
87
+ latest = dataset["latest_published_version"]
88
+ self.catalog_cache.remember(latest, slug)
89
+ return latest
90
+ for version in dataset.get("published_versions", []):
91
+ if version["semantic_version"] == revision:
92
+ self.catalog_cache.remember(version, slug)
93
+ return version
94
+ raise ClicError(f"Published version {revision} is unavailable in CLIC.")
95
+
96
+ def search_datasets(
97
+ self,
98
+ query: str,
99
+ page: int,
100
+ *,
101
+ field: str = "name",
102
+ exclude_noncommercial: bool = False,
103
+ column_filters: Mapping[str, tuple[str, bool]] | None = None,
104
+ direction: int = 1,
105
+ ) -> dict:
106
+ params = {"page_size": PAGE_SIZE}
107
+ if query and field in YEAR_FIELDS:
108
+ query = query.lstrip("0")
109
+ if len(query) > 4 or not query.isascii() or not query.isdecimal():
110
+ raise ClicError("Enter a year between 1 and 9999.")
111
+ params[f"{field}_min"] = params[f"{field}_max"] = query
112
+ elif query:
113
+ params[field] = query
114
+ filters = {
115
+ field: (term.casefold(), exclude)
116
+ for field, (term, exclude) in (column_filters or {}).items()
117
+ }
118
+
119
+ while True:
120
+ result = self._request(
121
+ "GET", "/api/datasets/", params={**params, "page": page}
122
+ )
123
+ latest_versions = [
124
+ dataset["latest_published_version"] for dataset in result["results"]
125
+ ]
126
+ for version in latest_versions:
127
+ self.catalog_cache.remember(version)
128
+ if not exclude_noncommercial and not filters:
129
+ return {**result, "results": latest_versions}
130
+ matches = [
131
+ version
132
+ for version in latest_versions
133
+ if (not exclude_noncommercial or not has_noncommercial_license(version))
134
+ and _matches_columns(version, filters)
135
+ ]
136
+ if matches or not result["next" if direction > 0 else "previous"]:
137
+ return {**result, "results": matches}
138
+ page = result["page"] + direction
139
+
140
+ def export(
141
+ self,
142
+ version_ids: Iterable[int],
143
+ target: dict,
144
+ token: str,
145
+ *,
146
+ on_progress: ProgressCallback = ignore_progress,
147
+ status_url: str = "",
148
+ on_job: Callable[[str], None] | None = None,
149
+ stop: Event | None = None,
150
+ ) -> dict:
151
+ ids = sorted(set(version_ids))
152
+ if not 1 <= len(ids) <= MAX_EXPORT_VERSIONS:
153
+ raise ClicError(
154
+ f"Select 1 to {MAX_EXPORT_VERSIONS} CLIC versions to export."
155
+ )
156
+ if status_url:
157
+ on_progress(
158
+ PreparationStep.WAIT_FOR_EXPORT, "Checking your saved CLIC export…"
159
+ )
160
+ job = self._request("GET", status_url, token=token)
161
+ else:
162
+ path = f"/api/versions/{ids[0]}/brightway-json-jobs/"
163
+ payload = {**target, "version_ids": ids[1:]} if len(ids) > 1 else target
164
+ on_progress(
165
+ PreparationStep.REQUEST_EXPORT,
166
+ "Requesting a Brightway export from CLIC…",
167
+ )
168
+ job = self._request("POST", path, token=token, json=payload)
169
+ if on_job is not None:
170
+ on_job(job["status_url"])
171
+ deadline = time.monotonic() + 180
172
+ wait_messages = {
173
+ "queued": "CLIC has queued the export. Waiting for it to start…",
174
+ "processing": "CLIC is preparing the Brightway package…",
175
+ }
176
+ previous_status = None
177
+ while job["status"] in wait_messages:
178
+ status = job["status"]
179
+ if status != previous_status:
180
+ on_progress(PreparationStep.WAIT_FOR_EXPORT, wait_messages[status])
181
+ previous_status = status
182
+ if time.monotonic() >= deadline:
183
+ raise ClicError(
184
+ "CLIC is still preparing the export. Resume it from Pending exports."
185
+ )
186
+ if stop is None:
187
+ time.sleep(2)
188
+ elif stop.wait(2):
189
+ raise ExportDeferred
190
+ status_url = job.get("status_url") or status_url
191
+ job = self._request("GET", status_url, token=token)
192
+
193
+ if stop is not None and stop.is_set():
194
+ raise ExportDeferred
195
+ if job["status"] != "succeeded":
196
+ error = job.get("error") or {}
197
+ detail = error.get("detail") or error.get("message") or job["status"]
198
+ raise ExportRejected(f"CLIC could not prepare this export. {detail}")
199
+
200
+ on_progress(
201
+ PreparationStep.DOWNLOAD_PACKAGE,
202
+ "Downloading the Brightway package from CLIC…",
203
+ )
204
+ package = self._request("GET", job["result_url"], token=token)
205
+ returned_ids = package.get("package", {}).get("root_version_ids", [])
206
+ if sorted(returned_ids) != ids:
207
+ raise ClicError(
208
+ "CLIC returned a package for a different selection of versions."
209
+ )
210
+ return package
211
+
212
+ def add_inventory_metadata(
213
+ self,
214
+ package: dict,
215
+ selected_versions: Iterable[dict],
216
+ *,
217
+ on_progress: ProgressCallback = ignore_progress,
218
+ ) -> None:
219
+ """Add exact-version descriptions and metadata to Brightway activity comments."""
220
+ on_progress(PreparationStep.READ_METADATA, "Reading published CLIC metadata…")
221
+ records = {
222
+ (version["dataset_slug"], version["semantic_version"]): version
223
+ for version in selected_versions
224
+ if "dataset_slug" in version
225
+ }
226
+ activities = []
227
+ by_slug = {}
228
+ for activity in package.get("activities", []):
229
+ provenance = activity.get("provenance") or {}
230
+ slug = provenance.get("dataset_slug")
231
+ version = provenance.get("semantic_version")
232
+ if not slug or not version:
233
+ continue
234
+ identity = (slug, version)
235
+ activities.append((identity, activity))
236
+ if identity not in records:
237
+ cached = self.catalog_cache.get(identity)
238
+ if cached is None:
239
+ by_slug.setdefault(slug, set()).add(version)
240
+ else:
241
+ records[identity] = cached
242
+
243
+ if by_slug:
244
+ on_progress(
245
+ PreparationStep.READ_METADATA,
246
+ f"Reading published CLIC metadata (0 of {len(by_slug)} datasets checked)…",
247
+ )
248
+ for checked, (slug, versions) in enumerate(
249
+ self._read_catalog_metadata(by_slug), start=1
250
+ ):
251
+ for record in versions:
252
+ self.catalog_cache.remember(record, slug)
253
+ records[slug, record["semantic_version"]] = record
254
+ on_progress(
255
+ PreparationStep.READ_METADATA,
256
+ f"Reading published CLIC metadata ({checked} of {len(by_slug)} datasets checked)…",
257
+ )
258
+
259
+ for identity, activity in activities:
260
+ if identity in records:
261
+ record = records[identity]
262
+ activity["provenance"]["clic_catalog"] = {
263
+ key: record[key]
264
+ for key in (
265
+ "id",
266
+ "public_url",
267
+ "selected_license",
268
+ "selected_license_label",
269
+ )
270
+ if record.get(key) is not None
271
+ }
272
+ comment = inventory_comment(record, activity.get("comment") or "")
273
+ if comment:
274
+ activity["comment"] = comment
275
+
276
+ def _read_catalog_metadata(self, by_slug: dict[str, set[str]]):
277
+ if len(by_slug) <= 1:
278
+ for slug, revisions in by_slug.items():
279
+ yield slug, self._read_dataset_versions(slug, revisions)
280
+ return
281
+
282
+ worker_state = local()
283
+ lock = Lock()
284
+ with ExitStack() as sessions:
285
+
286
+ def read(slug, revisions):
287
+ # Requests sessions own mutable state. Each worker reuses its own connection.
288
+ if not hasattr(worker_state, "client"):
289
+ with lock:
290
+ session = sessions.enter_context(requests.Session())
291
+ worker_state.client = ClicClient(session)
292
+ return slug, worker_state.client._read_dataset_versions(slug, revisions)
293
+
294
+ with ThreadPoolExecutor(max_workers=METADATA_WORKERS) as workers:
295
+ futures = [
296
+ workers.submit(read, slug, revisions)
297
+ for slug, revisions in by_slug.items()
298
+ ]
299
+ for future in as_completed(futures):
300
+ yield future.result()
301
+
302
+ def _read_dataset_versions(self, slug: str, revisions: set[str]) -> list[dict]:
303
+ try:
304
+ dataset = self._request("GET", f"/api/datasets/{quote(slug, safe='')}/")
305
+ except ClicError as exc:
306
+ logger.warning("Could not read CLIC metadata for %s: %s", slug, exc)
307
+ return []
308
+ return [
309
+ record
310
+ for record in dataset.get("published_versions", [])
311
+ if record.get("semantic_version") in revisions
312
+ ]
313
+
314
+ def _request(self, method: str, path: str, *, token: str = "", **kwargs) -> dict:
315
+ url = urljoin(CLIC_URL, path)
316
+ destination = urlsplit(url)
317
+ if (destination.scheme, destination.netloc) != ("https", "clic.psi.ch"):
318
+ raise ClicError("CLIC returned a URL on another origin.")
319
+
320
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
321
+ try:
322
+ response = self.session.request(
323
+ method,
324
+ url,
325
+ headers=headers,
326
+ timeout=(5, 30),
327
+ allow_redirects=False,
328
+ **kwargs,
329
+ )
330
+ except requests.RequestException:
331
+ raise ClicError(
332
+ "Could not reach CLIC. Check the connection and try again."
333
+ ) from None
334
+
335
+ if response.status_code in {401, 403}:
336
+ raise ClicError(
337
+ "Check that your CLIC token is valid and has inventory download access."
338
+ )
339
+ if not response.ok or 300 <= response.status_code < 400:
340
+ detail = ""
341
+ if response.status_code == 422:
342
+ with suppress(requests.exceptions.JSONDecodeError):
343
+ detail = response.json().get("detail", "")
344
+ raise ClicError(
345
+ f"CLIC returned HTTP {response.status_code}. {detail}".strip()
346
+ )
347
+ try:
348
+ return response.json()
349
+ except requests.exceptions.JSONDecodeError:
350
+ raise ClicError("CLIC returned an invalid JSON response.") from None