From 00ce6eb1e316f284802a992c033828a6f3ccc9fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Sp=C3=A1=C4=8Dil?= Date: Thu, 3 Dec 2026 10:13:27 +0100 Subject: [PATCH 1/2] =?UTF-8?q?=C4=8C=C3=ADst=20=C4=8D=C3=ADseln=C3=ADky?= =?UTF-8?q?=20z=20OAI=20i=20ve=20form=C3=A1tu=20oai=5Famcr=20(v2.2.1)=20(#?= =?UTF-8?q?97)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Založit OpenSpec změnu fix-oai-amcr-fallback Plánovací artefakty (proposal, design, delta spec, tasks) pro čtení číselníků z AMČR OAI v obou formátech: oai_dc jako dosud, a když server na oai_dc vrátí nativní amcr:* záznamy (oai_amcr), číst je z nich. Denní kontrola API pak takový stav hlásí jako DRIFT místo FAIL. Souvisí s #96 (a dříve #89). Implementace zatím není. Text artefaktů navržen AI. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013nPfHUicaDVqWsYEoQWhYD * Číst číselníky z OAI i ve formátu oai_amcr Server AMČR OAI na metadataPrefix=oai_dc vrací nativní záznamy amcr:amcr místo Dublin Core (#96, dříve #89), takže všech 17 OAI číselníků vycházelo prázdných. fetch_set dál žádá oai_dc, ale každý záznam čte v tom formátu, ve kterém přijde: oai_dc:dc jako dosud, jinak entitu amcr:* (heslo, ruian_kraj, ruian_okres, ruian_katastr, organizace). Výsledné kódy a názvy jsou stejné jako z DC. Smazané záznamy se přeskakují jako dřív. - tests/api_contract.py: oai_amcr na oai_dc je DRIFT, nečitelný záznam FAIL - tests/smoke_test.py: offline případy pro oba formáty - OpenSpec: úkoly odškrtnuty, v designu doplněny smazané záznamy Živě ověřeno 2026-12-02: všech 17 setů dává totéž co heslar.csv (včetně 13 091 katastrů), api_plugin_live v qgis:ltr bez FAIL/DRIFT. Kód navržen AI, ověřen automatickými kontrolami. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013nPfHUicaDVqWsYEoQWhYD * Povýšit verzi na 2.2.1 a doplnit changelog Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013nPfHUicaDVqWsYEoQWhYD * Odškrtnout ruční test v QGIS v OpenSpec úkolech Úkol 3.3 ověřen v QGIS 3.44.16 i 4.2.3 se ZIPem z PR #97. Připraveno s pomocí AI (Claude Code). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013nPfHUicaDVqWsYEoQWhYD * Archivovat OpenSpec změnu fix-oai-amcr-fallback openspec archive fix-oai-amcr-fallback --skip-specs; změna je change-tracked, trvalé specifikace se neudržují. Připraveno s pomocí AI (Claude Code). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013nPfHUicaDVqWsYEoQWhYD --------- Co-authored-by: Claude --- CITATION.cff | 4 +- amcr_viewer/amcr_codelists.py | 182 +++++++++++++----- amcr_viewer/metadata.txt | 6 +- .../.openspec.yaml | 2 + .../design.md | 96 +++++++++ .../proposal.md | 63 ++++++ .../specs/amcr-codelists/spec.md | 62 ++++++ .../2026-12-03-fix-oai-amcr-fallback/tasks.md | 50 +++++ tests/api_contract.py | 64 +++++- tests/smoke_test.py | 101 ++++++++++ 10 files changed, 567 insertions(+), 63 deletions(-) create mode 100644 openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/.openspec.yaml create mode 100644 openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/design.md create mode 100644 openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/proposal.md create mode 100644 openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/specs/amcr-codelists/spec.md create mode 100644 openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/tasks.md diff --git a/CITATION.cff b/CITATION.cff index fe98851..932b86f 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -25,5 +25,5 @@ abstract: >- the Digital archive of the Archaeological Map of the Czech Republic (https://digiarchiv.aiscr.cz/). license: GPL-3.0 -version: '2.2.0' -date-released: '2026-10-02' +version: '2.2.1' +date-released: '2026-12-02' diff --git a/amcr_viewer/amcr_codelists.py b/amcr_viewer/amcr_codelists.py index 4001e5e..315e85e 100644 --- a/amcr_viewer/amcr_codelists.py +++ b/amcr_viewer/amcr_codelists.py @@ -39,9 +39,15 @@ slovnicek = { NS = { 'oai': 'http://www.openarchives.org/OAI/2.0/', 'dc': 'http://purl.org/dc/elements/1.1/', - 'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/' + 'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/', + 'amcr': 'https://api.aiscr.cz/schema/amcr/2.2/', } +# Entities of the native oai_amcr format that hold a codelist item +_AMCR_ENTITIES = ('heslo', 'ruian_kraj', 'ruian_okres', 'ruian_katastr', + 'organizace') +_AMCR_PREFIX = '{' + NS['amcr'] + '}' + def ensure_codelists_dir(): """Creates the codelists directory if it does not exist.""" @@ -119,8 +125,106 @@ def _facet_name(item): return None +def _is_access_code(text): + """True for a one-letter access level code such as "A" or "D".""" + return bool(text) and len(text) == 1 and text.isalpha() + + +def _parse_dc(metadata): + """ + Reads one codelist item from an oai_dc:dc element. + + Returns (code, name, access_code) or None when metadata is None. + access_code is the one-letter title used by the pristupnost set. + """ + if metadata is None: + return None + identifier_el = metadata.find('dc:identifier', NS) + kod = identifier_el.text if identifier_el is not None else "" + + # Title – filter out system labels "AMČR - ..." + titles = metadata.findall('dc:title', NS) + nazev = "" + for t in titles: + if ( + t.text + and not t.text.startswith("AMČR -") + and not t.text.startswith(" AMČR -") + ): + nazev = t.text + break + # If no title passed the filter, fall back to the first available one + if not nazev and titles: + nazev = titles[0].text + + zkratka = next( + (t.text for t in titles if _is_access_code(t.text)), None) + return kod, nazev, zkratka + + +def _amcr_text(entity, tag): + """Stripped text of a direct amcr: child, or None.""" + el = entity.find('amcr:' + tag, NS) + if el is None or not el.text or not el.text.strip(): + return None + return el.text.strip() + + +def _parse_amcr(amcr_el): + """ + Reads one codelist item from an amcr:amcr element (oai_amcr format). + + The AMČR OAI server has been seen answering metadataPrefix=oai_dc with + this format (issues #89, #96). Returns (code, name, access_code) with + the same values the oai_dc format gives, or None when the entity is + unknown or lacks its code or name. + + Lookups are direct children of the entity on purpose: amcr:heslo is + both the entity and the child holding its name. + """ + if amcr_el is None: + return None + entity = next( + (child for child in amcr_el + if child.tag.startswith(_AMCR_PREFIX) + and child.tag[len(_AMCR_PREFIX):] in _AMCR_ENTITIES), + None) + if entity is None: + return None + if entity.tag == _AMCR_PREFIX + 'heslo': + kod = _amcr_text(entity, 'ident_cely') + nazev = _amcr_text(entity, 'heslo') + zkratka = _amcr_text(entity, 'zkratka') + if not _is_access_code(zkratka): + zkratka = None + else: + kod = (_amcr_text(entity, 'ident_cely') + or _amcr_text(entity, 'kod')) + nazev = _amcr_text(entity, 'nazev') + zkratka = None + if not kod or not nazev: + return None + return kod, nazev, zkratka + + +def _log_formats(api_set, amcr_count, skipped): + """Logs once per set when records did not come as oai_dc.""" + if amcr_count: + QgsMessageLog.logMessage( + f"Set {api_set}: {amcr_count} záznamů přišlo ve formátu " + "oai_amcr místo oai_dc, čtu je z něj.", + "AMČR", Qgis.MessageLevel.Info) + if skipped: + QgsMessageLog.logMessage( + f"Set {api_set}: {skipped} záznamů v neznámém formátu " + "přeskočeno.", + "AMČR", Qgis.MessageLevel.Warning) + + def fetch_set(base_url, internal_name, api_set, task=None): dataset = [] + amcr_count = 0 + skipped = 0 params_amcr = { "verb": "ListRecords", "metadataPrefix": "oai_dc", @@ -148,58 +252,35 @@ def fetch_set(base_url, internal_name, api_set, task=None): records = root.findall('.//oai:record', NS) for rec in records: - metadata = rec.find('.//oai_dc:dc', NS) - if metadata is not None: - # Code (identifier) - identifier_el = metadata.find('dc:identifier', NS) - kod = ( - identifier_el.text - if identifier_el is not None - else "" - ) + header = rec.find('oai:header', NS) + if (header is not None + and header.get('status') == 'deleted'): + continue # deleted records carry no metadata + parsed = _parse_dc(rec.find('.//oai_dc:dc', NS)) + if parsed is None: + parsed = _parse_amcr(rec.find('.//amcr:amcr', NS)) + if parsed is None: + skipped += 1 + continue + amcr_count += 1 + kod, nazev, zkratka = parsed - # Title – filter out system labels "AMČR - ..." - titles = metadata.findall('dc:title', NS) - nazev = "" - for t in titles: - if ( - t.text - and not t.text.startswith("AMČR -") - and not t.text.startswith(" AMČR -") - ): - nazev = t.text - break - # If no title passed the filter, fall back - # to the first available one - if not nazev and titles: - nazev = titles[0].text + if internal_name in ('okres', 'katastr'): + kod = nazev - specialni_pripady = ['okres', 'katastr'] + if internal_name == 'pristupnost': + # Skip records without a valid one-letter code – + # a None code would end up in the CSV and later + # in the API filter as the string "None" + kod = zkratka + if not kod: + continue - if internal_name in specialni_pripady: - kod = nazev - - if internal_name == 'pristupnost': - kod = next( - ( - t.text for t in titles - if t.text - and len(t.text) == 1 - and t.text.isalpha() - ), - None - ) - # Skip records without a valid one-letter code – - # a None code would end up in the CSV and later - # in the API filter as the string "None" - if not kod: - continue - - dataset.append({ - 'Název': nazev, - 'Kód': kod, - 'Kategorie': internal_name - }) + dataset.append({ + 'Název': nazev, + 'Kód': kod, + 'Kategorie': internal_name + }) # Pagination token = root.find('.//oai:resumptionToken', NS) @@ -210,6 +291,7 @@ def fetch_set(base_url, internal_name, api_set, task=None): } time.sleep(0.5) else: + _log_formats(api_set, amcr_count, skipped) break else: diff --git a/amcr_viewer/metadata.txt b/amcr_viewer/metadata.txt index afdb59d..6759b9e 100644 --- a/amcr_viewer/metadata.txt +++ b/amcr_viewer/metadata.txt @@ -8,7 +8,7 @@ name=AMČR Viewer qgisMinimumVersion=3.44.0 qgisMaximumVersion=4.99.0 description=Viewing and downloading the AMČR data. -version=2.2.0 +version=2.2.1 author=David Spáčil email=spacil@arub.cz @@ -23,7 +23,9 @@ repository=https://github.com/ARUP-CAS/aiscr-qgis-amcr-viewer hasProcessingProvider=no # Uncomment the following line and add your changelog: changelog= - Plný seznam změn v češtině je dostupný zde: https://github.com/ARUP-CAS/aiscr-qgis-amcr-viewer/releases/tag/v2.2.0 + Plný seznam změn v češtině je dostupný zde: https://github.com/ARUP-CAS/aiscr-qgis-amcr-viewer/releases/tag/v2.2.1 + v2.2.1 (2026-12-02) + * Codelist update works again when the AMCR OAI server answers oai_dc requests with the native oai_amcr format (issues #89, #96) v2.2.0 (2026-10-02) * Tables for Akce and Lokality contain a field with feature weight, when Komponenty rendering is enabled; the weights of one documentation unit sum to 1 also with period/area filters * The login state is verified before each download via /api/user/islogged; an expired session is renewed automatically diff --git a/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/.openspec.yaml b/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/.openspec.yaml new file mode 100644 index 0000000..eb2b21e --- /dev/null +++ b/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-12-02 diff --git a/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/design.md b/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/design.md new file mode 100644 index 0000000..db5e825 --- /dev/null +++ b/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/design.md @@ -0,0 +1,96 @@ +# Design + +## Context + +- `fetch_set` requests `ListRecords&metadataPrefix=oai_dc&set=`, + follows `resumptionToken`, and for each `oai:record` reads + `.//oai_dc:dc`. Records without it are skipped silently. +- Server behaviour, verified 2026-12-02 against the live API, digiarchiv + `v4.1.1-0-g167952b9`: + - `ListMetadataFormats` → `oai_dc`, `oai_amcr`. + - `metadataPrefix=oai_dc` and `metadataPrefix=oai_amcr` return the same + `` payload (namespace `https://api.aiscr.cz/schema/amcr/2.2/`). + Paging and record counts are unaffected, e.g. `ruian_kraj` 14, + `ruian_okres` 77, `organizace` 100 + token (201). + - `GetRecord` behaves the same way. +- `amcr:amcr` wraps exactly one entity element, whose name depends on the + set: `amcr:heslo`, `amcr:ruian_kraj`, `amcr:ruian_okres`, + `amcr:ruian_katastr`, `amcr:organizace`. +- `download_heslare` already keeps the previous rows of a set that comes + back empty and reports it in `failed`. This stays unchanged. + +## Goals / Non-Goals + +**Goals:** +- The same `Kód` / `Název` rows for every set, whichever format the server + sends. +- The contract monitor can tell "server switched format, plugin copes" + (DRIFT) apart from "plugin breaks" (FAIL). + +**Non-Goals:** +- Switching the request to `oai_amcr` (see Decisions 1). +- Reading any `amcr:*` field beyond those the CSV needs. + +## Decisions + +1. **Keep requesting `oai_dc`, parse both formats per record.** + *Alternative:* request `oai_amcr` only. Simpler parser, but + `ruian_katastr` carries GML and WKT boundaries, measured at 1.2 MB per + 100 records, about 160 MB for 13 091 records. Refreshing the codelists + would get several minutes slower for no benefit. Rejected. + *Alternative:* try `oai_dc` and repeat the whole set with `oai_amcr` when + it comes back empty. This doubles the requests during a fault and gains + nothing, because the server already sends `amcr:*` on `oai_dc`. Rejected. +2. **Mapping of the `amcr:*` entity** (`E` = the single child of + `amcr:amcr`; all lookups are direct children of `E`): + + | set / internal name | `Kód` | `Název` | + |---|---|---| + | `heslo:*` | `amcr:ident_cely` | `amcr:heslo` | + | `heslo:pristupnost` | `amcr:zkratka` (one letter, otherwise skip) | `amcr:heslo` | + | `ruian_kraj` | `amcr:kod` | `amcr:nazev` | + | `ruian_okres`, `ruian_katastr` | `amcr:nazev` (as today) | `amcr:nazev` | + | `organizace` | `amcr:ident_cely` | `amcr:nazev` | + + The `okres` / `katastr` / `pristupnost` special cases stay in one place + after the format-specific extraction, so both paths share them. + Note that `amcr:heslo` is both the entity element and its child with the + value, so the lookup must be `E.find('amcr:heslo')` on the entity, not + `.//amcr:heslo` from the record. +3. **Unknown entity or missing key fields → skip the record** and count it. + If a set yields no rows, `download_heslare` already keeps the old rows + and warns. Records whose header has `status="deleted"` carry no + metadata. They are skipped without being counted, as before. Log once per set, not per record, how many records were read + in the `amcr` format, so the fault is visible in the QGIS log. +4. **Contract test:** for each record, `oai_dc:dc` + `dc:identifier` → DC. + Otherwise an `amcr:amcr` child with the mapped key fields → AMCR. + Anything else → FAIL. Any AMCR record on an `oai_dc` request → DRIFT + with the message "server returns oai_amcr on oai_dc". +5. **Pure-Python parsing helpers** (`_parse_dc(metadata)`, + `_parse_amcr(metadata)` returning `(kod, nazev)` or `None`) so the smoke + test can feed XML snippets without the network or QGIS UI. + +## Risks / Trade-offs + +- [`oai_amcr` schema changes] → the AMCR path yields nothing. The old rows + are kept, and the monitor reports FAIL the next day. +- [Fault plus a future server fix] → both paths stay in place, no switch + back is needed. +- [The two formats disagree on a value] → we checked against the current + `heslar.csv` for heslo, kraj, okres, katastr, organizace and pristupnost. + Task 1.3 checks it again with a full refresh compared to the CSV. + +## Verification + +- Smoke test (ltr + stable) with DC and AMCR snippets for each entity type. +- `tests/api_contract.py` against the live API: DRIFT (not FAIL) while the + fault lasts. +- `tests/api_plugin_live.py`: `fetch_set` returns at least as many items + as the current CSV for every OAI set. +- A full refresh in QGIS, and a diff of the new `heslar.csv` against the + committed one. + +## Migration Plan + +Plain plugin update. No settings or data migration. Rollback is the +previous release. diff --git a/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/proposal.md b/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/proposal.md new file mode 100644 index 0000000..843f880 --- /dev/null +++ b/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/proposal.md @@ -0,0 +1,63 @@ +# Proposal + +## Why + +The AMČR OAI endpoint (`https://api.aiscr.cz/2.2/oai`) answers +`ListRecords&metadataPrefix=oai_dc` with records in the native +`oai_amcr` format (``) instead of Dublin Core (``), +although `ListMetadataFormats` still advertises `oai_dc`. The plugin only +reads `oai_dc:dc`, so every one of the 17 OAI codelists comes back empty. +`download_heslare` then keeps the previous rows from `heslar.csv` and warns, +so the plugin keeps working, but users can no longer refresh the codelists. + +The same server fault happened between 2026-10-02 and 2026-10-18 +(issue #89, fixed on the server without a plugin change) and has been back +since 2026-11-30 with digiarchiv `v4.1.1-0-g167952b9` (issue #96). Each +time the plugin depends on the server being fixed. + +## What Changes + +- `fetch_set` in `amcr_viewer/amcr_codelists.py` keeps requesting + `metadataPrefix=oai_dc` but reads each record in whichever format it + arrives in: `oai_dc:dc` as today, otherwise the `amcr:*` payload of + `oai_amcr`. Mapping of `amcr:*` elements to the `Kód` / `Název` columns + is in design.md and gives the same values as the DC path (checked against + the current `heslar.csv`). +- `tests/api_contract.py` (`check_oai_sets`) reports an `oai_dc` request + answered with `amcr:*` records as **DRIFT** (the plugin copes), not + **FAIL**. A record in neither format stays FAIL. +- `tests/smoke_test.py` gets offline cases for both formats. +- Version bump + changelog (`metadata.txt`, `CITATION.cff`). + +What the user sees: refreshing the codelists works again while the server +fault lasts, and keeps working after it is fixed. The values in the +dialog filters do not change. + +Out of scope: + +- Requesting `oai_amcr` directly. `ruian_katastr` in `oai_amcr` contains + boundary geometry (about 1.2 MB per page of 100, 131 pages, about + 160 MB in total), and the plugin needs only the name. +- Using the extra `amcr:*` data (English names, hierarchy, geometry). +- The digiarchiv sets (`vedouci`, `nalezce`), which do not use OAI. + +## Capabilities + +### New Capabilities + +- `amcr-codelists`: downloading the codelists from the AMČR OAI endpoint + and coping with both metadata formats. + +### Modified Capabilities + + + +## Impact + +- Code: `amcr_viewer/amcr_codelists.py` (`fetch_set`, `NS`); + `tests/api_contract.py` (`check_oai_sets`, `NS`); `tests/smoke_test.py`. +- API: no new requests. It still uses `ListRecords` with + `metadataPrefix=oai_dc` and `resumptionToken` paging. The change depends + on the `oai_amcr` schema `https://api.aiscr.cz/schema/amcr/2.2/`. +- Other repositories: none. +- No new dependencies. The Qt5/Qt6 rules from `AGENTS.md` apply. diff --git a/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/specs/amcr-codelists/spec.md b/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/specs/amcr-codelists/spec.md new file mode 100644 index 0000000..d7b6909 --- /dev/null +++ b/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/specs/amcr-codelists/spec.md @@ -0,0 +1,62 @@ +# Spec Delta + +## Purpose + +Keeps the codelist refresh from the AMČR OAI endpoint working whether the +server sends records as Dublin Core (`oai_dc`) or in the native AMČR format +(`oai_amcr`). + +## ADDED Requirements + +### Requirement: Codelist records are read in either metadata format +When refreshing codelists from the AMČR OAI endpoint, the plugin SHALL read +each record from its `oai_dc` payload when present, and otherwise from its +`oai_amcr` (`amcr:amcr`) payload. Both formats SHALL yield the same code and +name for the same record. + +#### Scenario: Server sends Dublin Core +- **WHEN** a codelist set is requested with `metadataPrefix=oai_dc` and the records contain `oai_dc:dc` +- **THEN** the codelist rows are the same as before this change + +#### Scenario: Server sends the AMČR format on an oai_dc request +- **WHEN** a codelist set is requested with `metadataPrefix=oai_dc` and the records contain `amcr:amcr` instead +- **THEN** the codelist rows are filled from the `amcr:*` elements and match the rows the Dublin Core format would give + +#### Scenario: Paged set in the AMČR format +- **WHEN** a set in the AMČR format spans several pages (`resumptionToken`) +- **THEN** records from all pages are read + +### Requirement: The download size of codelists does not grow +The plugin SHALL keep requesting codelists with `metadataPrefix=oai_dc` and +SHALL NOT request `oai_amcr` on its own, because the AMČR format includes +geometry the plugin does not use. + +#### Scenario: Normal refresh +- **WHEN** the user refreshes the codelists +- **THEN** every OAI request uses `metadataPrefix=oai_dc` or a `resumptionToken` + +### Requirement: Unreadable records do not empty a codelist +A record in neither format, or without the fields its codelist needs, SHALL +be skipped. If a whole set yields no rows, the plugin SHALL keep the +previous rows of that codelist and warn the user, as before this change. + +#### Scenario: Unknown payload +- **WHEN** every record of a set has a payload in an unknown format +- **THEN** the set keeps its previous rows and the user is warned that it could not be refreshed + +#### Scenario: Missing one-letter access code +- **WHEN** a `pristupnost` record in the AMČR format has no one-letter `amcr:zkratka` +- **THEN** that record is skipped and no row with an empty or "None" code is written + +### Requirement: The API monitor separates a format switch from a breakage +The daily API contract check SHALL report an `oai_dc` request answered with +readable `amcr:*` records as DRIFT, and records in neither readable format +as FAIL. + +#### Scenario: Server returns oai_amcr on oai_dc +- **WHEN** the contract check requests a set with `metadataPrefix=oai_dc` and receives `amcr:amcr` records with the fields the plugin reads +- **THEN** the check for that set is DRIFT, not FAIL + +#### Scenario: Unreadable records +- **WHEN** the records contain neither `oai_dc:dc` with `dc:identifier` nor a readable `amcr:amcr` entity +- **THEN** the check for that set is FAIL diff --git a/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/tasks.md b/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/tasks.md new file mode 100644 index 0000000..ece5122 --- /dev/null +++ b/openspec/changes/archive/2026-12-03-fix-oai-amcr-fallback/tasks.md @@ -0,0 +1,50 @@ +# Tasks + +## 1. Parsing both formats in the plugin + +- [x] 1.1 Add `amcr` to `NS` and the helpers `_parse_dc(metadata)` / + `_parse_amcr(metadata)` in `amcr_viewer/amcr_codelists.py` per design.md + (mapping table; direct-child lookups on the entity). Move the + `okres` / `katastr` / `pristupnost` special cases after the extraction so + both paths share them. Verify with `python3 tests/check_sources.py`, + `flake8 --isolated amcr_viewer/` and `ruff check .` +- [x] 1.2 Use the helpers in `fetch_set` (DC first, AMCR otherwise, skip + unreadable records) and log once per set how many records came in the + AMCR format. Verify by code review: the request parameters are unchanged + (`metadataPrefix=oai_dc`) +- [x] 1.3 Live check: run `fetch_set` for every OAI set while the server + fault lasts, and compare the rows to the committed `heslar.csv` by + category (same codes; differences only from real codelist changes). + Verify the diff summary is recorded in the PR + +## 2. Tests + +- [x] 2.1 Extend `tests/smoke_test.py` with offline XML snippets: DC + record, AMCR `heslo`, `heslo:pristupnost` (with and without a one-letter + `zkratka`), `ruian_kraj`, `ruian_okres`, `ruian_katastr`, `organizace`, + and an unknown payload. Verify the smoke test passes in `qgis/qgis:ltr` + and `qgis/qgis:stable` +- [x] 2.2 Update `check_oai_sets` in `tests/api_contract.py`: DC → OK, + readable AMCR → DRIFT ("server returns oai_amcr on oai_dc"), neither → + FAIL. Verify with + `uv run -q --no-project --with requests==2.34.2 python tests/api_contract.py` + (expect DRIFT for the oai checks while the fault lasts, and exit code per + the DRIFT rules) +- [x] 2.3 Run `tests/api_plugin_live.py` in `qgis/qgis:ltr`; verify every + `fetch_set` check is OK + +## 3. Release preparation and verification + +- [x] 3.1 Bump the version (patch) in `amcr_viewer/metadata.txt` and + `CITATION.cff`. Add a changelog entry with the date from + `python -c "import datetime; print(datetime.date.today().isoformat())"`. + Verify both files show the same version +- [x] 3.2 Run the full local check set from `AGENTS.md` (check_sources, + bandit, detect-secrets `--all-files`, flake8 `--isolated`, ruff, + pyqgis4-checker log empty, smoke test ltr + stable); verify all clean +- [x] 3.3 Manual test in QGIS: refresh the codelists; verify there is no + warning about sets that failed to download, the log reports the AMCR + format, and the filters in the dialog offer the same values as before + (done 2026-12-03 in QGIS 3.44.16 and 4.2.3 with the ZIP from PR #97: + all 17 OAI sets in AMCR format, no warning; the downloaded rows match + `heslar.csv` exactly, see 1.3) diff --git a/tests/api_contract.py b/tests/api_contract.py index ddd8867..0adfa97 100644 --- a/tests/api_contract.py +++ b/tests/api_contract.py @@ -116,6 +116,17 @@ NS = { "oai": "http://www.openarchives.org/OAI/2.0/", "dc": "http://purl.org/dc/elements/1.1/", "oai_dc": "http://www.openarchives.org/OAI/2.0/oai_dc/", + "amcr": "https://api.aiscr.cz/schema/amcr/2.2/", +} + +# oai_amcr entities the plugin can read a codelist item from, with the +# (code, name) children it uses – mirrors _parse_amcr in amcr_codelists +AMCR_ENTITIES = { + "heslo": (("ident_cely",), "heslo"), + "ruian_kraj": (("ident_cely", "kod"), "nazev"), + "ruian_okres": (("ident_cely", "kod"), "nazev"), + "ruian_katastr": (("ident_cely", "kod"), "nazev"), + "organizace": (("ident_cely", "kod"), "nazev"), } SESSION = requests.Session() @@ -461,6 +472,37 @@ def check_facet_sets(): f"mixed shapes {sorted(shapes)}", url) +def _has_text(entity, tag): + """True when a direct amcr: child has non-blank text.""" + el = entity.find(f"amcr:{tag}", NS) + return el is not None and bool((el.text or "").strip()) + + +def _amcr_readable(amcr_el): + """True when amcr:amcr holds a known entity with its code and name.""" + if amcr_el is None: + return False + for tag, (code_tags, name_tag) in AMCR_ENTITIES.items(): + entity = amcr_el.find(f"amcr:{tag}", NS) + if entity is not None: + return (any(_has_text(entity, t) for t in code_tags) + and _has_text(entity, name_tag)) + return False + + +def _record_shape(rec): + """'dc', 'amcr', 'deleted' or 'bad' for one oai:record.""" + header = rec.find("oai:header", NS) + if header is not None and header.get("status") == "deleted": + return "deleted" + if (rec.find(".//oai_dc:dc", NS) is not None + and rec.find(".//dc:identifier", NS) is not None): + return "dc" + if _amcr_readable(rec.find(".//amcr:amcr", NS)): + return "amcr" + return "bad" + + def check_oai_sets(): """Every OAI set in slovnicek: first page + resumptionToken paging.""" url = OAI_URL @@ -489,15 +531,14 @@ def check_oai_sets(): record(f"oai {name}", "FAIL", f"set {oai_set} returned no records", url) continue - # record shape: identifier, titles, dc payload - ok_shape = all( - r.find(".//oai_dc:dc", NS) is not None - and r.find(".//dc:identifier", NS) is not None - for r in records - ) - if not ok_shape: + # record shape: oai_dc payload with an identifier, or – the server + # fault of #89 / #96 – a readable oai_amcr payload on an oai_dc + # request, which the plugin tolerates + shapes = {_record_shape(r) for r in records} + if "bad" in shapes: record(f"oai {name}", "FAIL", - "record missing oai_dc:dc or dc:identifier", url) + "record in neither readable format (oai_dc:dc with " + "dc:identifier, or amcr:amcr with code and name)", url) continue token = root.find(".//oai:resumptionToken", NS) token_ok = True @@ -526,7 +567,12 @@ def check_oai_sets(): desc = f"{len(records)} records" if token is not None and token.text: desc += ", token page followed" - record(f"oai {name}", "OK", desc, url) + if "amcr" in shapes: + record(f"oai {name}", "DRIFT", + "server returns oai_amcr on oai_dc – the plugin " + f"reads it ({desc})", url) + else: + record(f"oai {name}", "OK", desc, url) else: record(f"oai {name}", "FAIL", "resumptionToken page returned no records", url) diff --git a/tests/smoke_test.py b/tests/smoke_test.py index b2bb19e..cd8798c 100644 --- a/tests/smoke_test.py +++ b/tests/smoke_test.py @@ -645,6 +645,106 @@ def upozorneni_obnovy(): dialog._REMEMBERED_STATE.clear() +_OAI_HEAD = ( + '' +) +_OAI_TAIL = '' +_AMCR_NS = 'xmlns:amcr="https://api.aiscr.cz/schema/amcr/2.2/"' + + +def _dc_record(identifier, *titles): + tituly = "".join(f"{t}" for t in titles) + return ( + "
x
" + '' + f"{identifier}{tituly}" + "
" + ) + + +def _amcr_record(entity, **fields): + obsah = "".join(f"{v}" for k, v in fields.items()) + return ( + "
x
" + f"{obsah}" + "
" + ) + + +def _deleted_record(): + return ('
x' + '
') + + +def _fetch_offline(codelists, internal_name, *records): + """fetch_set against one canned OAI page – no request leaves.""" + class Odpoved: + content = (_OAI_HEAD + "".join(records) + _OAI_TAIL).encode("utf-8") + + def raise_for_status(self): + pass + + puvodni = codelists.requests.get + codelists.requests.get = lambda *a, **k: Odpoved() + try: + data = codelists.fetch_set(codelists.BASE_URL_AMCR, internal_name, + "set") + finally: + codelists.requests.get = puvodni + return [(d["Kód"], d["Název"]) for d in data] + + +def ciselniky_oai(): + """ + fetch_set reads oai_dc and – the server fault of #89 / #96 – the + native oai_amcr payload, with the same values for both. + """ + c = amcr_viewer.amcr_codelists + pripady = [ + ("obdobi", [_dc_record("HES-000277", "AMČR - obdobi", + "rané středohradištní období")], + [("HES-000277", "rané středohradištní období")]), + ("obdobi", [_amcr_record("heslo", ident_cely="HES-000277", + nazev_heslare="obdobi", + heslo="rané středohradištní období", + zkratka="rs.3.ra")], + [("HES-000277", "rané středohradištní období")]), + ("pristupnost", [_dc_record("HES-000868", "archivář", "D")], + [("D", "archivář")]), + ("pristupnost", [_amcr_record("heslo", ident_cely="HES-000868", + heslo="archivář", zkratka="D"), + _amcr_record("heslo", ident_cely="HES-000869", + heslo="bez zkratky"), + _amcr_record("heslo", ident_cely="HES-000870", + heslo="dlouhá", zkratka="AB")], + [("D", "archivář")]), + ("kraj", [_amcr_record("ruian_kraj", kod="ruian-27", + nazev="Středočeský kraj")], + [("ruian-27", "Středočeský kraj")]), + ("okres", [_amcr_record("ruian_okres", kod="ruian-3713", + nazev="Znojmo", spz="ZN")], + [("Znojmo", "Znojmo")]), + ("katastr", [_amcr_record("ruian_katastr", kod="ruian-751910", + nazev="Soběšice")], + [("Soběšice", "Soběšice")]), + ("organizace", [_amcr_record("organizace", ident_cely="ORG-000128", + nazev="Galerie a muzeum Vysočiny", + nazev_zkraceny="GMV")], + [("ORG-000128", "Galerie a muzeum Vysočiny")]), + ("obdobi", [_amcr_record("projekt", ident_cely="X", nazev="Y"), + _amcr_record("heslo", ident_cely="HES-1"), + _deleted_record(), + "
x
" + "
"], + []), + ] + for interni, zaznamy, ocekavano in pripady: + vysledek = _fetch_offline(c, interni, *zaznamy) + assert vysledek == ocekavano, (interni, vysledek, ocekavano) + return f"{len(pripady)} případů oai_dc / oai_amcr" + + zkouska("scoped enumy", enumy) zkouska("UpdateCodelistsTask", uloha) zkouska("filtrační dialogy", dialogy) @@ -658,6 +758,7 @@ zkouska("upozornění obnovy", upozorneni_obnovy) zkouska("stav přihlášení", prihlasovaci_stav) zkouska("odhlášení", odhlaseni) zkouska("váha komponent", vaha_komponent) +zkouska("číselníky z OAI", ciselniky_oai) qgs.exitQgis() From 8c28b32157eb212411901bb04b6f9f0079e8f235 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 09:17:07 +0000 Subject: [PATCH 2/2] =?UTF-8?q?Nastavit=20datum=20vyd=C3=A1n=C3=AD=202.2.1?= =?UTF-8?q?=20na=202026-12-03?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Datum v changelogu metadata.txt a date-released v CITATION.cff podle dne vydání. Připraveno s pomocí AI (Claude Code). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013nPfHUicaDVqWsYEoQWhYD --- CITATION.cff | 2 +- amcr_viewer/metadata.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CITATION.cff b/CITATION.cff index 932b86f..952287f 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -26,4 +26,4 @@ abstract: >- Czech Republic (https://digiarchiv.aiscr.cz/). license: GPL-3.0 version: '2.2.1' -date-released: '2026-12-02' +date-released: '2026-12-03' diff --git a/amcr_viewer/metadata.txt b/amcr_viewer/metadata.txt index 6759b9e..d963adb 100644 --- a/amcr_viewer/metadata.txt +++ b/amcr_viewer/metadata.txt @@ -24,7 +24,7 @@ hasProcessingProvider=no # Uncomment the following line and add your changelog: changelog= Plný seznam změn v češtině je dostupný zde: https://github.com/ARUP-CAS/aiscr-qgis-amcr-viewer/releases/tag/v2.2.1 - v2.2.1 (2026-12-02) + v2.2.1 (2026-12-03) * Codelist update works again when the AMCR OAI server answers oai_dc requests with the native oai_amcr format (issues #89, #96) v2.2.0 (2026-10-02) * Tables for Akce and Lokality contain a field with feature weight, when Komponenty rendering is enabled; the weights of one documentation unit sum to 1 also with period/area filters